diff --git a/changes/stambha-arm64-preview.json b/changes/stambha-arm64-preview.json new file mode 100644 index 0000000..cde2147 --- /dev/null +++ b/changes/stambha-arm64-preview.json @@ -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." +} diff --git a/docs/arm64-preview.md b/docs/arm64-preview.md new file mode 100644 index 0000000..8e07c53 --- /dev/null +++ b/docs/arm64-preview.md @@ -0,0 +1,30 @@ +# 运行 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 内存。首次登录后,系统索引和缓存初始化会影响交互速度。 + +## 启动 + +在运行时页面导入 ARM64 预览包。它以 `stambha-hosted` 类型单独安装。Intel 虚拟机继续绑定选中的 x86-64 运行时,ARM 虚拟机自动使用已安装且兼容的 ARM64 运行时。 + +新建虚拟机时选择「macOS ARM64(预览)」。可从 Apple 下载 macOS 27.2.1 恢复镜像,下载支持暂停和续传,文件保存到数据目录的 `images/arm64`,完成后核对 SHA-256。本预览需要先将 IPSW 制作成 Stambha 启动介质。填写准备好的启动目录及对应的可写磁盘路径后即可创建和启动。GPU 加速窗口由运行时打开。 + +也可在 PowerShell 中操作。将示例路径替换成自己的文件位置。 + +```powershell +.\reims-go.exe runtime install .\reims-stambha-runtime-win-x64-stambha-arm64-preview.2.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 的苹果菜单中选择「关机」。客户端的停止操作会向来宾发送电源按键事件。若来宾没有退出,可回到桌面完成关机。只在来宾无响应时使用强制停止。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 69c7496..13c3e9e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -13,7 +13,7 @@ import { VMPage } from './components/VMPage' import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB } from './lib/format' import { initialWizardResolution } from './lib/displayResolution' -import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' +import { hasStambhaRuntime, isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' import { LogLine, appendLog, createLogLine } from './lib/logs' import { macOSMajor } from './macos/macosRelease' @@ -488,7 +488,8 @@ export const App: React.FC = () => { const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : [] const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false - const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime + const 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) @@ -595,7 +596,7 @@ export const App: React.FC = () => { try { const s = await api.GetState() setState(s) - setSetupStage(s?.active_runtime ? null : 'runtime') + setSetupStage(s?.active_runtime || hasStambhaRuntime(s?.runtimes) ? null : 'runtime') } catch (e) { console.warn('[app] GetState after setup failed:', e) fail(tr('failGeneric'), e) @@ -937,7 +938,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 diff --git a/frontend/src/components/AppDialogs.tsx b/frontend/src/components/AppDialogs.tsx index ac13144..67fd047 100644 --- a/frontend/src/components/AppDialogs.tsx +++ b/frontend/src/components/AppDialogs.tsx @@ -5,6 +5,7 @@ import { ElevationDialog } from './ElevationDialog' import { CloneDialog } from './CloneDialog' import { SendTextDialog } from './SendTextDialog' import { I18nKey, t } from '../i18n' +import { hasStambhaRuntime, STAMBHA_DRIVER_ID } from '../lib/endpoints' import { latestVMStats } from '../lib/vmStats' import { vmRefKey } from '../lib/vmRef' import type { PluginViewRoute } from '../lib/pluginViewRouter' @@ -111,6 +112,7 @@ export const AppDialogs: React.FC = (props) => { host={state.host} fixedModeSupported={fixedModeSupported} captureSupported={state.runtime_capture_supported} + initialDriverID={!state.active_runtime && hasStambhaRuntime(state.runtimes) ? STAMBHA_DRIVER_ID : undefined} tasks={tasks} draft={wizardDraft} onClose={onCloseWizard} diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 483eb90..b5c444e 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -1,6 +1,7 @@ import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react' import React, { Suspense, lazy, useEffect, useMemo, 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' @@ -66,6 +67,7 @@ interface Props { host: HostReport fixedModeSupported?: boolean captureSupported?: boolean + initialDriverID?: string tasks?: Task[] draft?: WizardDraft | null onClose: () => void @@ -93,7 +95,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI { mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' }, ] -export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => { +export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported = false, captureSupported = false, initialDriverID = BUILTIN_MACOS_DRIVER, tasks = [], draft, onClose, onSubmit }) => { const tr = (k: I18nKey, v?: Record) => 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. @@ -103,7 +105,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported const [issues, setIssues] = useState([]) const [cmdPreview, setCmdPreview] = useState('') const [drivers, setDrivers] = useState([]) - const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER) + const [driverID, setDriverID] = useState(initialDriverID) const [driverOpts, setDriverOpts] = useState>({}) const [driverCreating, setDriverCreating] = useState(false) const [dependencyBusy, setDependencyBusy] = useState(false) @@ -115,12 +117,13 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported api.ListDrivers().then((list) => { if (live) setDrivers(list ?? []) }).catch((e) => console.warn('[wizard] ListDrivers failed:', e)) return () => { live = false } }, []) + const armImageTask = [...tasks].reverse().find((task) => task.installer_kind === 'arm-ipsw') const activeDriver = drivers.find((d) => d.id === driverID) const isCustomDriver = driverID !== BUILTIN_MACOS_DRIVER && !!activeDriver const defaultGraphics = host.recommended_gpu ? 'reims-vgpu' : 'vmware-svga' const [opts, setOpts] = useState(draft?.opts ?? { - name: 'macos-tahoe', + name: initialDriverID === STAMBHA_DRIVER_ID ? 'macos-arm64' : 'macos-tahoe', dir: '', // 离线安装默认关闭网络,减少恢复环境依赖;用户仍可在第 4 步改为 NAT 或桥接。 source_mode: 'offline', @@ -294,7 +297,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported return ( - }
{err &&
{err}
} @@ -332,7 +335,7 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported value: d.id, label: locText(d.name, locale, d.id), }))} - onChange={(id) => { setDriverID(id); setErr('') }} + onChange={(id) => { setDriverID(id); setDriverOpts({}); setErr('') }} /> } /> @@ -346,6 +349,19 @@ export const CreateWizard: React.FC = ({ locale, host, fixedModeSupported control={ set({ name: e.target.value })} />} /> + {driverID === STAMBHA_DRIVER_ID && ( + + { + setErr('') + void api.DownloadARMImage().catch((e) => setErr(parseAppError(e).summary)) + }}>{tr('armRestoreDownload')} + } /> + {armImageTask?.status === 'done' && armImageTask.result && ( + {armImageTask.result}} /> + )} + + )} {activeDriver.create_schema && ( = ({ 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)} /> )} @@ -792,7 +814,7 @@ export const CreateWizard: React.FC = ({ 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() diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 634621f..57bf5dd 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -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 { Switch } from '../ui/settings' @@ -111,7 +112,7 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o
- {(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 && (

{tr('welcomeTitle')}

{tr('welcomeSub')}

@@ -228,43 +229,51 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o - {(runtimes ?? []).filter((rt) => !rt.active).map((rt) => ( -
-
-
- {rt.commit} - {latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && ( - {tr('runtimeLatestBadge')} + {(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 ( +
+
+
+ {stambha ? rt.manifest.name || rt.commit : rt.commit} + {(stambha || !rt.kind || rt.kind === 'reims-vgpu') && + {tr(stambha ? 'armRuntimeLabel' : 'x86RuntimeLabel')}} + {!stambha && latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && ( + {tr('runtimeLatestBadge')} + )} +
+
{rt.manifest.qemu_version?.replace(/^QEMU emulator version\s*/i, 'QEMU ')}
+
+
+ {confirmDelete === ref ? ( + <> + + + + ) : ( + <> + {!stambha && ( + + )} + } + disabled={removing !== ''} + onClick={() => setConfirmDelete(ref)} + /> + )}
-
{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}
-
- {confirmDelete === rt.commit ? ( - <> - - - - ) : ( - <> - - } - disabled={removing !== ''} - onClick={() => setConfirmDelete(rt.commit)} - /> - - )} -
-
- ))} + ) + })}
diff --git a/frontend/src/components/SchemaForm.tsx b/frontend/src/components/SchemaForm.tsx index 6e9c73f..9a6ecfd 100644 --- a/frontend/src/components/SchemaForm.tsx +++ b/frontend/src/components/SchemaForm.tsx @@ -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, patch: Record) => void hideGroupHeader?: boolean + pathFields?: Readonly> + 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 = ({ - 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 = ({ ) } + const pathField = pathFields?.[k] + if (pathField !== undefined) { + return ( +
+ setKey(k, e.target.value)} + /> + +
+ ) + } + return ( = ({ locale, locales, state, tr, onLocale, } const RuntimeStep: React.FC = ({ 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 [activating, setActivating] = useState('') diff --git a/frontend/src/i18n/domains/wizard.gen.ts b/frontend/src/i18n/domains/wizard.gen.ts index 38f9fe2..71cba16 100644 --- a/frontend/src/i18n/domains/wizard.gen.ts +++ b/frontend/src/i18n/domains/wizard.gen.ts @@ -2,6 +2,12 @@ import { registerBuiltinDomain } from '../runtime' export const wizardZh: Record = { + "armRestoreDownload": "下载 IPSW", + "armRestoreDownloaded": "已下载的 IPSW", + "armRestoreGroup": "ARM 恢复镜像", + "armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。", + "armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB", + "armRuntimeLabel": "ARM64 来宾", "commandToggle": "等效命令", "commandToggleHint": "在终端运行下面这条命令效果相同", "createNow": "创建", @@ -90,9 +96,16 @@ export const wizardZh: Record = { "wizardDriverGroup": "客体平台驱动", "wizardDriverType": "驱动类型", "wizardTitle": "新建虚拟机", + "x86RuntimeLabel": "x86-64 来宾", } export const wizardEn: Record = { + "armRestoreDownload": "Download IPSW", + "armRestoreDownloaded": "Downloaded IPSW", + "armRestoreGroup": "ARM restore image", + "armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.", + "armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB", + "armRuntimeLabel": "ARM64 guest", "commandToggle": "Equivalent command", "commandToggleHint": "Running this in a terminal does the same thing", "createNow": "Create", @@ -181,6 +194,7 @@ export const wizardEn: Record = { "wizardDriverGroup": "Guest driver", "wizardDriverType": "Driver", "wizardTitle": "New virtual machine", + "x86RuntimeLabel": "x86-64 guest", } registerBuiltinDomain(wizardZh, wizardEn) diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 6fe552c..8a246b1 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -68,6 +68,12 @@ export type I18nKey = | "appVersionTitle" | "appearance" | "appliesNextStart" + | "armRestoreDownload" + | "armRestoreDownloaded" + | "armRestoreGroup" + | "armRestoreMediaHint" + | "armRestoreVersion" + | "armRuntimeLabel" | "attachGuestTools" | "attachInstaller" | "audioBackendAuto" @@ -1189,4 +1195,5 @@ export type I18nKey = | "wizardBasics" | "wizardDriverGroup" | "wizardDriverType" - | "wizardTitle"; + | "wizardTitle" + | "x86RuntimeLabel"; diff --git a/frontend/src/lib/endpoints.ts b/frontend/src/lib/endpoints.ts index d14ae4c..79107a7 100644 --- a/frontend/src/lib/endpoints.ts +++ b/frontend/src/lib/endpoints.ts @@ -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' | '' diff --git a/frontend/src/lib/tasks.ts b/frontend/src/lib/tasks.ts index 407f41b..5dbe6e0 100644 --- a/frontend/src/lib/tasks.ts +++ b/frontend/src/lib/tasks.ts @@ -67,7 +67,7 @@ export function isInstallerTask(task: Task): boolean { } export function taskInstallerKind(task: Task): InstallerKind | '' { - if (task.installer_kind === 'offline' || task.installer_kind === 'online') return task.installer_kind + if (task.installer_kind === 'offline' || task.installer_kind === 'online' || task.installer_kind === 'arm-ipsw') return task.installer_kind if (task.kind === 'installer-download') return 'offline' if (task.kind === 'recovery-download') return 'online' return '' diff --git a/frontend/src/macos/InstallersPage.tsx b/frontend/src/macos/InstallersPage.tsx index 15d4e91..2b80f85 100644 --- a/frontend/src/macos/InstallersPage.tsx +++ b/frontend/src/macos/InstallersPage.tsx @@ -246,6 +246,9 @@ export const InstallersPage: React.FC = ({ active, } } + if (kind === 'arm-ipsw') { + return { key: `active-${task.id}`, title: task.subject, version, kind: 'ipsw', active } + } return { key: `active-${taskInstallerKey(task) || task.id}`, title: formatOnlineTitle(version), diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 43d6106..0f45f59 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -126,7 +126,7 @@ export type CreateOpts = Model & { type TaskStatus = 'running' | 'done' | 'failed' | 'canceled' -export type InstallerKind = 'offline' | 'online' +export type InstallerKind = 'offline' | 'online' | 'arm-ipsw' export type InstallerPhase = 'queued' | 'downloading' /** A tracked long-running job pushed as "reims:task" (internal/app/tasks.go). */ diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index e066de7..37cd9ab 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -72,6 +72,8 @@ export function DownloadAppUpdate():Promise; export function DownloadInstaller(arg1:string):Promise; +export function DownloadARMImage():Promise; + export function EjectInstaller(arg1:string,arg2:string):Promise; export function EnablePlugin(arg1:string,arg2:boolean):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index eeef3a9..9b3c644 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -118,6 +118,10 @@ export function DownloadAppUpdate() { return window['go']['app']['App']['DownloadAppUpdate'](); } +export function DownloadARMImage() { + return window['go']['app']['App']['DownloadARMImage'](); +} + export function DownloadInstaller(arg1) { return window['go']['app']['App']['DownloadInstaller'](arg1); } diff --git a/internal/app/app.go b/internal/app/app.go index 57c101c..627960b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -122,31 +122,31 @@ type App struct { trayMgr *tray.Manager allowQuit bool launchPrevDataRoot string - quitMode string - vmStarts sync.WaitGroup - lastVMs []driver.VMListItem - lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale - lastVMListErr error - pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick - diskPaths map[string]cachedDiskPath - procSamples map[string]host.ProcessSample - recentLogs []string - needsSetup bool - root dataroot.Status // how the current data folder opened (dataroot_flow.go) - launch cli.WindowArgs // flags this window was started with (window_launch.go) - trayIcon []byte // embedded PNG passed in from package main - logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go) - pluginMgr *plugin.Manager - pluginMarket *market.MarketClient - controlServer *control.Server - driverRouter *driver.Router - vmStateTable *driver.StateTable - lifecycleSvc *vmlifecycle.Service - runtimeKinds *rt.KindRegistry - uiHealth uiHealthState - themeMode string - vmClosePrompts sync.Map - displayHost vmDisplayHost + quitMode string + vmStarts sync.WaitGroup + lastVMs []driver.VMListItem + lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale + lastVMListErr error + pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick + diskPaths map[string]cachedDiskPath + procSamples map[string]host.ProcessSample + recentLogs []string + needsSetup bool + root dataroot.Status // how the current data folder opened (dataroot_flow.go) + launch cli.WindowArgs // flags this window was started with (window_launch.go) + trayIcon []byte // embedded PNG passed in from package main + logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go) + pluginMgr *plugin.Manager + pluginMarket *market.MarketClient + controlServer *control.Server + driverRouter *driver.Router + vmStateTable *driver.StateTable + lifecycleSvc *vmlifecycle.Service + runtimeKinds *rt.KindRegistry + uiHealth uiHealthState + themeMode string + vmClosePrompts sync.Map + displayHost vmDisplayHost displayPlacements sync.Map @@ -191,15 +191,15 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) { needsSetup: needsSetup, launch: launch, launchPrevDataRoot: launchPrevDataRoot, - trayIcon: trayIcon, - transitions: make(map[string]string), - pendingChanges: make(map[string][]PendingChange), - rebootWatchers: make(map[string]rebootWatcherEntry), - pollWake: make(chan struct{}, 1), - diskPaths: make(map[string]cachedDiskPath), - procSamples: make(map[string]host.ProcessSample), - uiHealth: uiHealthState{windowHidden: launch.Background}, - displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay}, + trayIcon: trayIcon, + transitions: make(map[string]string), + pendingChanges: make(map[string][]PendingChange), + rebootWatchers: make(map[string]rebootWatcherEntry), + pollWake: make(chan struct{}, 1), + diskPaths: make(map[string]cachedDiskPath), + procSamples: make(map[string]host.ProcessSample), + uiHealth: uiHealthState{windowHidden: launch.Background}, + displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay}, } a.hostAPI.app = a a.hostAPI.pluginFiles = make(map[string]pluginFileGrant) @@ -822,6 +822,10 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) { } return nil, err } + if inst.Kind == rt.StambhaKind { + a.emitLog("runtime", fmt.Sprintf("Runtime %s installed -> %s", inst.Commit, inst.Dir)) + return inst, nil + } if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil { inst.Active = false a.emitLog("runtime", err.Error()) diff --git a/internal/app/arm_image.go b/internal/app/arm_image.go new file mode 100644 index 0000000..abc5564 --- /dev/null +++ b/internal/app/arm_image.go @@ -0,0 +1,80 @@ +package app + +import ( + "context" + "errors" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/Nwflower/reims-go/internal/fetch" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/macos/installer" + "github.com/Nwflower/reims-go/internal/netproxy" +) + +const ( + armImageBuild = "26B131" + armImageName = "UniversalMac_27.2.1_26B131_Restore.ipsw" + armImageURL = "https://updates.cdn-apple.com/2026FallFCS/c202a724-db7e-4d56-917b-110aa0226507/" + armImageName + armImageSHA = "233e85a09887579d47d0b195e7db72be7f204261059c6946f719acf6b300814f" + armImageSize = int64(25595954706) +) + +// DownloadARMImage fetches the pinned ARM restore image from Apple into the user data folder. +func (a *App) DownloadARMImage() (string, error) { + cfg := a.runtimeConfig() + if err := cfg.EnsureDirs(); err != nil { + return "", err + } + final := filepath.Join(cfg.ImagesDir(), "arm64", armImageName) + if err := os.MkdirAll(filepath.Dir(final), 0o755); err != nil { + return "", err + } + a.ensureTaskEmitter() + var ctx context.Context + var cancel context.CancelFunc + run, id, owned := installerDownloads.reserveOrFind("arm-ipsw", armImageBuild, "installer-download", func(initialPhase string) string { + ctx, cancel = context.WithCancel(a.baseCtx()) + return tasks.startWithInstaller("installer-download", "macOS 27.2.1 · ARM64", "", "arm-ipsw", armImageBuild, initialPhase, cancel) + }) + if !owned { + return id, nil + } + go func() { + defer cancel() + client := netproxy.NewClient() + client.Timeout = 0 + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 || req.URL.Scheme != "https" || req.URL.Hostname() != "updates.cdn-apple.com" { + return errors.New("ARM restore image download redirected outside Apple's update server") + } + return nil + } + path, err := fetch.ResumeDirect(ctx, client, armImageURL, final, armImageSize, armImageSHA, func(done, total int64) { + update := host.Update{Kind: host.KindProgress, Done: done, Total: total, Percent: percent(done, total)} + tasks.update(id, update) + run.publish(update) + }, fetch.ResumeOptions{MaxBytes: armImageSize, StallTimeout: 45 * time.Second}) + if err == nil { + if info, statErr := os.Stat(path); statErr != nil { + err = statErr + } else if info.Size() != armImageSize { + err = errors.New("ARM restore image size does not match the pinned build") + } + } + if err != nil && ctx.Err() != nil { + err = ctx.Err() + } + var result *installer.Result + if err == nil { + result = &installer.Result{Image: path} + } else { + path = "" + } + installerDownloads.complete(run, result, err) + tasks.finish(id, path, err) + }() + return id, nil +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index b65e672..573620e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -305,8 +305,10 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { } return err } - if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil { - return err + if inst.Kind != rt.StambhaKind { + if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil { + return err + } } fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir)) return nil @@ -409,11 +411,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 ] [--force] ") + } + return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force) case "suspend": driverID, name, err := parseVMTarget(args) if err != nil { @@ -511,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, disk) if err := fs.Parse(args); err != nil { return err } @@ -518,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 := 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) @@ -529,8 +541,11 @@ func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []s if err != nil { return err } - if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" { - return fmt.Errorf("--disk, --disk-mode, and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID) + if strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" { + return fmt.Errorf("--disk-mode and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID) + } + if drv.ID() != driver.BuiltinStambhaDriverID && strings.TrimSpace(*disk) != "" { + return fmt.Errorf("--disk is not supported by the %s driver", drv.ID()) } req := driver.CreateRequest{ DriverID: drv.ID(), @@ -542,6 +557,14 @@ 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 + req.Options["raw_disk"] = *disk + 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) } @@ -569,13 +592,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, nil) if err := fs.Parse(args); err != nil { return err } if fs.NArg() < 1 { return fmt.Errorf("usage: reims-go vm set [--driver ] [flags] ") } - 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 } @@ -605,6 +632,51 @@ 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, disk *string) 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)") + sharedDisk := disk != nil + if !sharedDisk { + 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") + flags := 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 }}, + } + if sharedDisk { + delete(flags, "disk") + } + return flags +} + +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("", " ") diff --git a/internal/cli/stambha_test.go b/internal/cli/stambha_test.go new file mode 100644 index 0000000..59512b9 --- /dev/null +++ b/internal/cli/stambha_test.go @@ -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) + } +} diff --git a/internal/cli/start.go b/internal/cli/start.go index fd05db8..2a14cb0 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -103,13 +103,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 { diff --git a/internal/driver/driver.go b/internal/driver/driver.go index 4418435..5312112 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -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 diff --git a/internal/macos/guest/register.go b/internal/macos/guest/register.go index adfdee7..abccb73 100644 --- a/internal/macos/guest/register.go +++ b/internal/macos/guest/register.go @@ -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))) } diff --git a/internal/macos/guest/stambha.go b/internal/macos/guest/stambha.go new file mode 100644 index 0000000..b0a9b67 --- /dev/null +++ b/internal/macos/guest/stambha.go @@ -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 + }, + } +} diff --git a/internal/macos/stambhadriver/stambha.go b/internal/macos/stambhadriver/stambha.go new file mode 100644 index 0000000..3ee8141 --- /dev/null +++ b/internal/macos/stambhadriver/stambha.go @@ -0,0 +1,1236 @@ +package stambhadriver + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/filelock" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/reims" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/qmp" + rt "github.com/Nwflower/reims-go/internal/runtime" + "github.com/Nwflower/reims-go/internal/vmstart" +) + +const ( + StambhaDriverID = driver.BuiltinStambhaDriverID + StambhaRuntimeKind = rt.StambhaKind + stambhaAPI = "0.1.0" + stambhaProfileName = "stambha.json" + stambhaHostedReimsBase = "0x300000000" + stambhaHostedReimsIRQ = "auto" + stambhaHostedIRQMode = "poll" + stambhaStagedMediaDir = "boot-media" + stambhaEnginePath = "bin/stambha-engine.exe" + stambhaQEMUPath = "qemu/bin/qemu-system-x86_64.exe" + stambhaQEMUImgPath = "qemu/bin/qemu-img.exe" + stambhaEFIPath = "firmware/stambha.efi" + stambhaFirmwareCode = "firmware/edk2-code.fd" + stambhaFirmwareVars = "firmware/edk2-vars.fd" +) + +var ( + stambhaName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}$`) + stambhaPCIDeviceID = regexp.MustCompile(`^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$`) +) + +type StambhaDriver struct{ config func() config.Config } + +var ( + _ driver.Driver = (*StambhaDriver)(nil) + _ driver.LogDriver = (*StambhaDriver)(nil) +) + +func StambhaRuntimeFiles() []string { + return []string{stambhaEnginePath, stambhaQEMUPath, stambhaQEMUImgPath, stambhaEFIPath, stambhaFirmwareCode, stambhaFirmwareVars} +} + +type stambhaProfile struct { + BootVolume string `json:"boot_volume,omitempty"` + USBImage string `json:"usb_image,omitempty"` + Disk string `json:"raw_disk,omitempty"` + MemoryMiB int `json:"memory_mib"` + CPUs int `json:"cpus"` + Display bool `json:"display"` + Accel string `json:"accelerator,omitempty"` + MediaBus string `json:"media_bus,omitempty"` + HostedGPU bool `json:"hosted_gpu,omitempty"` + GPU string `json:"gpu,omitempty"` + StelaArgs string `json:"stela_args,omitempty"` +} + +type stambhaPlan struct { + API string `json:"runtime_api"` + Exe string `json:"exe_path"` + Args []string `json:"args"` + Dir string `json:"work_dir"` + Serial string `json:"serial_log"` +} + +func NewStambhaDriver(cfg func() config.Config) *StambhaDriver { return &StambhaDriver{config: cfg} } +func (*StambhaDriver) ID() string { return StambhaDriverID } +func (*StambhaDriver) DisplayName() plugin.LocalizedText { + return plugin.LocalizedText{ZhCN: "macOS ARM64(预览)", EnUS: "macOS ARM64 (Preview)"} +} +func (*StambhaDriver) RuntimeKind() string { return StambhaRuntimeKind } +func (*StambhaDriver) RuntimeAPIRange() string { return stambhaAPI } +func (*StambhaDriver) Capabilities() []string { + return []string{"guest.arm64", "serial_log", driver.CapAffinity} +} +func (d *StambhaDriver) CreateSchema() *plugin.SettingsSchema { + minCPUs, maxCPUs := float64(1), float64(64) + return &plugin.SettingsSchema{Scope: "vm", Order: []string{"boot_volume", "usb_image", "media_bus", "raw_disk", "memory", "cpus", "accelerator", "hosted_gpu", "gpu", "display", "stela_args"}, + Properties: map[string]plugin.SettingProperty{ + "boot_volume": {Type: "string", Title: plugin.LocalizedText{ZhCN: "启动介质目录", EnUS: "Boot media directory"}}, + "usb_image": {Type: "string", Title: plugin.LocalizedText{ZhCN: "USB 镜像(RAW)", EnUS: "USB image (RAW)"}}, + "media_bus": {Type: "string", Title: plugin.LocalizedText{ZhCN: "启动镜像总线", EnUS: "Boot image bus"}, Default: "usb", Enum: []string{"usb", "nvme"}}, + "raw_disk": {Type: "string", Title: plugin.LocalizedText{ZhCN: "可写虚拟磁盘(RAW / QCOW2)", EnUS: "Writable virtual disk (RAW / QCOW2)"}}, + "memory": {Type: "string", Title: plugin.LocalizedText{ZhCN: "内存", EnUS: "Memory"}, Default: "16G"}, + "cpus": {Type: "integer", Title: plugin.LocalizedText{ZhCN: "执行核心数", EnUS: "CPU cores"}, Default: 8, Minimum: &minCPUs, Maximum: &maxCPUs}, + "accelerator": {Type: "string", Title: plugin.LocalizedText{ZhCN: "CPU 加速后端", EnUS: "CPU accelerator"}, Default: "whpx", Enum: []string{"tcg", "whpx"}}, + "hosted_gpu": {Type: "boolean", Title: plugin.LocalizedText{ZhCN: "托管 Reims Metal 显卡加速", EnUS: "Hosted Reims Metal GPU acceleration"}, Default: true}, + "gpu": {Type: "string", Title: plugin.LocalizedText{ZhCN: "显卡选择器(auto / VID:DID / ICD)", EnUS: "GPU selector (auto / VID:DID / ICD)"}, Default: "auto"}, + "display": {Type: "boolean", Title: plugin.LocalizedText{ZhCN: "显示窗口", EnUS: "Display window"}, Default: true}, + "stela_args": {Type: "string", Title: plugin.LocalizedText{ZhCN: "附加 Stambha 启动参数", EnUS: "Extra Stambha boot arguments"}}, + }, + } +} +func (d *StambhaDriver) SettingsSchema() *plugin.SettingsSchema { return d.CreateSchema() } + +func stambhaRoot(cfg config.Config) string { return filepath.Join(cfg.XDGDataDir(), "stambha", "vms") } + +func (d *StambhaDriver) directory(name string) (string, error) { + if !stambhaName.MatchString(name) { + return "", fmt.Errorf("invalid Stambha VM name %q", name) + } + return filepath.Abs(filepath.Join(stambhaRoot(d.config()), name)) +} + +func stambhaOptions(options map[string]any) (stambhaProfile, error) { + raw, err := json.Marshal(options) + if err != nil { + return stambhaProfile{}, err + } + input := struct { + stambhaProfile + Memory string `json:"memory"` + }{stambhaProfile: stambhaProfile{CPUs: 8, Display: true, HostedGPU: true}, Memory: "16G"} + if err := json.Unmarshal(raw, &input); err != nil { + return stambhaProfile{}, err + } + size, ok := reims.ParseSizeGB(input.Memory) + if !ok || size < 1 || size > 256 || input.CPUs < 1 || input.CPUs > 64 { + return stambhaProfile{}, errors.New("Stambha requires 1–256 GB of memory and 1–64 cores") + } + input.MemoryMiB = int(size * 1024) + switch input.Accel { + case "": + input.Accel = "whpx" + case "tcg", "whpx": + default: + return stambhaProfile{}, fmt.Errorf("unsupported Stambha accelerator %q", input.Accel) + } + switch input.MediaBus { + case "": + input.MediaBus = "usb" + case "usb", "nvme": + default: + return stambhaProfile{}, fmt.Errorf("unsupported Stambha boot image bus %q", input.MediaBus) + } + input.BootVolume = strings.TrimSpace(input.BootVolume) + input.USBImage = strings.TrimSpace(input.USBImage) + input.Disk = strings.TrimSpace(input.Disk) + input.GPU = strings.TrimSpace(input.GPU) + if input.GPU == "" && input.HostedGPU { + input.GPU = "auto" + } + if err := validateStambhaGPU(input.GPU); err != nil { + return stambhaProfile{}, err + } + input.StelaArgs = strings.TrimSpace(input.StelaArgs) + if err := validateStambhaArgs(input.StelaArgs, input.BootVolume != "", input.USBImage != ""); err != nil { + return stambhaProfile{}, err + } + return input.stambhaProfile, nil +} + +func validateStambhaGPU(gpu string) error { + if gpu == "" || strings.EqualFold(gpu, "auto") || stambhaPCIDeviceID.MatchString(gpu) { + return nil + } + if strings.HasSuffix(strings.ToLower(gpu), ".json") { + info, err := os.Stat(gpu) + if err != nil { + return fmt.Errorf("invalid Stambha Vulkan ICD %q: %w", gpu, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("invalid Stambha Vulkan ICD %q", gpu) + } + return nil + } + return fmt.Errorf("unsupported Stambha GPU selector %q (expected auto, VID:DID, or Vulkan ICD .json)", gpu) +} + +func validateStambhaArgs(args string, hasBootVolume, hasUSBImage bool) error { + if args == "" { + return nil + } + if strings.ContainsAny(args, "\r\n\x00") { + return errors.New("Stambha boot arguments must be a single line") + } + if !hasBootVolume && hasUSBImage { + return errors.New("stela_args requires a boot_volume directory") + } + return nil +} + +func resolveStambhaRuntime(cfg *config.Config) (rt.Installed, error) { + list, err := rt.ListByKind(cfg, StambhaRuntimeKind) + if err != nil { + return rt.Installed{}, err + } + var firstError error + for _, inst := range list { + if err := rt.CheckCompatibility(StambhaRuntimeKind, stambhaAPI, inst); err != nil { + if firstError == nil { + firstError = err + } + continue + } + valid := true + for _, rel := range StambhaRuntimeFiles() { + info, err := os.Stat(filepath.Join(inst.Dir, filepath.FromSlash(rel))) + if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { + if firstError == nil { + firstError = fmt.Errorf("Stambha runtime %s is missing %s", inst.Commit, rel) + } + valid = false + break + } + } + if valid { + return inst, nil + } + } + if firstError != nil { + return rt.Installed{}, firstError + } + return rt.Installed{}, fmt.Errorf("import a Stambha ARM64 runtime before starting this VM: %w", rt.ErrNoActiveRuntime) +} + +func (d *StambhaDriver) launchPlan(ctx context.Context, vmDir string, profile stambhaProfile) (stambhaPlan, []string, string, string, error) { + cfg := d.config() + inst, err := resolveStambhaRuntime(&cfg) + if err != nil { + return stambhaPlan{}, nil, "", "", err + } + engine := filepath.Join(inst.Dir, stambhaEnginePath) + qemu := filepath.Join(inst.Dir, stambhaQEMUPath) + qemuShareDir := filepath.Join(inst.Dir, "qemu", "share") + if info, err := os.Stat(filepath.Join(qemuShareDir, "qemu")); err == nil && info.IsDir() { + qemuShareDir = filepath.Join(qemuShareDir, "qemu") + } + qemuBinDir := filepath.Dir(qemu) + firmware := filepath.Join(inst.Dir, stambhaFirmwareCode) + vars := filepath.Join(inst.Dir, stambhaFirmwareVars) + args := []string{"boot-plan", "--qemu", qemu, "--firmware-code", firmware, + "--firmware-vars", vars, "--vm-dir", vmDir, "--memory-mib", strconv.Itoa(profile.MemoryMiB), "--cpus", strconv.Itoa(profile.CPUs)} + if (profile.BootVolume == "") == (profile.USBImage == "") { + return stambhaPlan{}, nil, "", "", errors.New("select one Stambha boot media directory or RAW USB image") + } + bootVol := profile.BootVolume + if bootVol != "" { + staged, err := stageStambhaBootVolume(bootVol, vmDir, filepath.Join(inst.Dir, stambhaEFIPath), profile) + if err != nil { + return stambhaPlan{}, nil, "", "", fmt.Errorf("stage Stambha boot media: %w", err) + } + bootVol = staged + } + if bootVol != "" { + args = append(args, "--boot-volume", bootVol) + } + if profile.USBImage != "" { + args = append(args, "--usb-image", profile.USBImage) + } + if profile.Disk != "" { + args = append(args, "--disk", profile.Disk) + } + // Under hosted GPU, Reims owns the native Vulkan window and requires QEMU -display none. + if profile.Display && !profile.HostedGPU { + args = append(args, "--display") + } + env := rt.BuildChildEnv(&cfg, inst) + cmd := exec.CommandContext(ctx, engine, args...) + cmd.Env = env + stambhaHideConsole(cmd) + out, err := cmd.Output() + if err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) { + err = fmt.Errorf("%w: %s", err, strings.TrimSpace(string(exit.Stderr))) + } + return stambhaPlan{}, nil, "", "", fmt.Errorf("prepare Stambha boot: %w", err) + } + var plan stambhaPlan + if err := json.Unmarshal(out, &plan); err != nil { + return plan, nil, "", "", fmt.Errorf("decode Stambha launch plan: %w", err) + } + if plan.API != stambhaAPI || !sameStambhaPath(plan.Exe, qemu) || !sameStambhaPath(plan.Dir, vmDir) || + !sameStambhaPath(plan.Serial, filepath.Join(vmDir, "serial.log")) || len(plan.Args) == 0 { + return plan, nil, "", "", errors.New("invalid Stambha launch plan") + } + return plan, env, qemuBinDir, qemuShareDir, nil +} + +func sameStambhaPath(a, b string) bool { + return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) +} + +func stambhaValidateMedia(vmDir string, profile *stambhaProfile) error { + if (profile.BootVolume == "") == (profile.USBImage == "") { + return errors.New("select one Stambha boot media directory or RAW USB image") + } + if profile.Disk == "" { + return errors.New("select a writable RAW or QCOW2 virtual disk") + } + for _, src := range []struct { + path *string + dir bool + }{ + {&profile.BootVolume, true}, {&profile.USBImage, false}, {&profile.Disk, false}, + } { + if *src.path == "" { + continue + } + path, err := filepath.Abs(*src.path) + if err != nil { + return err + } + item, err := os.Stat(path) + if err != nil { + return err + } + if (src.dir && !item.IsDir()) || (!src.dir && (!item.Mode().IsRegular() || item.Size() == 0)) { + return fmt.Errorf("invalid Stambha media %q", path) + } + if src.dir { + realPath, err := filepath.EvalSymlinks(path) + if err != nil && !errors.Is(err, os.ErrPermission) { + return fmt.Errorf("resolve Stambha boot folder %q: %w", path, err) + } + if err == nil { + path = realPath + } + } + *src.path = path + } + if profile.BootVolume != "" { + path := filepath.Join(profile.BootVolume, "EFI", "stela", "stela.cfg") + if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() || info.Size() == 0 { + return errors.New("the boot folder must contain EFI/stela/stela.cfg") + } + } + if profile.USBImage != "" { + disk, diskErr := os.Stat(profile.Disk) + media, mediaErr := os.Stat(profile.USBImage) + if diskErr != nil || mediaErr != nil { + return errors.Join(diskErr, mediaErr) + } + if os.SameFile(disk, media) { + return errors.New("the installer image and writable virtual disk must be different files") + } + } + return ensureStambhaMediaOutsideStage(vmDir, *profile) +} + +func ensureStambhaMediaOutsideStage(vmDir string, profile stambhaProfile) error { + stage := filepath.Join(vmDir, stambhaStagedMediaDir) + paths := []string{profile.BootVolume, profile.USBImage, profile.Disk} + conflicts := func(root, selected string) bool { + return selected != "" && stambhaPathWithin(root, selected) + } + for _, path := range paths { + if conflicts(stage, path) { + return errors.New("select boot media and a virtual disk outside the VM's boot-media folder") + } + } + info, err := os.Lstat(stage) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("the VM's boot-media folder must be a regular directory") + } + realStage, err := filepath.EvalSymlinks(stage) + if err != nil { + return err + } + for _, path := range paths { + if path == "" { + continue + } + realPath, err := filepath.EvalSymlinks(path) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + return err + } + if conflicts(realStage, realPath) { + return errors.New("select boot media and a virtual disk outside the VM's boot-media folder") + } + } + return nil +} + +func (d *StambhaDriver) ValidateCreate(_ context.Context, req driver.CreateRequest) []driver.ValidationIssue { + dir, err := d.directory(req.Name) + if err != nil { + return []driver.ValidationIssue{{Field: "name", Message: err.Error()}} + } + if req.Dir != "" { + return []driver.ValidationIssue{{Field: "dir", Message: "Stambha stores its VM profile in the data folder"}} + } + profile, err := stambhaOptions(req.Options) + if err == nil { + err = stambhaValidateMedia(dir, &profile) + } + if err != nil { + return []driver.ValidationIssue{{Field: "boot_volume", Message: err.Error()}} + } + return nil +} + +func (d *StambhaDriver) Create(ctx context.Context, req driver.CreateRequest, stdout, _ io.Writer) error { + if issues := d.ValidateCreate(ctx, req); len(issues) > 0 { + return errors.New(issues[0].Message) + } + profile, _ := stambhaOptions(req.Options) + dir, _ := d.directory(req.Name) + if err := stambhaValidateMedia(dir, &profile); err != nil { + return err + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + release, err := lockStambhaDir(dir) + if err != nil { + return err + } + defer release() + if _, err := os.Lstat(filepath.Join(dir, stambhaProfileName)); err == nil { + return fmt.Errorf("Stambha VM %q already exists", req.Name) + } else if !errors.Is(err, os.ErrNotExist) { + return err + } + if err := driver.WriteOwnerDriver(dir, d.ID()); err != nil { + return err + } + if err := driver.WriteVMRecord(dir, stambhaProfileName, profile); err != nil { + _ = os.Remove(filepath.Join(dir, driver.OwnerMarkerFile)) + return err + } + if stdout != nil { + fmt.Fprintf(stdout, "Created %s\n", req.Name) + } + return nil +} + +func readStambhaProfile(dir string) (stambhaProfile, error) { + var profile stambhaProfile + raw, err := os.ReadFile(filepath.Join(dir, stambhaProfileName)) + if err == nil { + err = json.Unmarshal(raw, &profile) + } + return profile, err +} + +func (d *StambhaDriver) List(ctx context.Context) ([]driver.VMInfo, error) { + items, err := os.ReadDir(stambhaRoot(d.config())) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, err + } + var found []driver.VMInfo + for _, item := range items { + if !item.IsDir() { + continue + } + info, err := d.Show(ctx, item.Name()) + if err == nil { + found = append(found, info) + } + } + return found, nil +} + +func (d *StambhaDriver) Show(_ context.Context, name string) (driver.VMInfo, error) { + dir, err := d.directory(name) + if err != nil { + return driver.VMInfo{}, err + } + profile, err := readStambhaProfile(dir) + if err != nil { + return driver.VMInfo{}, err + } + proc, err := stambhaLiveProcess(dir) + state := "stopped" + var pid *int + if err != nil { + state = "broken" + } else if proc.PID != 0 { + state = "running" + pid = &proc.PID + } + return driver.VMInfo{Name: name, DriverID: d.ID(), State: state, PID: pid, CPUs: profile.CPUs, + Memory: fmt.Sprintf("%dM", profile.MemoryMiB), DiskSummary: profile.Disk, DiskPath: profile.Disk, Directory: dir, + GuestOS: &driver.GuestOSInfo{Family: driver.GuestFamilyMacOS, Arch: "arm64"}, + Capabilities: d.Capabilities(), DriverData: map[string]any{ + "boot_volume": profile.BootVolume, + "usb_image": profile.USBImage, + "media_bus": profile.MediaBus, + "raw_disk": profile.Disk, + "memory": fmt.Sprintf("%dM", profile.MemoryMiB), + "cpus": profile.CPUs, + "display": profile.Display, + "accelerator": profile.Accel, + "hosted_gpu": profile.HostedGPU, + "gpu": profile.GPU, + "stela_args": profile.StelaArgs, + "serial_log": filepath.Join(dir, "serial.log"), + }}, nil +} + +func (d *StambhaDriver) ValidateSet(ctx context.Context, req driver.SetRequest) []driver.ValidationIssue { + info, err := d.Show(ctx, req.Name) + if err == nil && info.State != "stopped" { + err = errors.New("stop the Stambha VM before editing it") + } + if err == nil { + _, err = d.updatedProfile(info.Directory, req.Changes) + } + if err != nil { + return []driver.ValidationIssue{{Field: "settings", Message: err.Error()}} + } + return nil +} + +func (d *StambhaDriver) updatedProfile(dir string, changes map[string]any) (stambhaProfile, error) { + profile, err := readStambhaProfile(dir) + if err != nil { + return profile, err + } + options := map[string]any{ + "boot_volume": profile.BootVolume, + "usb_image": profile.USBImage, + "raw_disk": profile.Disk, + "memory": fmt.Sprintf("%dM", profile.MemoryMiB), + "cpus": profile.CPUs, + "display": profile.Display, + "accelerator": profile.Accel, + "media_bus": profile.MediaBus, + "hosted_gpu": profile.HostedGPU, + "gpu": profile.GPU, + "stela_args": profile.StelaArgs, + } + for key, value := range changes { + if _, ok := options[key]; !ok { + return profile, fmt.Errorf("unknown Stambha setting %q", key) + } + options[key] = value + } + profile, err = stambhaOptions(options) + if err == nil { + err = stambhaValidateMedia(dir, &profile) + } + return profile, err +} + +func (d *StambhaDriver) Set(_ context.Context, req driver.SetRequest, _, _ io.Writer) error { + return d.withVM(req.Name, func(dir string, proc stambhaProcess) error { + if proc.PID != 0 { + return errors.New("stop the Stambha VM before editing it") + } + profile, err := d.updatedProfile(dir, req.Changes) + if err != nil { + return err + } + return driver.WriteVMRecord(dir, stambhaProfileName, profile) + }) +} + +func (d *StambhaDriver) withVM(name string, fn func(string, stambhaProcess) error) error { + dir, err := d.directory(name) + if err != nil { + return err + } + release, err := lockStambhaDir(dir) + if err != nil { + return err + } + defer release() + if _, err := os.Stat(filepath.Join(dir, stambhaProfileName)); err != nil { + return err + } + proc, err := stambhaLiveProcess(dir) + if err != nil { + return err + } + return fn(dir, proc) +} + +func lockStambhaDir(dir string) (func(), error) { + lock, err := os.OpenFile(filepath.Join(dir, ".stambha.lock"), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, err + } + ok, err := filelock.TryLock(lock) + if err != nil || !ok { + _ = lock.Close() + if err == nil { + err = errors.New("another Stambha operation is in progress") + } + return nil, err + } + return func() { + filelock.Unlock(lock) + _ = lock.Close() + }, nil +} + +func (d *StambhaDriver) socketPath(dir string) (string, error) { + cfg := d.config() + cache, _ := os.UserCacheDir() + return stambhaSocketPath(dir, cfg.TempDir(), cache) +} + +func stambhaSocketPath(vmDir string, fallbackDirs ...string) (string, error) { + const maxSocketBytes = 103 + if path := qmp.SocketPath(vmDir); len(path) <= maxSocketBytes { + return path, nil + } + hash := sha256.Sum256([]byte(strings.ToLower(filepath.Clean(vmDir)))) + name := fmt.Sprintf("%x.qmp", hash[:8]) + for _, root := range fallbackDirs { + if root == "" || !filepath.IsAbs(root) { + continue + } + path := filepath.Join(root, "reims-q", name) + if len(path) <= maxSocketBytes { + return path, nil + } + } + return "", errors.New("no local folder has a short enough path for the QEMU control socket") +} + +func checkStambhaDiskOwners(name, disk string, vms []driver.VMInfo) error { + current, err := os.Stat(disk) + if err != nil { + return err + } + for _, vm := range vms { + if strings.EqualFold(vm.Name, name) || (vm.State != "running" && vm.State != "broken") { + continue + } + if vm.DiskPath == "" { + continue + } + other, err := os.Stat(vm.DiskPath) + if err == nil && os.SameFile(current, other) { + return fmt.Errorf("Stambha VM %q may still be using the same writable disk", vm.Name) + } + if sameStambhaPath(disk, vm.DiskPath) { + return fmt.Errorf("Stambha VM %q may still be using the same writable disk", vm.Name) + } + } + return nil +} + +func (d *StambhaDriver) Start(ctx context.Context, req driver.StartRequest) (driver.StartResult, error) { + name, stdout := req.Ref.Name, req.Stdout + err := d.withVM(name, func(dir string, proc stambhaProcess) error { + if proc.PID != 0 { + return fmt.Errorf("%s is already running", name) + } + profile, err := readStambhaProfile(dir) + if err != nil { + return err + } + memoryGB := float64(profile.MemoryMiB) / 1024 + if available, ok := host.CommitAvailGB(); ok && memoryGB+host.StartMarginGB > available { + cfg := d.config() + suggested := host.RecommendedMemoryGB(host.Inspect(cfg.DataRoot)) + return errors.New(i18n.T(cfg.Locale, "err.commit_memory", memoryGB, available, suggested)) + } + if err := stambhaValidateMedia(dir, &profile); err != nil { + return err + } + // Two profiles can refer to one external image. Serialize the disk + // check and startup across clients before either marks its VM running. + wait, cancel := context.WithTimeout(ctx, 30*time.Second) + release, err := filelock.Acquire(wait, filepath.Join(filepath.Dir(dir), ".disk-start.lock"), 0) + cancel() + if err != nil { + return err + } + defer release() + vms, err := d.List(ctx) + if err != nil { + return err + } + if err := checkStambhaDiskOwners(name, profile.Disk, vms); err != nil { + return err + } + plan, env, qemuBinDir, qemuShareDir, err := d.launchPlan(ctx, dir, profile) + if err != nil { + return err + } + sock, err := d.socketPath(dir) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(sock), 0o755); err != nil { + return err + } + if err := os.Remove(sock); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + qemuImg := filepath.Join(qemuBinDir, filepath.Base(stambhaQEMUImgPath)) + diskFormat, err := inspectStambhaImage(ctx, qemuImg, profile.Disk, env) + if err != nil { + return err + } + if profile.USBImage != "" { + format, err := inspectStambhaImage(ctx, qemuImg, profile.USBImage, env) + if err != nil { + return err + } + if format != "raw" { + return errors.New("the boot image must be RAW") + } + } + args := rewriteStambhaArgs(plan.Args, profile, qemuShareDir, diskFormat == "qcow2", sock) + cfg := d.config() + rep := host.Inspect(cfg.DataRoot) + if profile.Accel == "whpx" && rep.WHPX != host.WHPXReady { + return errors.New(i18n.T(cfg.Locale, "err.whpx_"+string(rep.WHPX))) + } + recommendedICD := "" + if profile.HostedGPU && (profile.GPU == "" || strings.EqualFold(profile.GPU, "auto")) { + if rec := rep.RecommendedGPU; rec != nil { + recommendedICD = rec.VulkanICD + } + } + env = applyStambhaEnv(env, qemuBinDir, profile, recommendedICD) + cmd := exec.Command(plan.Exe, args...) + cmd.Dir, cmd.Env = plan.Dir, env + log, err := os.OpenFile(filepath.Join(dir, "qemu.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) + if err != nil { + return err + } + defer log.Close() + cmd.Stdout, cmd.Stderr = log, log + pid, err := stambhaStartProcess(cmd, dir) + if err != nil { + return err + } + if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, dir, cfg.AutoPinPCores, pid, profile.CPUs, false); line != "" && stdout != nil { + fmt.Fprintln(stdout, line) + } + if err := waitStambhaQMP(ctx, dir, sock, pid); err != nil { + if proc, probeErr := stambhaLiveProcess(dir); probeErr == nil && proc.PID == pid { + _ = proc.kill() + } + return fmt.Errorf("Stambha QEMU did not start: %w (see %s)", err, filepath.Join(dir, "qemu.log")) + } + if stdout != nil { + fmt.Fprintf(stdout, "Started %s (PID %d)\n", name, pid) + } + return nil + }) + return driver.StartResult{}, err +} + +func waitStambhaQMP(ctx context.Context, dir, socket string, pid int) error { + wait, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + poll := time.NewTicker(100 * time.Millisecond) + defer poll.Stop() + for { + proc, err := stambhaLiveProcess(dir) + if err != nil { + return err + } + if proc.PID != pid { + return errors.New("the QEMU process exited") + } + conn, err := qmp.Dial(wait, "unix", socket) + if err == nil { + return conn.Close() + } + select { + case <-wait.Done(): + return fmt.Errorf("%w: %v", wait.Err(), err) + case <-poll.C: + } + } +} + +func (d *StambhaDriver) Stop(ctx context.Context, name string, force bool, _, _ io.Writer) error { + return d.withVM(name, func(dir string, proc stambhaProcess) error { + if proc.PID == 0 { + return nil + } + socket, err := d.socketPath(dir) + if err != nil { + return err + } + if force { + if conn, err := qmp.Dial(ctx, "unix", socket); err == nil { + _ = conn.Execute("quit", nil) + _ = conn.Close() + wait, cancel := context.WithTimeout(ctx, 5*time.Second) + err = host.WaitProcessExit(wait, uint32(proc.PID), "qemu-system-x86_64.exe") + cancel() + if err == nil { + return nil + } + } + return proc.kill() + } + conn, err := qmp.Dial(ctx, "unix", socket) + if err != nil { + return err + } + defer conn.Close() + if err := conn.Execute("system_powerdown", nil); err != nil { + return err + } + wait, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + err = host.WaitProcessExit(wait, uint32(proc.PID), "qemu-system-x86_64.exe") + if errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("macOS is still running. Shut down from the Apple menu or explicitly force stop the VM (%w)", err) + } + return err + }) +} + +func (d *StambhaDriver) Delete(_ context.Context, name string, keepFiles bool, _, _ io.Writer) error { + return d.withVM(name, func(dir string, proc stambhaProcess) error { + if proc.PID != 0 { + return errors.New("stop the Stambha VM before deleting it") + } + if keepFiles { + if err := os.Remove(filepath.Join(dir, driver.OwnerMarkerFile)); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return os.Remove(filepath.Join(dir, stambhaProfileName)) + } + profile, err := readStambhaProfile(dir) + if err != nil { + return err + } + if err := ensureStambhaMediaOutsideStage(dir, profile); err != nil { + return err + } + // Media and disks are references. Deleting a VM removes only its profile and staged boot files. + if err := os.RemoveAll(filepath.Join(dir, stambhaStagedMediaDir)); err != nil { + return err + } + for _, file := range []string{"serial.log", "qemu.log", "uefi-vars.fd", "stambha-process.json", driver.OwnerMarkerFile} { + if err := os.Remove(filepath.Join(dir, file)); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + if sock, err := d.socketPath(dir); err == nil { + if err := os.Remove(sock); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + return os.Remove(filepath.Join(dir, stambhaProfileName)) + }) +} + +func (d *StambhaDriver) ReadLogs(_ context.Context, name string, serial bool) (string, error) { + dir, err := d.directory(name) + if err != nil { + return "", err + } + logName := "qemu.log" + if serial { + logName = "serial.log" + } + f, err := os.Open(filepath.Join(dir, logName)) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return "", err + } + const maxBytes = 1024 * 1024 + if info.Size() > maxBytes { + if _, err := f.Seek(info.Size()-maxBytes, io.SeekStart); err != nil { + return "", err + } + } + raw, err := io.ReadAll(io.LimitReader(f, maxBytes)) + return string(raw), err +} + +func inspectStambhaImage(ctx context.Context, qemuImg, path string, env []string) (string, error) { + cmd := exec.CommandContext(ctx, qemuImg, "info", "--output=json", path) + cmd.Env = env + stambhaHideConsole(cmd) + raw, err := cmd.Output() + if err != nil { + var exit *exec.ExitError + if errors.As(err, &exit) && len(exit.Stderr) > 0 { + err = fmt.Errorf("%w: %s", err, strings.TrimSpace(string(exit.Stderr))) + } + return "", fmt.Errorf("inspect Stambha disk %s: %w", filepath.Base(path), err) + } + return parseStambhaImageInfo(raw) +} + +func parseStambhaImageInfo(raw []byte) (string, error) { + var image struct { + Format string `json:"format"` + Size uint64 `json:"virtual-size"` + } + if err := json.Unmarshal(raw, &image); err != nil { + return "", fmt.Errorf("decode QEMU disk information: %w", err) + } + if image.Format != "raw" && image.Format != "qcow2" { + return "", fmt.Errorf("expected a RAW or QCOW2 disk, got %q", image.Format) + } + if image.Size == 0 { + return "", errors.New("the virtual disk is empty") + } + return image.Format, nil +} + +func rewriteStambhaArgs(rawArgs []string, profile stambhaProfile, qemuShareDir string, diskIsQcow2 bool, qmpSock string) []string { + out := make([]string, 0, len(rawArgs)+16) + for i := 0; i < len(rawArgs); i++ { + flag := rawArgs[i] + if i+1 < len(rawArgs) { + val := rawArgs[i+1] + switch flag { + case "-machine": + // Stambha uses HPET for PCI startup delays when the hypervisor + // supplies no invariant TSC. In hosted GPU mode, back outer RAM with + // a shareable Windows section so reims-graphics-pci can install the + // guest DRAM map for zero-copy SURFACE_PAGES / MapViewOfFile3. + val = strings.Replace(val, ",hpet=off,", ",hpet=on,", 1) + if profile.HostedGPU && profile.MemoryMiB > 0 && !strings.Contains(val, "memory-backend=") { + val += ",memory-backend=ram" + } + out = append(out, flag, val) + i++ + continue + case "-accel": + if profile.Accel == "whpx" { + val = "whpx,kernel-irqchip=off" + } + out = append(out, flag, val) + i++ + continue + case "-cpu": + if profile.Accel == "whpx" { + val = "host" + } + out = append(out, flag, val) + i++ + continue + case "-display": + if profile.HostedGPU { + val = "none" + } else if val == "sdl" { + val = "gtk" + } + out = append(out, flag, val) + i++ + continue + case "-drive": + if diskIsQcow2 && strings.Contains(val, "id=guest,") { + val = strings.Replace(val, "format=raw,", "format=qcow2,l2-cache-size=16M,", 1) + } + out = append(out, flag, val) + i++ + continue + case "-device": + if profile.HostedGPU { + if strings.HasPrefix(val, "isa-debug-exit,") || val == "VGA" || val == "virtio-keyboard-pci" || val == "virtio-tablet-pci" { + i++ + continue + } + } + if profile.MediaBus == "nvme" && strings.HasPrefix(val, "usb-storage,drive=volume,") { + val = "nvme,drive=volume,serial=STELAMEDIA,bootindex=0" + } + out = append(out, flag, val) + i++ + continue + } + } + out = append(out, flag) + } + if profile.HostedGPU { + if profile.MemoryMiB > 0 { + out = append(out, "-object", fmt.Sprintf("memory-backend-ram,id=ram,size=%dM,share=on", profile.MemoryMiB)) + } + out = append(out, + "-device", "VGA,id=stela-console", + "-device", "virtio-keyboard-pci", + "-device", "virtio-tablet-pci", + "-device", "reims-graphics-pci,id=gfx,x-hosted-arm64=on", + ) + } else if !profile.Display { + out = append(out, "-device", "VGA") + } + if qemuShareDir != "" { + out = append(out, "-L", qemuShareDir) + } + if qmpSock != "" { + out = append(out, "-qmp", "unix:"+strings.ReplaceAll(qmpSock, ",", ",,")+",server=on,wait=off") + } + return out +} + +func applyStambhaEnv(baseEnv []string, qemuBinDir string, profile stambhaProfile, recommendedICD string) []string { + out := make([]string, 0, len(baseEnv)+6) + hasVulkanOverride := false + for _, kv := range baseEnv { + idx := strings.IndexByte(kv, '=') + if idx <= 0 { + continue + } + k := kv[:idx] + if strings.EqualFold(k, "VK_ICD_FILENAMES") || strings.EqualFold(k, "VK_DRIVER_FILES") || + strings.EqualFold(k, "MESA_VK_DEVICE_SELECT") || strings.EqualFold(k, "VK_LOADER_DEVICE_SELECT") { + hasVulkanOverride = true + } + } + + dropKeys := map[string]bool{} + setKeys := map[string]string{} + if profile.HostedGPU { + if !profile.Display { + setKeys["REIMS_VGPU_WINDOW"] = "0" + } else { + dropKeys["REIMS_VGPU_WINDOW"] = true + } + switch { + case stambhaPCIDeviceID.MatchString(profile.GPU): + id := strings.ToLower(profile.GPU) + setKeys["MESA_VK_DEVICE_SELECT"] = id + setKeys["VK_LOADER_DEVICE_SELECT"] = id + dropKeys["VK_ICD_FILENAMES"] = true + dropKeys["VK_DRIVER_FILES"] = true + case strings.HasSuffix(strings.ToLower(profile.GPU), ".json"): + setKeys["VK_ICD_FILENAMES"] = profile.GPU + setKeys["VK_DRIVER_FILES"] = profile.GPU + dropKeys["MESA_VK_DEVICE_SELECT"] = true + dropKeys["VK_LOADER_DEVICE_SELECT"] = true + case recommendedICD != "" && !hasVulkanOverride: + setKeys["VK_ICD_FILENAMES"] = recommendedICD + setKeys["VK_DRIVER_FILES"] = recommendedICD + } + } + + seenPath := false + for _, kv := range baseEnv { + idx := strings.IndexByte(kv, '=') + if idx <= 0 { + continue + } + k := kv[:idx] + v := kv[idx+1:] + if strings.EqualFold(k, "PATH") { + if qemuBinDir != "" { + out = append(out, k+"="+qemuBinDir+string(os.PathListSeparator)+v) + } else { + out = append(out, kv) + } + seenPath = true + continue + } + skip := false + for dk := range dropKeys { + if strings.EqualFold(k, dk) { + skip = true + break + } + } + for sk := range setKeys { + if strings.EqualFold(k, sk) { + skip = true + break + } + } + if !skip { + out = append(out, kv) + } + } + if !seenPath && qemuBinDir != "" { + out = append(out, "PATH="+qemuBinDir) + } + for _, k := range []string{"REIMS_VGPU_WINDOW", "MESA_VK_DEVICE_SELECT", "VK_LOADER_DEVICE_SELECT", "VK_ICD_FILENAMES", "VK_DRIVER_FILES"} { + if v, ok := setKeys[k]; ok { + out = append(out, k+"="+v) + } + } + return out +} + +func stageStambhaBootVolume(srcDir, vmDir, runtimeEFI string, profile stambhaProfile) (string, error) { + dstDir := filepath.Join(vmDir, stambhaStagedMediaDir) + profile.BootVolume = srcDir + if err := ensureStambhaMediaOutsideStage(vmDir, profile); err != nil { + return "", err + } + // A source directory must never contain the staging destination or be inside it. + if stambhaPathWithin(srcDir, dstDir) || stambhaPathWithin(dstDir, srcDir) { + return "", errors.New("choose a boot folder outside the VM's staging directory") + } + if err := os.RemoveAll(dstDir); err != nil { + return "", err + } + complete := false + defer func() { + if !complete { + _ = os.RemoveAll(dstDir) + } + }() + cfgRel := filepath.Join("EFI", "stela", "stela.cfg") + efiRel := filepath.Join("EFI", "BOOT", "BOOTX64.EFI") + err := filepath.WalkDir(srcDir, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + rel, err := filepath.Rel(srcDir, path) + if err != nil { + return err + } + if strings.EqualFold(rel, efiRel) { + if entry.IsDir() { + return filepath.SkipDir + } + return nil + } + target := filepath.Join(dstDir, rel) + if entry.IsDir() { + return os.MkdirAll(target, 0o755) + } + if !entry.Type().IsRegular() { + return nil + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + // Never hardlink stela.cfg because we rewrite it below; hardlink read-only EFI payloads when possible. + if !strings.EqualFold(rel, cfgRel) { + if linkErr := os.Link(path, target); linkErr == nil { + return nil + } + } + return copyStambhaFile(path, target) + }) + if err != nil { + return "", err + } + efiPath := filepath.Join(dstDir, efiRel) + if err := os.MkdirAll(filepath.Dir(efiPath), 0o755); err != nil { + return "", err + } + if err := copyStambhaFile(runtimeEFI, efiPath); err != nil { + return "", err + } + cfgPath := filepath.Join(dstDir, cfgRel) + raw, err := os.ReadFile(cfgPath) + if err != nil { + return "", err + } + flags := strings.TrimSpace(string(raw)) + combined := flags + " " + profile.StelaArgs + var extra []string + if profile.HostedGPU { + if !stambhaHasFlag(combined, "--hosted-reims-base") { + extra = append(extra, "--hosted-reims-base", stambhaHostedReimsBase) + } + if !stambhaHasFlag(combined, "--hosted-reims-irq") { + extra = append(extra, "--hosted-reims-irq", stambhaHostedReimsIRQ) + } + if !stambhaHasFlag(combined, "--hosted-reims-irq-mode") { + extra = append(extra, "--hosted-reims-irq-mode", stambhaHostedIRQMode) + } + } + if profile.StelaArgs != "" { + extra = append(extra, profile.StelaArgs) + } + if len(extra) > 0 { + if flags != "" { + flags += " " + } + flags += strings.Join(extra, " ") + } + if err := os.WriteFile(cfgPath, []byte(flags+"\n"), 0o644); err != nil { + return "", err + } + complete = true + return dstDir, nil +} + +func stambhaHasFlag(args, key string) bool { + for _, arg := range strings.Fields(args) { + if arg == key || strings.HasPrefix(arg, key+"=") { + return true + } + } + return false +} + +func stambhaPathWithin(root, path string) bool { + rel, err := filepath.Rel(root, path) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) +} + +func copyStambhaFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + out, err := os.Create(dst) + if err != nil { + return err + } + _, copyErr := io.Copy(out, in) + return errors.Join(copyErr, out.Close()) +} diff --git a/internal/macos/stambhadriver/stambha_other.go b/internal/macos/stambhadriver/stambha_other.go new file mode 100644 index 0000000..85ce6e7 --- /dev/null +++ b/internal/macos/stambhadriver/stambha_other.go @@ -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 } diff --git a/internal/macos/stambhadriver/stambha_test.go b/internal/macos/stambhadriver/stambha_test.go new file mode 100644 index 0000000..425538e --- /dev/null +++ b/internal/macos/stambhadriver/stambha_test.go @@ -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) + } +} diff --git a/internal/macos/stambhadriver/stambha_windows.go b/internal/macos/stambhadriver/stambha_windows.go new file mode 100644 index 0000000..94b4f51 --- /dev/null +++ b/internal/macos/stambhadriver/stambha_windows.go @@ -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) +} diff --git a/internal/runtime/kinds.go b/internal/runtime/kinds.go index a62f6f0..ae3a34c 100644 --- a/internal/runtime/kinds.go +++ b/internal/runtime/kinds.go @@ -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" ) diff --git a/internal/runtime/selection.go b/internal/runtime/selection.go index c9c3ff0..c6ac838 100644 --- a/internal/runtime/selection.go +++ b/internal/runtime/selection.go @@ -97,7 +97,7 @@ func requestedSelection(next config.Config, commit string, aslr *bool) (config.C return next, err } if !slices.ContainsFunc(installed, func(r Installed) bool { - return r.Commit == commit || r.Kind+"/"+r.Commit == commit + return r.Kind != StambhaKind && (r.Commit == commit || r.Kind+"/"+r.Commit == commit) }) { return next, fmt.Errorf("%w: %s", ErrNotFound, commit) } diff --git a/internal/runtime/selection_test.go b/internal/runtime/selection_test.go index 9f703e5..182ce00 100644 --- a/internal/runtime/selection_test.go +++ b/internal/runtime/selection_test.go @@ -190,3 +190,16 @@ func TestNonWindowsIgnoresSavedQEMUASLR(t *testing.T) { t.Fatalf("lost runtime selection or portable preference: %+v, %v", saved, err) } } + +func TestSelectionDoesNotActivateARMRuntimeForX86(t *testing.T) { + cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "intel"} + writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "intel"), Manifest{Commit: "intel"}) + writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), StambhaKind, "arm"), Manifest{Commit: "arm", Kind: StambhaKind}) + + for _, ref := range []string{"arm", StambhaKind + "/arm"} { + got, err := requestedSelection(cfg, ref, nil) + if !errors.Is(err, ErrNotFound) || got.ActiveRuntime != cfg.ActiveRuntime { + t.Fatalf("select %q: active = %q, err = %v", ref, got.ActiveRuntime, err) + } + } +} diff --git a/locales/en-US/wizard.json b/locales/en-US/wizard.json index 0303153..6c943b8 100644 --- a/locales/en-US/wizard.json +++ b/locales/en-US/wizard.json @@ -89,5 +89,12 @@ "wizardBasics": "Basics", "offlineListFailedDetail": "Couldn’t read Apple’s release list: {err}", "setupLangPackOffer": "Also install “{name}”", - "setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page" + "setupLangPackFailed": "Could not install the language pack; you can retry from the Plugins page", + "armRestoreGroup": "ARM restore image", + "armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB", + "armRestoreMediaHint": "Download the IPSW from Apple. To create a VM, select prepared Stambha boot media and a writable virtual disk below.", + "armRestoreDownload": "Download IPSW", + "armRestoreDownloaded": "Downloaded IPSW", + "armRuntimeLabel": "ARM64 guest", + "x86RuntimeLabel": "x86-64 guest" } diff --git a/locales/zh-CN/wizard.json b/locales/zh-CN/wizard.json index abea692..83b0814 100644 --- a/locales/zh-CN/wizard.json +++ b/locales/zh-CN/wizard.json @@ -89,5 +89,12 @@ "wizardBasics": "基本信息", "offlineListFailedDetail": "无法读取 Apple 的版本列表:{err}", "setupLangPackOffer": "同时安装「{name}」", - "setupLangPackFailed": "语言包安装失败,可稍后在插件页重试" + "setupLangPackFailed": "语言包安装失败,可稍后在插件页重试", + "armRestoreGroup": "ARM 恢复镜像", + "armRestoreVersion": "macOS 27.2.1 (26B131) · 25.6 GB", + "armRestoreMediaHint": "从 Apple 下载 IPSW。创建虚拟机时,请在下方选择已制作的 Stambha 启动介质和可写虚拟磁盘。", + "armRestoreDownload": "下载 IPSW", + "armRestoreDownloaded": "已下载的 IPSW", + "armRuntimeLabel": "ARM64 来宾", + "x86RuntimeLabel": "x86-64 来宾" }