From 46f274be09542fb2bf6f669b9b16a716063fb628 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sat, 28 Nov 2026 02:04:27 -0700 Subject: [PATCH] feat: initialize reims-go portable runtime spec, packager, and M1 bilingual Go CLI --- .gitattributes | 2 + .gitignore | 30 +++ AGENTS.md | 45 ++++ NOTICE.md | 26 ++ README.md | 36 +++ cmd/reims-go/main.go | 324 ++++++++++++++++++++++ docs/architecture.md | 102 +++++++ docs/portable-runtime-spec.md | 127 +++++++++ docs/roadmap.md | 97 +++++++ docs/shell-design.md | 100 +++++++ go.mod | 3 + internal/config/config.go | 106 ++++++++ internal/driver/reims/reims.go | 230 ++++++++++++++++ internal/driver/reims/reims_test.go | 36 +++ internal/host/host.go | 92 +++++++ internal/host/host_other.go | 23 ++ internal/host/host_test.go | 24 ++ internal/host/host_windows.go | 273 +++++++++++++++++++ internal/i18n/i18n.go | 119 +++++++++ internal/i18n/i18n_test.go | 23 ++ internal/runtime/runtime.go | 383 +++++++++++++++++++++++++++ patches/README.md | 13 + patches/qemu-whpx-win10-compat.patch | 77 ++++++ scripts/pack-runtime.ps1 | 147 ++++++++++ 24 files changed, 2438 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 NOTICE.md create mode 100644 README.md create mode 100644 cmd/reims-go/main.go create mode 100644 docs/architecture.md create mode 100644 docs/portable-runtime-spec.md create mode 100644 docs/roadmap.md create mode 100644 docs/shell-design.md create mode 100644 go.mod create mode 100644 internal/config/config.go create mode 100644 internal/driver/reims/reims.go create mode 100644 internal/driver/reims/reims_test.go create mode 100644 internal/host/host.go create mode 100644 internal/host/host_other.go create mode 100644 internal/host/host_test.go create mode 100644 internal/host/host_windows.go create mode 100644 internal/i18n/i18n.go create mode 100644 internal/i18n/i18n_test.go create mode 100644 internal/runtime/runtime.go create mode 100644 patches/README.md create mode 100644 patches/qemu-whpx-win10-compat.patch create mode 100644 scripts/pack-runtime.ps1 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8083b67 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.patch -text +*.diff -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..857829d --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Build & Wails artifacts +/build/bin/ +/dist/ +/frontend/dist/ +/frontend/node_modules/ +*.exe +*.dll +*.so +*.dylib +*.zip +*.tar.zst +*.7z + +# Runtime & VM data (NEVER commit images, firmware, or runtime bundles) +/runtime/ +/data/ +*.qcow2 +*.img +*.dmg +*.ipsw +*.fd +*.rom +*.iso + +# OS / IDE / Logs +.DS_Store +Thumbs.db +*.log +.vscode/ +.idea/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e8d65b8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,45 @@ +# AGENTS.md(reims-go) + +> 面向在本仓库工作的 AI Agent 与协作者。遵循上级 [`D:\Build\AGENTS.md`](../AGENTS.md) 与 [`D:\Build\DISK-LAYOUT.md`](../DISK-LAYOUT.md)。 + +## 仓库定位 + +**`reims-go`** 是面向 Windows x86-64 的 **免编译、一站式 `reims-vgpu` macOS 虚拟机桌面启动器与工程工作台**(Go + Wails,GUI 与 CLI 共用内核)。 + +它与上游 [steelbrain/reims-vgpu](https://github.com/steelbrain/reims-vgpu) 及研究仓 [`D:\Build\macos-vm-lab`](../macos-vm-lab) 的分工: +- `reims-vgpu`:上游底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。 +- `macos-vm-lab`:内核/图形深度研究、M0–M5 实验记录与基准数据。 +- `reims-go`(本仓库):产品化一站式桌面应用与便携运行时打包/分发流水线,让用户在无需安装 MSYS2、Rust、Git 或本地编译的前提下,开箱运行带 GPU 加速的 macOS 虚拟机(时间目标见 `docs/roadmap.md` 的 M2 DoD),并提供 CoW 派生、快照、P-Core 绑核、QMP/SSH 自动化等工程能力。 + +## 存储与路径硬约束 + +1. **代码与文档放仓库**:Go 后端、Wails 前端、打包脚本、CI workflow 与文档位于 `D:\Build\reims-go\`。 +2. **大体积文件严禁入库**:预编译 QEMU 运行时包(~900 MB 解压 / ~250 MB 压缩)、macOS 镜像、`.qcow2` 磁盘、快照统一放 **`D:\Data\reims-go\`**(开发联调时可复用 `D:\Data\macos-vm-lab\reims\`),**严禁写入 `C:` 或 `F:`**。 +3. **临时文件放 `D:\Build\Temp\`**:打包草稿、一次性测试目录用完即清。 +4. **Go 缓存**:本机已配置 `GOPATH=D:\DevCache\go`、`GOBIN=D:\DevTools\go-bin`,直接沿用即可。 + +## 事实核验与安全规则 + +1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时附上游 commit 与 `文件:行号`;未实测项显式标「待验证」。 +2. **不绕过系统安全与人工确认**:UAC 提权启用 WHPX、重启 Windows、macOS GUI 安装向导、发布 Release 等操作由人确认触发。 +3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。 +4. **对上游的修改只走补丁队列**:不长期维护 fork。改动以补丁形式放在 `patches/`,在 `docs/portable-runtime-spec.md` 第 5 节登记,目标是清零。补丁打不上就停下报告,不要自动改补丁。向上游提 PR 由人来做。 +5. **运行时包必须如实声明来源**:`manifest.json` 写清上游 commit、`vendor/qemu` commit 和全部补丁。带补丁的包不能写成「纯上游」。 +6. **用户只拿 `stable` 通道**:CI 产物只进 `candidate`,经真实宿主冒烟测试并由人确认后才升级(`portable-runtime-spec.md` 第 6 节)。 +7. **配置只通过 `reims-ctl set` 写入**:不直接改 `vm.toml`,让上游的校验和 OpenCore 重建逻辑生效(`docs/shell-design.md`)。 + +## 开源合规边界 + +- `reims-go` 自身代码(Go 后端 + 前端外壳)采用 **MIT** 协议(规划)。 +- 运行时组件(`qemu-system-x86_64.exe` 为 GPLv2,`reims-ctl` / `reims-vgpu` / `metal2vulkan` 为 `GPL-2.0-or-later OR LGPL-3.0-or-later`,以及 CLANG64/libva 动态库)以**独立子进程与独立运行时压缩包**形态集成。发布二进制时必须同时提供**对应源码包**(含本地补丁,只给上游链接不够)和完整许可证文本(`NOTICE.md` / `licenses/`),见 `docs/portable-runtime-spec.md` 第 7 节。 +- 不打包、不托管任何 Apple 系统文件;macOS 恢复镜像一律由用户端运行 `reims-util` 直连 Apple 服务器拉取或本地导入。 +- macOS 的软件许可只允许在 Apple 硬件上虚拟化。上游也处在同样的位置,但一键工具公开发布会放大风险。**是否公开发布由人决定**,在此之前 Release 保持私有。 + +## 文档导航 + +- [`README.md`](README.md) — 项目总览、核心特性与差异化定位 +- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时剥离实测结论、目录规范与 CI 打包设计 +- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 分层架构、环境隔离、WHPX/GPU/P-Core 自动调优与控制面设计 +- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS(Virtualization.framework 与 macOS 人机界面规范) +- [`patches/`](patches/) — 对上游的补丁队列(当前只有 Win10 WHPX 兼容补丁) +- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 里程碑与验收标准 diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..cc907fe --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,26 @@ +# Third-Party Notices + +`reims-go` itself (Go backend and desktop frontend) is licensed separately from the +portable runtime bundle it invokes as an external child process. + +The portable runtime bundle (`reims-runtime-win-x64-.tar.zst`) contains +precompiled binaries built from the following upstream open-source projects: + +1. **reims-vgpu / reims-ctl** + - Upstream: https://github.com/steelbrain/reims-vgpu + - License: `GPL-2.0-or-later OR LGPL-3.0-or-later` +2. **metal2vulkan / metal2vulkan-runtime** + - Upstream: https://github.com/steelbrain/metal2vulkan + - License: See upstream repository license +3. **reims-util** + - Upstream: https://github.com/steelbrain/reims-util + - License: See upstream repository license +4. **QEMU (qemu-reims-vgpu fork)** + - Upstream: https://github.com/steelbrain/qemu-reims-vgpu + - License: `GPL-2.0-only` / `GPL-2.0-or-later` (and component licenses in QEMU) +5. **MSYS2 CLANG64 runtime libraries, libva, Mesa vaon12** + - Upstream: https://github.com/msys2/MINGW-packages + - License: Respective open-source licenses of each packaged DLL + +No Apple proprietary files, macOS installers, recovery images, or SMC keys are +included in this repository or in any runtime bundle. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a13b3de --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# reims-go + +> Windows 桌面端 **免编译、一站式 `reims-vgpu` macOS 虚拟机启动器与开发者工作台**(Go + Wails,GUI + CLI 一体)。 + +## 为什么做 reims-go? + +上游 [steelbrain/reims-vgpu](https://github.com/steelbrain/reims-vgpu) 已经实现了在 Windows 原生 QEMU + WHPX 上将 macOS Guest 的 Metal 图形转译到宿主机 Vulkan GPU(如 NVIDIA RTX 4070 Ti)。但当前使用门槛依然很高: + +1. **安装编译繁琐**:需手动安装 MSYS2、换镜像源、装 Rust、拉取 `vendor/qemu` 并本地编译 1800+ 目标(耗时 15–30 分钟)。 +2. **默认污染 C 盘**:MSYS2、Cargo/Rustup、QEMU 构建和上百 GB 的 macOS 虚拟盘默认全部写入 `%USERPROFILE%` 与 `C:\msys64`。 +3. **硬件排障靠手工**:缺少 WHPX 一键体检、多显卡/虚拟显示适配器(如 ToDesk/GameViewer)自动过滤、Intel 12–14 代大小核 P-Core 亲和性绑核。 +4. **缺少开发者工作流**:上游 `reims-ctl` 未内置 CoW 秒级派生、快照管理、QMP 控制与自动化测试闭环;现有社区 GUI(如 PySide6 打包的 `Reims-GUI-Win`)包体达 1.68 GB 且绕开了 `reims-ctl`,难以跟进上游更新。 + +**`reims-go` 的解法**: +- **免编译便携运行时**:通过 CI 预编译单套 `reims-runtime-win-x64`(仅含 `reims-ctl.exe` + `reims-util.exe` + 自包含 71 DLL 的 `qemu/`,**彻底脱离 MSYS2 / Rust / Git**),经本机冒烟测试后进入 `stable` 通道,用户端下载解压即用。 +- **把上游当内核**:不长期维护 fork。对上游的修改只放在 `patches/` 补丁队列里,同时向上游提 PR,合并后删掉,目标是补丁数清零。 +- **轻量单文件外壳**:Go + Wails(复用系统内置 WebView2),GUI 与 CLI 共用同一套 Go 核心包,不捆绑 Python / PowerShell 7。 +- **紧贴 `reims-ctl` 生态**:以子进程封装 `reims-ctl`(并通过 `XDG_*` 环境变量强制隔离到用户指定盘符),上游更新只需同步发布新版运行时包。 +- **工程化增值能力**:WHPX 一键体检与提权引导、自动锁定独显 Vulkan ICD、P-Core 绑核、CoW 派生与快照、QMP/SSH/截屏控制。 + +## 技术可行性基线(2026-11-28 本机实测) + +- **Win10 19045 + RTX 4070 Ti 实测可用,但需要本地补丁**:本机已在 `Reims vGPU` 窗口内成功引导并进入 `Install macOS Tahoe` 图形安装界面。这次用的 QEMU 带着 [`patches/qemu-whpx-win10-compat.patch`](patches/qemu-whpx-win10-compat.patch)(修复 Win10 上 WHPX 建 vCPU 失败),不是纯上游构建。补丁的管理方式见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) 第 5 节。 +- **上游没有 Release、变动很快**:2026-11-21 到 11-28 上游有 100 多个提交。所以 `reims-go` 只给用户发冒烟测试过的 `stable` 运行时(同上文档第 6 节)。 +- **目标宿主**:Win10 的扩展支持已在 2026 年 10 月结束,上游只在 Win11 上测过。对外以 Win11 为主,Win10 靠补丁保证本机可用。 +- **便携运行时剥离实测通过**:将 `reims-ctl.exe`(58 MB)、`reims-util.exe`(31.3 MB)与 `qemu/current/`(828.5 MB,含 71 个 DLL)置于纯净 `PATH`(无 MSYS2、无 Rust、无源码仓库)中运行,`reims-ctl doctor` 的 **9/9 运行时检查全部通过**(详情见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。 +- **本机开发环境就绪**:`Go 1.27.3`、`Node.js`、`pnpm`、`WebView2 Runtime 158.0` 均已存在。 + +## 文档索引 + +- [`AGENTS.md`](AGENTS.md) — 仓库约定、存储红线与开源合规边界 +- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时实测记录、目录规范与打包方案 +- [`docs/architecture.md`](docs/architecture.md) — Go + Wails 系统架构与模块设计 +- [`docs/shell-design.md`](docs/shell-design.md) — 外壳设计原语:配置模型与交互对齐 macOS,随时修改、标明生效时机 +- [`patches/`](patches/) — 对上游的补丁队列 +- [`docs/roadmap.md`](docs/roadmap.md) — M0–M4 开发路线图与验收门槛 diff --git a/cmd/reims-go/main.go b/cmd/reims-go/main.go new file mode 100644 index 0000000..7d0f6a5 --- /dev/null +++ b/cmd/reims-go/main.go @@ -0,0 +1,324 @@ +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver/reims" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintf(os.Stderr, "error: %v\n", err) + os.Exit(1) + } +} + +func run(args []string) error { + fs := flag.NewFlagSet("reims-go", flag.ContinueOnError) + langFlag := fs.String("lang", "", "UI/CLI language: zh-CN | en-US") + dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory") + if err := fs.Parse(args); err != nil { + return err + } + + cfgPath := "" + if *dataRootFlag != "" { + cfgPath = filepath.Join(*dataRootFlag, "reims-go.json") + } + cfg, err := config.Load(cfgPath) + if err != nil { + return err + } + if *dataRootFlag != "" { + cfg.DataRoot = *dataRootFlag + } + if *langFlag != "" { + cfg.Locale = i18n.Normalize(*langFlag) + } + loc := cfg.Locale + + rest := fs.Args() + if len(rest) == 0 { + printUsage(loc) + return nil + } + + switch rest[0] { + case "doctor": + return cmdDoctor(cfg, loc, rest[1:]) + case "runtime": + return cmdRuntime(cfg, loc, rest[1:]) + case "vm": + return cmdVM(cfg, loc, rest[1:]) + case "help", "-h", "--help": + printUsage(loc) + return nil + default: + return fmt.Errorf("unknown command %q", rest[0]) + } +} + +func printUsage(loc i18n.Locale) { + if loc == i18n.ZhCN { + fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器与 CLI") + fmt.Println("\n用法:") + fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]") + fmt.Println("\n命令:") + fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)") + fmt.Println(" runtime install 导入并校验便携运行时包(.tar.zst 或 .zip)") + fmt.Println(" runtime list 查看已安装的便携运行时版本") + fmt.Println(" runtime use 切换当前激活运行时") + fmt.Println(" vm list 列出已创建的虚拟机") + fmt.Println(" vm create [options] 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)") + fmt.Println(" vm set [options] 修改虚拟机配置(下次启动生效)") + fmt.Println(" vm start|stop|eject 启动 / 停止 / 弹出安装盘") + return + } + fmt.Println("reims-go - Portable one-stop reims-vgpu launcher & CLI for Windows") + fmt.Println("\nUsage:") + fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] [args]") + fmt.Println("\nCommands:") + fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)") + fmt.Println(" runtime install Verify and install a portable runtime (.tar.zst or .zip)") + fmt.Println(" runtime list List installed portable runtimes") + fmt.Println(" runtime use Activate an installed runtime version") + fmt.Println(" vm list List virtual machines") + fmt.Println(" vm create [options] Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)") + fmt.Println(" vm set [options] Update VM settings (applies on next start)") + fmt.Println(" vm start|stop|eject Start / stop / eject installer") +} + +func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("doctor", flag.ContinueOnError) + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args); err != nil { + return err + } + rep := host.Inspect(cfg.DataRoot) + active, _ := rt.ResolveActive(cfg) + + if *asJSON { + payload := map[string]any{ + "host": rep, + "config": cfg, + "runtime": active, + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(payload) + } + + fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title")) + fmt.Printf("%-36s: %s/%s\n", i18n.T(loc, "doctor.os"), rep.OS, rep.Arch) + fmt.Printf("%-36s: %dC / %dT\n", i18n.T(loc, "doctor.cpu"), rep.PhysicalCores, rep.LogicalCPUs) + if rep.HasHybridCores { + fmt.Printf("%-36s: %d cores, mask %s (CPUs %v)\n", i18n.T(loc, "doctor.pcores"), rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs) + fmt.Printf("%-36s: %d cores (CPUs %v)\n", i18n.T(loc, "doctor.ecores"), rep.ECoreCount, rep.ECoreLogicalCPUs) + } + if rep.TotalRAMGB > 0 { + fmt.Printf("%-36s: %.1f GB total / %.1f GB avail\n", i18n.T(loc, "doctor.ram"), rep.TotalRAMGB, rep.AvailRAMGB) + } + if rep.FreeDiskGB > 0 { + fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot) + } + + whpxKey := "doctor.whpx.unsupported" + switch rep.WHPX { + case host.WHPXReady: + whpxKey = "doctor.whpx.ok" + case host.WHPXNoHypervisor: + whpxKey = "doctor.whpx.no_hv" + case host.WHPXMissing: + whpxKey = "doctor.whpx.missing" + } + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey)) + + if len(rep.GPUs) == 0 { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.T(loc, "doctor.gpu.none")) + } else { + fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu")) + for _, g := range rep.GPUs { + rec := "" + if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD { + rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]" + } + fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD) + } + } + + if active == nil { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none")) + } else { + fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir)) + } + return nil +} + +func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) == 0 { + return fmt.Errorf("usage: reims-go runtime ") + } + switch args[0] { + case "install": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go runtime install ") + } + inst, err := rt.InstallFromArchive(cfg, args[1]) + if err != nil { + return err + } + cfg.ActiveRuntime = inst.Commit + if err := config.Save("", cfg); err != nil { + return err + } + fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir)) + return nil + case "list": + list, err := rt.List(cfg) + if err != nil { + return err + } + if len(list) == 0 { + fmt.Println(i18n.T(loc, "runtime.empty")) + return nil + } + for _, item := range list { + mark := " " + if item.Active { + mark = "*" + } + fmt.Printf("%s %s %s (%s)\n", mark, item.Commit, item.Manifest.QemuVersion, item.Dir) + } + return nil + case "use": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go runtime use ") + } + list, err := rt.List(cfg) + if err != nil { + return err + } + for _, item := range list { + if item.Commit == args[1] { + cfg.ActiveRuntime = item.Commit + if err := config.Save("", cfg); err != nil { + return err + } + fmt.Println(i18n.T(loc, "runtime.activated", item.Commit)) + return nil + } + } + return fmt.Errorf("runtime %q not found", args[1]) + default: + return fmt.Errorf("unknown runtime subcommand %q", args[0]) + } +} + +func cmdVM(cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) == 0 { + return fmt.Errorf("usage: reims-go vm ") + } + active, err := rt.ResolveActive(cfg) + if err != nil { + return fmt.Errorf("%s", i18n.T(loc, "err.runtime_not_installed")) + } + client := reims.NewClient(cfg, *active) + ctx := context.Background() + + switch args[0] { + case "list": + vms, err := client.ListRaw(ctx) + if err != nil { + return err + } + if len(vms) == 0 { + fmt.Println(i18n.T(loc, "vm.empty")) + return nil + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(vms) + case "create": + fs := flag.NewFlagSet("vm create", flag.ContinueOnError) + dir := fs.String("dir", "", "Custom VM directory") + macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)") + cpus := fs.Int("cpus", 8, "vCPU count") + mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)") + diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)") + gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path") + logs := fs.Bool("logs", true, "Keep graphics and serial logs") + start := fs.Bool("start", false, "Start VM immediately after creation") + if err := fs.Parse(args[1:]); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm create [flags] ") + } + name := fs.Arg(0) + opts := reims.CreateOpts{ + Name: name, + Dir: *dir, + MacOS: *macos, + CPUs: *cpus, + Memory: *mem, + DiskSize: *diskSize, + GPU: *gpu, + Logs: logs, + Start: *start, + } + if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil { + return err + } + fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title")) + fmt.Println(i18n.T(loc, "vm.install_guide.step1")) + fmt.Println(i18n.T(loc, "vm.install_guide.step2")) + fmt.Println(i18n.T(loc, "vm.install_guide.step3", name)) + return nil + case "set": + fs := flag.NewFlagSet("vm set", flag.ContinueOnError) + cpus := fs.Int("cpus", 0, "vCPU count") + mem := fs.String("memory", "", "RAM size") + gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON") + res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT") + if err := fs.Parse(args[1:]); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm set [flags] ") + } + return client.Set(ctx, reims.SetOpts{ + Name: fs.Arg(0), + CPUs: *cpus, + Memory: *mem, + GPU: *gpu, + Resolution: *res, + }, os.Stdout, os.Stderr) + case "start": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm start ") + } + return client.Start(ctx, args[1], os.Stdout, os.Stderr) + case "stop": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm stop ") + } + return client.Stop(ctx, args[1], os.Stdout, os.Stderr) + case "eject": + if len(args) < 2 { + return fmt.Errorf("usage: reims-go vm eject ") + } + return client.Eject(ctx, args[1], os.Stdout, os.Stderr) + default: + return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " ")) + } +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..e410292 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,102 @@ +# 系统架构设计(Architecture) + +> 技术栈:**Go + Wails**(Windows x86-64 优先,GUI 与 CLI 共用核心逻辑) + +## 1. 设计目标与原则 + +1. **零编译上手**:用户拿到单个 `reims-go.exe`(或便携压缩包),首次启动向导自动检测环境 → 下载/导入便携运行时 → 创建并启动 macOS Tahoe。 +2. **不重复造 `reims-ctl` 的轮子**:`reims-go` 通过受控子进程包装 `reims-ctl`(及 `qemu-img`),避免像手写 PowerShell 启动脚本那样在每次上游变更参数时失效。 +3. **GUI 与 CLI 同源**:所有核心能力落在 `internal/` Go 包中;既可双击启动 Wails 桌面界面,也可通过 `reims-go ` 在终端或 CI 中自动化调用。 +4. **C 盘零污染**:所有运行时、下载缓存、VM 磁盘与快照严格留在用户选定的 `` 下。 +5. **Day-1 中英双语(`zh-CN` / `en-US`)**:前端界面、装机引导文案(默认贴合简体中文 macOS 恢复与安装界面术语,如「磁盘工具 → 抹掉为 APFS → 重新安装 macOS」)与 CLI 输出从第一天即内置双语字典,自动跟随系统语言并支持在界面顶部实时切换(持久化到 `reims-go.json`)。 +6. **跨平台开发友好**:虽然宿主机运行目标优先面向 Windows x86-64(WHPX),但所有 Windows 原生 API(`WinHvPlatform.dll`、注册表 Vulkan ICD、`GetLogicalProcessorInformationEx`、进程亲和性)严格隔离在 `*_windows.go` 构建标签中,提供 `*_other.go` 桩实现,确保在中文 macOS 开发环境上也能直接进行前端开发、`go build` 与 `go test ./...`。 +7. **面向未来扩展**:驱动层抽象出 `Engine` 接口,当前实现 `reims`(macOS x86-64 WHPX),预留扩展位以对接后续 `vphone`(iOS)或远程宿主模式。 + +## 2. 总体分层架构 + +```mermaid +flowchart TB + subgraph UI["交互层"] + GUI["Wails 桌面界面\n(React / Vite + WebView2)"] + CLI["CLI 子命令\n(reims-go doctor/runtime/vm/clone/exec)"] + end + + subgraph Core["Go 核心服务层 (internal/)"] + Preflight["host/ 环境体检与调优\n(WHPX检测与一键提权、Vulkan ICD扫描、\nP/E核拓扑与进程亲和性绑核)"] + RuntimeMgr["runtime/ 便携运行时管理\n(Release拉取、SHA256校验、\n原子解压、版本切换与回滚)"] + VMMgr["vm/ 生命周期与工作流\n(向导创建、日志流、eject、\nGolden Image、CoW 派生与快照)"] + Control["control/ 带外控制\n(QMP 客户端、SSH 执行、\n截屏与状态监控)"] + end + + subgraph External["外部运行时(独立子进程,全部在 DataRoot 下)"] + ReimsCtl["reims-ctl.exe + reims-util.exe"] + QEMU["qemu-system-x86_64.exe + qemu-img.exe\n(含 reims-graphics-pci + 71 DLLs)"] + end + + GUI --> Preflight & RuntimeMgr & VMMgr & Control + CLI --> Preflight & RuntimeMgr & VMMgr & Control + VMMgr --> ReimsCtl + VMMgr --> QEMU + Control --> QEMU + ReimsCtl --> QEMU +``` + +## 3. 核心模块设计 + +### 3.1 `internal/host` — 宿主机体检与自动硬件调优 +- **WHPX 检测与引导**: + - 直接加载 `WinHvPlatform.dll` 调用 `WHvGetCapability`(与 `reims-ctl` 逻辑一致),同时查询 `Win32_OptionalFeature`(`HypervisorPlatform` / `VirtualMachinePlatform`),**无需管理员权限即可准确判断**。 + - 仅在检测到未启用时,GUI 提供「开启 Hypervisor Platform(需要 UAC)」按钮,调用 `ShellExecuteW(..., "runas", ...)` 弹出标准桌面 UAC 并提示重启。 +- **GPU / Vulkan ICD 自动选卡**: + - 读取注册表显示适配器类键下的 `VulkanDriverName` 与 `DriverDesc`,自动区分独立显卡(NVIDIA/AMD)、核显(Intel UHD)与虚拟显示适配器(ToDesk / GameViewer 等),默认推荐并可一键锁定独显 ICD 传给 `reims-ctl --gpu `。 +- **Alder Lake / 异构大小核 P-Core 绑核**: + - 通过 `GetLogicalProcessorInformationEx(RelationProcessorCore)` 解析 `EfficiencyClass`,计算 P-Core 逻辑 CPU 亲和性掩码(如 i7-12700K 的 `0xFFFF`)。 + - VM 启动后,自动将对应 `qemu-system-x86_64.exe` 进程设置 `SetProcessAffinityMask` 到 P-Core(支持按 VM 开关)。 + +### 3.2 `internal/runtime` — 便携运行时管理 +- 维护 `\runtimes\` 下的多版本便携运行时包: + - 支持从 GitHub Releases(含可选国内加速镜像)拉取,也支持「导入本地 `.tar.zst` 包」离线安装; + - 校验 `manifest.json` 与 SHA256 后解压至 `.tmp` 再原子重命名,失败不破坏现有版本; + - 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖。 + +### 3.3 `internal/driver/reims` — `reims-ctl` 受控包装器 +- 包装 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`、`command`、`doctor`。 +- 流式捕获 stdout/stderr 与串口日志,实时推送到 Wails 前端事件总线(`runtime.EventsEmit`),让用户在安装 macOS Tahoe 期间直观看到下载进度与内核启动日志。 +- **QMP 不抢上游的 socket**:上游 `reims-ctl` 自己就有 QMP 客户端,走每台 VM 的 `qmp.sock`(Windows 上是 Winsock AF_UNIX,`crates/reims-ctl/src/qmp.rs:1-8`、`vm.rs:1000-1027`)。QEMU 的一个 `-qmp` 同一时间只接受一个客户端,第二个连接会一直等到超时(同上 `qmp.rs` 注释,引自 QEMU `chardev/char-socket.c`)。所以 `reims-go` **不连这个 socket**,否则会卡住 `reims-ctl stop` 等命令;它通过 `reims-ctl set --extra-args` 另开一个自己的 monitor(`-qmp tcp:127.0.0.1:,server=on,wait=off`)。QEMU 允许多个 `-qmp`,但与上游参数是否冲突仍**待 M3.2 实测**。 +- **配置写入只用 `set`**:`reims-ctl set` 的修改在**下次启动**时生效(`cli.rs:73`);改图形会在 VM 停止时重建 OpenCore 镜像(`cli.rs:242`)。可改字段见 `cli.rs:551-616`,外壳如何呈现见 [`shell-design.md`](shell-design.md)。 + +### 3.4 `internal/vm` 与 `internal/control` — 开发者进阶能力(M3) +- **CoW 秒级派生**:使用便携运行时自带的 `qemu-img.exe create -f qcow2 -F qcow2 -b ` 生成写时复制派生盘,挂入临时实例,实现秒级拉起与无痕销毁(待验证 `reims-ctl create --disk --disk-mode in-place` 对 backing file 的兼容性)。 +- **带外控制**:通过 QMP 查询运行态、优雅关机(失败再回退终止,避免粗暴 `taskkill` 伤盘)、截屏与键鼠注入;结合 `--ssh-port` 提供命令执行通道。 + +## 4. 建议代码目录结构 + +```text +reims-go/ +├── cmd/ +│ └── reims-go/ # 主入口(无参启动 Wails GUI,带子命令走 CLI 模式) +├── internal/ +│ ├── config/ # reims-go.json(含 locale: zh-CN|en-US、DataRoot、P-Core 开关) +│ ├── i18n/ # Go 端中英双语消息字典与结构化错误码 +│ ├── host/ # WHPX、Vulkan ICD、P/E 核拓扑、进程亲和性(*_windows.go + *_other.go) +│ ├── runtime/ # 便携运行时下载/导入、校验、解压、环境构造 +│ ├── driver/ +│ │ └── reims/ # reims-ctl 子进程包装与 JSON/日志解析 +│ ├── qmp/ # QMP TCP 客户端 +│ └── vm/ # VM 编排、CoW 派生、向导状态机 +├── frontend/ # Wails 前端(轻量 React + Vite + TypeScript + zh-CN/en-US i18n) +├── scripts/ +│ └── pack-runtime.ps1 # 从本地构建打包便携运行时(tar.zst + manifest) +└── docs/ +``` + +## 5. 与 `Reims-GUI-Win` 的核心差异 + +> 本节关于 `Reims-GUI-Win` 的数据(Release 约 1.68 GB、PySide6 + PowerShell 7、双套 QEMU)没有附来源,按事实核验规则标为**待验证**。另外注意,上游 `reims-ctl` 自带一个终端界面,有创建和编辑表单(`crates/reims-ctl/src/tui.rs`、`form.rs`)。`reims-go` 的 GUI 要比它多出价值,而不是重做一遍,见 [`shell-design.md`](shell-design.md) 第 5 节。 + +| 维度 | `Reims-GUI-Win`(社区参考) | `reims-go`(本设计) | +| :--- | :--- | :--- | +| 外壳与体积 | Python + PySide6 + PowerShell 7 + 双套 QEMU(Release ~1.68 GB) | Go + Wails(WebView2 原生)+ 单套 `zstd` 便携运行时(预计总下载 ~250–320 MB) | +| 上游耦合方式 | 手写 PowerShell 拼 QEMU 参数与 `fatsync` 改 OpenCore | 直接包装 `reims-ctl`,上游升级只需替换运行时包 | +| 硬件调优 | CPU 预设 + SMBIOS 伪装 | 自动体检 WHPX + 过滤虚拟显卡锁定独显 ICD + 异构大小核 P-Core 绑核 | +| 开发者能力 | 基础创建/启停,`taskkill` 强杀 | GUI + CLI 双模、串口日志流、CoW 派生、QMP/SSH 自动化接口 | diff --git a/docs/portable-runtime-spec.md b/docs/portable-runtime-spec.md new file mode 100644 index 0000000..b516d3a --- /dev/null +++ b/docs/portable-runtime-spec.md @@ -0,0 +1,127 @@ +# 便携运行时规范(Portable Runtime Spec) + +> 实测日期:2026-11-28 +> 基准上游:`steelbrain/reims-vgpu` commit `3731afd9b13416a24f74ec27a90b3913aef2dcc0`(QEMU `11.1.90`,`reims-util 0.1.0`) +> **本地补丁**:本机实测用的 QEMU **不是纯上游构建**。`vendor/qemu`(`4571bc5`)的 `target/i386/whpx/whpx-all.c` 带着一个未提交的修改,内容与 [`macos-vm-lab/patches/qemu-whpx-win10-compat.patch`](../../macos-vm-lab/patches/qemu-whpx-win10-compat.patch)(SHA256 `3eed7895…0304b8`,无 BOM、LF 行尾)一致。没有它,Win10 19045 上 VM 起不来。见第 5 节。 + +## 1. 脱离 MSYS2 / Rust / 源码仓库的实测结论 + +2026-11-28 在本机(Windows 10 19045 x64 + i7-12700K + RTX 4070 Ti)构造了纯净临时环境: +- `PATH` 仅保留便携 `bin\` 与 Windows 系统目录(`System32` / `Wbem` / `WindowsPowerShell`),**完全不含** `MSYS2`、`Cargo/Rust`、`Git`、`reims-vgpu` 源码目录。 +- 通过 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME` 将所有读写重定向至隔离目录。 + +实测结果: + +| 检查项 | 结果 | 说明 | +| :--- | :--- | :--- | +| `qemu-system-x86_64.exe -device help` | ✅ PASS | 正确列出 `reims-graphics-pci`(71 个 CLANG64/libva DLL 已由上游 `install-ctl.sh:783-797` 随 `bin\` 打包) | +| `reims-util.exe --version` | ✅ PASS | 输出 `reims-util 0.1.0` | +| `reims-ctl.exe list --json` | ✅ PASS | 输出 `[]`,无报错 | +| `reims-ctl.exe doctor` — `host` / `files` / `qemu` / `audio` / `hypervisor platform` / `vulkan` / `sound` / `desktop` / `reims-util` | ✅ 9/9 PASS | 全部 `ok`,正确识别 RTX 4070 Ti(`nv-vk64.json`)与 XDG 数据路径 | +| `reims-ctl.exe doctor` — `checkout` | ❌ FAIL(预期内) | 见第 2 节源码分析:仅因 `install.toml` 缺少必填 `repo` 字段,且 `checkout` 仅用于 `reims-ctl update` | + +**结论**:`reims-vgpu` 的 Windows 运行时在二进制层面**已经自包含,可以脱离 MSYS2 与编译环境独立运行**。 + +**限定条件**:这次实测的 `qemu/` 带着第 5 节的 Win10 补丁。纯上游构建在 Win10 上能否启动 VM,没有单独测过(**待验证**)。所以运行时包必须说明自己带了哪些补丁,不能写成「纯上游 `3731afd`」。 + +## 2. 上游源码关键发现(`3731afd`) + +1. **Option ROM 与 Guest Kext 已内嵌**(`crates/reims-ctl/src/prebuilt.rs:1-32`): + - `reims-ctl.exe` 编译时已将 `ReimsGraphics.rom` 与 `guest/prebuilt/set.toml` 内的全部 kext 嵌入二进制,运行时按内容哈希释放到 `/reims-ctl/prebuilt/`,不依赖源码树。 +2. **XDG 路径重定向在 Windows 原生生效**(`crates/reims-ctl/src/paths.rs:54-77`): + - 只要传入 Windows 绝对路径格式的 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME`,`reims-ctl` 与 `reims-util` 均遵守重定向,不会写入 `%USERPROFILE%`。 + - 唯一仍在系统盘的是临时运行目录 `%TEMP%\reims-ctl`(用于短路径 socket,体积极小)。 + - 上游另有两个专用变量,优先级高于 XDG:`REIMS_CTL_CONFIG_DIR`(`paths.rs:61-66`)和 `REIMS_CTL_DATA_DIR`(`paths.rs:68-73`)。它们直接给出 `reims-ctl` 的目录,不再拼 `reims-ctl` 子目录。缓存目录没有专用变量,只认 `XDG_CACHE_HOME`(`paths.rs:75-77`)。`reims-util` 是否认这两个变量**待验证**,所以 `reims-go` 先继续注入 XDG 三件套。 +3. **QEMU 定位优先级**(`crates/reims-ctl/src/install.rs:85-101`): + - 优先读取环境变量 `REIMS_CTL_QEMU`(`qemu-img.exe` 自动从其同级目录查找); + - 未设置时回退到 `\reims-ctl\qemu\current\bin\qemu-system-x86_64.exe`。 +4. **`install.toml` 的 `repo` 字段**(`crates/reims-ctl/src/install.rs:34-50`): + - `Install.repo` 没有 `#[serde(default)]`,省略会导致 `Install::load()` 返回 `None`,令 `doctor` 报 `FAIL checkout`。 + - `reims-go` **不调用 `reims-ctl update`**,而是由自带的 Runtime Manager 下载新版预编译包并原子切换版本目录;自检模块直接消费 `reims-go` 的健康检查,不依赖 `checkout` 项。 + +## 3. 便携运行时体积与目录规范 + +本机实测未压缩体积:**917.8 MB**(`qemu/` 828.5 MB + `reims-ctl.exe` 58.0 MB + `reims-util.exe` 31.3 MB);2026-11-28 实测使用 `zstd -T0 -15` 打包 `reims-runtime-win-x64-3731afd.tar.zst` 后仅 **`160.4 MB`**(压缩率 **17.5%**,不到同类 PySide6 打包方案 1.68 GB 的十分之一)。 + +### 3.1 运行时发布包结构(`reims-runtime-win-x64-.tar.zst`) + +```text +reims-runtime-/ +├── manifest.json # 上游 commit、vendor/qemu commit、补丁清单与哈希、通道、构建日期、各文件 SHA256 +├── NOTICE.md # 上游源码链接与第三方许可声明 +├── licenses/ # GPL-2.0、LGPL-3.0 等许可证原文 +├── patches/ # 本包打上的补丁原文(与 manifest.json 的补丁清单一一对应) +├── bin/ +│ ├── reims-ctl.exe +│ └── reims-util.exe +└── qemu/ + ├── bin/ + │ ├── qemu-system-x86_64.exe + │ ├── qemu-img.exe + │ ├── reims-vgpu-compile.exe + │ └── *.dll # 71 个自包含 CLANG64 + libva/vaon12 DLL + └── share/ # QEMU pc-bios / edk2 / keymaps 等数据文件 +``` + +> **版本耦合约束**:`reims-ctl.exe`、`reims-util.exe` 与 `qemu/` 必须来自**同一个上游 commit**,作为单一版本目录原子安装与回滚,避免协议或内嵌 kext 版本错配。 + +### 3.2 用户数据目录结构(由用户在向导中选择,默认非系统盘如 `D:\Data\reims-go\`) + +```text +/ +├── reims-go.json # reims-go 自身配置(数据目录、默认硬件参数、镜像加速等) +├── runtimes/ +│ ├── / # 解压后的便携运行时(含 bin/ 与 qemu/) +│ └── current -> # 当前激活版本(目录联接或配置文件指向) +├── config/ # 注入为 XDG_CONFIG_HOME(含 reims-ctl/vms.toml) +├── data/ # 注入为 XDG_DATA_HOME(含 reims-ctl/vms/、installers/、prebuilt/) +├── cache/ # 注入为 XDG_CACHE_HOME +└── images/ # Golden Images 与 CoW backing files(M3) +``` + +调用 `reims-ctl.exe` 时,`reims-go` 在子进程环境变量中统一注入: +- `XDG_CONFIG_HOME=\config` +- `XDG_DATA_HOME=\data` +- `XDG_CACHE_HOME=\cache` +- `REIMS_CTL_QEMU=\runtimes\\qemu\bin\qemu-system-x86_64.exe` +- `PATH=\runtimes\\bin;...`(确保 `reims-ctl` 能直接找到同目录的 `reims-util.exe`) + +## 4. 打包与发布流水线(M0 / M4) + +- **本地打包验证(M0)**:编写 `scripts/pack-runtime.ps1`,直接从本机已编译的 `reims-vgpu` 产物生成 `reims-runtime-win-x64-3731afd.tar.zst` 与 `manifest.json`(含 SHA256),验证纯净解压启动。 +- **自动化 CI(M4)**:在 GitHub Actions `windows-latest` runner 上使用 MSYS2 CLANG64,先打上第 5 节的补丁队列,再执行上游构建脚本,产出 `reims-runtime-win-x64-.tar.zst`、`SHA256SUMS.txt` 和对应源码包(第 7 节)。CI 产物只进 `candidate` 通道,不直接发给用户(第 6 节)。 +- **CI 测不到 Win10**:`windows-latest` 是 Windows Server 2022/2025,复现不了第 5 节的 Win10 问题,而且 GitHub 托管 runner 一般不提供 WHPX。CI 只能保证「能构建、`-device help` 列出 `reims-graphics-pci`」,能不能启动 VM 要靠第 6 节的本机冒烟测试。 + +## 5. 补丁队列(把上游当内核来优化的方式) + +原则:**不长期维护 fork,补丁数以清零为目标。** 每个补丁都要经过「本地带着发 → 由人向上游提 PR → 上游合并后删掉本地副本」这个周期。 + +| 补丁 | 作用对象 | 解决的问题 | 状态 | +| :--- | :--- | :--- | :--- | +| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `WHvResetPartition` 在 Win10 上不存在时跳过调用;② `whpx_tsc_deadline_refused()` 改在一个临时分区上探测。原实现在真实分区上建、删 vCPU 0,Win10 19045 上之后再建 vCPU 0 会返回 `E_INVALIDARG`(`0x80070057`) | 本机已用,未提交上游。提 PR 由人来做 | + +规则: +1. 补丁原文的权威副本放在 `reims-go/patches/`。macos-vm-lab 的那份是研究时的原始记录。 +2. 每次跟进上游 commit 时,先 `git apply --check`。打不上就停在 `candidate`,不要自动改补丁。 +3. 补丁文件必须是**无 BOM、LF 行尾**,由 `.gitattributes` 的 `*.patch -text` 保证。用 PowerShell 5.1 的 `Out-File` 或 `>` 生成的补丁会带 BOM 和 CRLF,`git apply` 不认(2026-11-28 实测,原始副本就是这样)。 +4. 上游合并之后,在表里记下合并 commit,然后删掉补丁。 + +## 6. 发布通道(已验证通道) + +上游变动非常快(2026-11-21 到 11-28 有 100 多个提交,截至 2026-11-28 没有任何 GitHub Release),出现过某个提交弄坏 `reims-ctl` 安装的情况([issue #138](https://github.com/steelbrain/reims-vgpu/issues/138))。所以运行时**不跟上游最新 commit**,而是分两级: + +| 通道 | 来源 | 进入条件 | +| :--- | :--- | :--- | +| `candidate` | CI 按指定上游 commit 构建并打补丁 | 能构建;`qemu-system-x86_64.exe -device help` 列出 `reims-graphics-pci`;SHA256 清单齐全 | +| `stable` | 从 `candidate` 升级 | 在一台真实 Win10 或 Win11 宿主上跑通冒烟测试:`doctor` 的运行时检查全部通过,用 golden 镜像启动到 macOS 桌面,截一张屏,正常关机。由人确认后升级 | + +`reims-go` 客户端默认只拉 `stable`,`candidate` 要用户主动打开。这层筛选是 `reims-go` 相对于「自己跑上游安装脚本」的主要价值之一。 + +## 7. 许可证与源码义务 + +发布二进制,就要同时提供对应的源码。只给上游链接不够,因为本地补丁不在上游。每个运行时 Release 附带: +- `reims-vgpu`(含 `reims-ctl`)、`qemu-reims-vgpu`(**含本地补丁**)、`metal2vulkan`、`reims-util` 在所用 commit 的源码包; +- 运行时里 MSYS2 CLANG64 DLL 对应的包名、版本,以及其中 LGPL/GPL 组件(如 glib)的源码或获取方式(具体清单**待 M0.1 打包时列出**); +- `licenses/` 里的许可证全文。 + +`reims-go` 外壳用 MIT,前提是它和这些组件只通过独立进程交互,不链接它们。 diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..09b4939 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,97 @@ +# 开发路线图与里程碑(Roadmap) + +> 原则:先打通“最小可用闭环”(本地打包便携运行时 → Go 核心驱动 → Wails GUI),再扩展自动化与 CI 自动发版。每个里程碑均有明确的可验证验收标准(DoD)。 + +```mermaid +flowchart LR + M0["M0 便携包与环境验证\n(2–3 天)"] --> M1["M1 Go 核心层与 CLI\n(1 周)"] + M1 --> M2["M2 Wails 桌面 GUI MVP\n(1–2 周)"] + M2 --> M3["M3 硬件调优与 CoW/QMP\n(1–2 周)"] + M3 --> M4["M4 CI 自动构建与发版\n(1 周)"] +``` + +--- + +## M0:便携运行时打包与纯净验证 + +**目标**:把本机已验证可用的 `reims-vgpu` 产出一份标准、可复现、可校验的便携运行时压缩包,并在纯净目录中验证完整建机/启动闭环。 + +- [ ] **M0.0**:把 Win10 补丁的来龙去脉记清楚:在 `vendor/qemu` 里 `git diff` 与 `patches/qemu-whpx-win10-compat.patch` 比对一致;用一份**不带补丁**的上游构建在本机启动一次 VM,记下失败现象(作为补丁必要性的证据,也是向上游提 PR 的材料)。 +- [ ] **M0.1**:编写 `scripts/pack-runtime.ps1`,从本地 `reims-vgpu` 安装产物打包 `reims-runtime-win-x64-.tar.zst`、`manifest.json`(含 SHA256、`vendor/qemu` commit、补丁清单与哈希)、`patches/`、`NOTICE.md` 与 `licenses/`,实测压缩体积,并列出包内 MSYS2 DLL 对应的包名与许可证。 +- [ ] **M0.2**:在 `D:\Build\Temp\` 纯净路径中解压该包,验证在不依赖 MSYS2 / Rust / 源码仓库的条件下,可正常 `list --json`、`doctor`(9/9 运行时项通过)并拉起现有 `m0` 虚拟机进入 macOS 桌面。 +- [ ] **M0.3**:在本地初始化 `go.mod` 与 Wails 工具链检查(确认 `wails doctor` 通过)。 + +**DoD**: +- 存在可重复生成的便携运行时包及其 SHA256 清单; +- 脱离 MSYS2 后实测可成功引导 macOS Tahoe 桌面,且 C 盘无新增 reims 文件。 + +--- + +## M1:Go 核心层与 CLI(`reims-go` 无界面闭环) + +**目标**:先用纯 Go 打通所有底层能力与单元测试,确保 CLI 单独就能跑完整个生命周期。 + +- [ ] **M1.1**:`internal/config` + `internal/i18n` — 实现配置持久化(`locale: zh-CN | en-US`、`data_root`)与双语消息字典;`internal/host` 实现 Windows 原生体检(`*_windows.go`)与非 Windows 桩(`*_other.go`,确保 macOS 开发环境可直接 `go test ./...`)。 +- [ ] **M1.2**:`internal/runtime` — 实现便携运行时导入(本地 `.tar.zst` 与 HTTP 下载)、SHA256 校验、原子解压、版本切换与子进程环境变量构造(`XDG_*` + `REIMS_CTL_QEMU`)。 +- [ ] **M1.3**:`internal/driver/reims` — 封装 `reims-ctl` 的 `list --json`、`show`、`create`、`start`、`stop`、`set`、`eject`、`delete`、`logs`,带 Fake CLI 单元测试。 +- [ ] **M1.4**:`cmd/reims-go` — 提供 `doctor`、`runtime install/list/use`、`vm list/create/start/stop/eject/logs` 子命令,支持 `--lang zh|en` 与中英双语输出。 + +**DoD**: +- 在一个从未 dot-source `reims-env.ps1` 的全新 PowerShell 中,仅运行 `reims-go` CLI 即可完成体检、导入运行时、启动/查看 VM; +- `go test ./...` 全通过。 + +--- + +## M2:Wails 桌面 GUI MVP(一站式开箱体验) + +**目标**:做成真正给普通开发者/自己点几下就能用的轻量桌面应用。 + +- [ ] **M2.1**:**首次启动向导(中英双语实时切换)** — 自动识别系统语言(支持顶部一键切换 `中文 / English`);展示环境体检卡片(WHPX、显卡、内存、磁盘);WHPX 未开时提供「一键提权启用并重启」按钮;引导选择非 C 盘数据目录并一键安装/导入便携运行时。 +- [ ] **M2.2**:**VM 主面板** — 实例列表、实时状态、一键启停、实时输出下载进度与串口/图形日志抽屉。 +- [ ] **M2.3**:**创建与装机引导(贴合简体中文 / 英文 macOS 界面术语)** — 选版本(macOS Tahoe)、存放目录、核数、内存、磁盘上限、目标 GPU(默认锁定独显 ICD),安装完毕后突出提示一键 **弹出安装盘(Eject)**。 +- [ ] **M2.4**:打包为单文件 `reims-go.exe`(验证体积与冷启动速度)。 +- [ ] **M2.5**:**设置面板(对齐 macOS)** — 按 [`shell-design.md`](shell-design.md) 第 3 节的类别分页(平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口与日志、高级);VM 运行中也能打开、能改,每个字段标出生效时机;保存前先在 Go 里校验,再调用 `reims-ctl set` 写入;平台类字段只读且脱敏。 +- [ ] **M2.6**:**待生效修改** — 详情页列出「已保存、下次启动才生效」的修改(例如 `cpus 8→12`),提供「重启以应用」按钮;状态模型按 `shell-design.md` 第 4 节实现。 +- [ ] **M2.7**:**主窗口结构** — 侧边栏 + 详情 + 工具栏,新建用分步助手,最后一步显示将执行的 `reims-ctl create` 命令(`shell-design.md` 第 5 节)。 + +**DoD**: +- 双击 `reims-go.exe` 即可走完「体检 → 导入运行时 → 创建/启动 VM → 查看日志 → 弹出安装盘」全流程,无需打开命令行。 +- VM 运行中修改 CPU / 内存 / 显示器数量并保存,重启后 `reims-ctl show` 显示新值;非法输入(如内存超过宿主物理内存、ICD 文件不存在)在保存前被拦下。 +- **可测量的时间目标**:从首次双击到出现 macOS 安装界面 ≤ 10 分钟。不计入:开启 WHPX 后的重启、运行时下载、从 Apple 下载恢复镜像。macOS 图形安装本身的耗时单独实测记录(**待验证**,预计几十分钟),不作为 DoD。 + +--- + +## M3:硬件自动调优与开发者进阶能力 + +**目标**:补齐现有社区 GUI 的空白,对接 `macos-vm-lab` 的工程化需求。 + +- [ ] **M3.1**:**P-Core 自动绑核** — 启动 VM 后自动定位对应 `qemu-system-x86_64.exe` PID 并应用 P-Core 亲和性掩码,界面显示当前绑核状态。 +- [ ] **M3.2**:**QMP 与优雅关机** — 通过 `--extra-args` 接入 QMP,实现运行态监控、优雅关机与截屏(实测验证不与上游内置参数冲突)。 +- [ ] **M3.3**:**Golden Image 与 CoW 秒级派生** — 支持将已装好系统的 VM 标记为模板,用 `qemu-img` 秒级派生临时测试实例,销毁后模板哈希不变。 +- [ ] **M3.4**:**一键打包排障日志** — 收集体检报告、QEMU/串口日志(自动脱敏序列号/MAC/OSK),一键导出 `.zip`。 + +**DoD**: +- P-Core 绑核、QMP 连接、CoW 派生在本机均有实测通过记录。 + +--- + +## M4:GitHub Actions 自动化构建与发布 + +**目标**:彻底自动化上游跟进,用户点「检查更新」即可拉取新版运行时与外壳。 + +- [ ] **M4.1**:编写 GitHub Actions workflow:在 `windows-latest` 上通过 MSYS2 CLANG64,先 `git apply --check` 并打上 `patches/` 补丁队列,再构建指定上游 commit 的 `reims-runtime-win-x64-.tar.zst`、`SHA256SUMS.txt` 与源码包。产物只进 `candidate` 通道。补丁打不上时 workflow 失败,不自动修补丁。 +- [ ] **M4.2**:**`candidate` → `stable` 升级流程**(排在自动发版之前):编写 `scripts/smoke-runtime.ps1`,在真实宿主上解压候选包,跑 `doctor`、用 golden 镜像启动到桌面、截屏、正常关机,输出报告;由人看过报告后再升级为 `stable`。规则见 `portable-runtime-spec.md` 第 6 节。 +- [ ] **M4.3**:自动构建 `reims-go.exe` 并发布 GitHub Release,客户端接入在线版本检查,默认只拉 `stable`,支持一键回滚旧版本。 +- [ ] **M4.4**:补齐 `NOTICE.md`、第三方许可证包、对应源码包(含本地补丁)与安全/合规核验清单(`portable-runtime-spec.md` 第 7 节)。 +- [ ] **M4.5**:补丁上游化:整理 `patches/` 里每个补丁的复现步骤与实测证据,交给人向上游提 PR;合并后从队列删除。 + +**DoD**: +- 触发一次 tag/手动 workflow 即可产出完整的 `candidate`(App + Runtime + SHA256 + 源码包);冒烟通过并经人确认后升为 `stable`;在干净目录下载 `stable` 后,按 M2 的时间目标跑通。 + +--- + +## 不做的事 + +- **不维护长期 fork**:对上游的改动只走补丁队列,目标是清零(见 `portable-runtime-spec.md` 第 5 节)。 +- **不跟踪上游最新 commit**:用户只拿到冒烟过的 `stable`。 +- **暂不实现 `vphone` 等其他 `Engine`**:接口位置先留着,等 x86 macOS 主线稳定后再说。 diff --git a/docs/shell-design.md b/docs/shell-design.md new file mode 100644 index 0000000..016fe53 --- /dev/null +++ b/docs/shell-design.md @@ -0,0 +1,100 @@ +# 外壳设计原语(对齐 macOS) + +> 2026-11-28 起草。上游行为引自 `steelbrain/reims-vgpu` commit `3731afd`,路径相对 `crates/reims-ctl/src/`。 + +## 1. 「对齐 macOS」指什么 + +两层意思,都要做到: + +1. **配置模型对齐 Apple 的虚拟化概念**。界面上的分类、字段名和校验方式,以 Apple [Virtualization.framework](https://developer.apple.com/documentation/virtualization) 的 [`VZVirtualMachineConfiguration`](https://developer.apple.com/documentation/virtualization/vzvirtualmachineconfiguration) 为词表:平台、引导、CPU、内存、存储、网络、图形与显示器、音频、键盘与指针、串口。macOS 用户和做 macOS 开发的人对这套分类最熟悉,以后做 arm64 宿主或者对接 Apple 宿主时,也能直接对上。 +2. **交互对齐 macOS 的人机界面规范**([Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines)): + - 主窗口:左边侧边栏列出 VM,右边是详情,顶部工具栏放常用操作; + - 创建:用分步助手; + - 修改:设置面板按类别分页,像 macOS 的「系统设置」。 + +外壳跑在 Windows 上,但视觉和交互按 macOS 来做,用户进 VM 前后体验一致。Windows 特有的部分(UAC、WHPX、Vulkan ICD)集中放在「宿主」页,不混进 VM 设置。 + +## 2. 三条原语 + +| 原语 | 含义 | 来源 | +| :--- | :--- | :--- | +| **配置是一份声明式文档** | 一台 VM 等于一份配置,界面只编辑它,不直接拼 QEMU 参数 | 对应 `VZVirtualMachineConfiguration`;上游落到 `vm.toml` | +| **先校验,后保存** | 保存前在 Go 里检查一遍(CPU 数、内存上限、GPU ICD 文件是否存在、磁盘控制器切换前是否已弹出安装盘),不合法就不提交 | 对应 `VZVirtualMachineConfiguration.validate()` | +| **随时可编辑,标明生效时机** | 不管 VM 运行与否,设置面板都能打开、能改。每个字段标出何时生效;VM 正在运行时,保存后显示「下次启动生效」和「重启以应用」按钮 | 上游所有 `set` 修改都在下次启动时生效(`cli.rs:73`) | + +写入一律通过 `reims-ctl set`,不直接改 `vm.toml`。这样上游的校验和「改图形时重建 OpenCore 镜像」(`cli.rs:242`)都会照常执行。 + +## 3. 配置项映射 + +生效时机分三种:**下次启动**;**停机时**(只能在 VM 停止时修改,或者修改会触发额外操作);**仅创建时**。 + +| 类别(对齐 VZ) | 界面字段 | `reims-ctl` 参数(`cli.rs:551-616`) | 生效时机 | 备注 | +| :--- | :--- | :--- | :--- | :--- | +| 平台 | Mac 机型、序列号、MLB、UUID、ROM | 存在 OpenCore 的 `config.plist`,`update-opencore` 时保留(`cli.rs:236-248`) | 只读 | 界面只显示是否已设置,**不显示具体值**;日志和排障包里一律脱敏 | +| 引导 | OpenCore 镜像、启动选择 | `update-opencore`、`--boot-selection` | 停机时 | 「重建引导镜像」放在高级操作里 | +| 系统来源 | 下载 Apple 版本 / 本地安装器 / 已有磁盘 | `create --macos`、`--installer`、`--disk`、`--disk-mode` | 仅创建时 | 装好后提示「弹出安装盘」(`eject`) | +| CPU | 核数 | `--cpus` | 下次启动 | 推荐 4 或 8;绑 P 核的开关属于 `reims-go` 自己的功能 | +| 内存 | 大小 | `--memory` | 下次启动 | 上限按宿主物理内存校验 | +| 存储 | 磁盘控制器(SATA / NVMe / virtio) | `--disk-controller` | 下次启动 | 切换前必须先弹出安装盘,否则 OpenCore 可能又从安装盘启动(`cli.rs` 中该参数的说明) | +| 存储 | 磁盘大小 | `create --disk-size` | 仅创建时 | 创建后能否扩容**待验证** | +| 网络 | 开关、SSH 端口转发、MAC | `--network`、`--ssh-port`、`--mac` | 下次启动 | MAC 属于敏感值,默认隐藏 | +| 图形与显示器 | 显卡类型、显示器数量(1–4)、分辨率、无边框全屏、宿主 GPU | `--graphics`、`--displays`、`--resolution`、`--borderless`、`--gpu` | 下次启动;改显卡类型要停机 | GPU 下拉框由 `reims-go` 扫描 ICD 后生成,过滤掉虚拟显示适配器 | +| 音频 | 开关、后端 | `--audio`、`--audio-backend` | 下次启动 | Windows 上的可选后端**待验证** | +| 键盘与指针 | 点击窗口时捕获键鼠 | `--capture` | 下次启动 | — | +| 串口与日志 | 日志开关、日志级别 | `--logs`、`--log-level` | 下次启动 | 日志在详情页抽屉里实时查看 | +| 高级 | 关机等待时间、额外 QEMU 参数、环境变量 | `--stop-timeout`、`--extra-args`、`--env` | 下次启动 | `reims-go` 自己注入的 QMP 参数要和用户填的分开存放、合并写入,不能互相覆盖 | +| (VZ 有,上游没有) | 共享目录、剪贴板、vsock | 无 | — | 先不做,界面上也不放占位 | + +## 4. 状态模型 + +上游 `list --json` 只给三种状态:`running`、`stopped`、`broken`(`cli.rs:816-830`)。 + +`reims-go` 在此基础上加上自己发起操作时的过渡状态,名称对齐 `VZVirtualMachine.State`: + +| 显示状态 | 来源 | 可用操作 | +| :--- | :--- | :--- | +| 已停止 | 上游 `stopped` | 启动、设置、复制派生、删除 | +| 正在启动 | `reims-go` 发起 `start` 到出现 `running` 之间 | 查看日志 | +| 运行中 | 上游 `running` | 关机、强制关机、截屏、弹出安装盘、设置(下次启动生效) | +| 正在停止 | `reims-go` 发起 `stop` 到出现 `stopped` 之间 | 强制关机 | +| 配置损坏 | 上游 `broken` | 打开排障、删除 | + +暂停、保存和恢复状态(VZ 的 `paused`、`saving`、`restoring`)**先不提供**,因为上游没有文档化快照功能,QMP `savevm` 在 reims-vgpu 下能否用**待验证**。 + +状态每秒刷新一次,和上游 TUI 的做法一样(`tui.rs:1-6`),这样在 CLI 里或直接关掉 VM 窗口造成的变化也能及时反映出来。 + +## 5. 界面结构 + +```text +┌ 工具栏:[▶ 启动] [■ 关机] [⏏ 弹出安装盘] [📷 截屏] [⚙ 设置] [+ 新建] ┐ +├──────────────┬───────────────────────────────────────────────────────────────┤ +│ 侧边栏 │ 详情 │ +│ ● m0 运行中 │ 概览:系统版本、CPU / 内存 / 磁盘、GPU、SSH 端口 │ +│ ○ golden │ 待生效的修改(有才显示):cpus 8→12 [重启以应用] │ +│ ○ run-01 │ 日志抽屉:QEMU 输出 / 串口 │ +│ ───────── │ │ +│ 宿主 │ │ +└──────────────┴───────────────────────────────────────────────────────────────┘ +``` + +- **新建助手**(弹出式分步):① 系统来源 → ② CPU 与内存 → ③ 存储 → ④ 图形与 GPU → ⑤ 摘要与校验 → 创建。每一步都能返回,最后一步列出将要执行的 `reims-ctl create` 命令。 +- **设置面板**:左边是第 3 节的类别列表,右边是表单。顶部显示 VM 当前状态,以及这一页修改的生效时机。 +- **宿主页**:WHPX 状态和启用按钮(UAC)、GPU 与 ICD 列表、P/E 核拓扑、数据目录与空间、运行时版本和通道。 + +和上游 TUI 相比,`reims-go` 多出这些东西: +- 「待生效修改」对比和一键重启以应用; +- 保存前在 Go 里预先校验; +- GPU 列表过滤掉虚拟显示适配器; +- 绑 P 核; +- 复制派生(CoW); +- 截屏; +- 运行时通道管理。 + +基础的创建和编辑表单,上游已经有了(`tui.rs`、`form.rs`),不需要再做一套新逻辑,GUI 只换一种呈现方式。 + +## 6. 待验证 + +- `reims-ctl show` 能不能输出 JSON;不能的话,读取配置要解析文本或直接读 `vm.toml`(只读)。 +- 磁盘创建后能否扩容。 +- Windows 上可用的 `--audio-backend` 取值。 +- `reims-go` 注入的 `-qmp tcp:` 与用户的 `--extra-args` 合并后,上游会不会原样传给 QEMU。 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..61dc224 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/Nwflower/reims-go + +go 1.22 diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..1f5f11a --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,106 @@ +package config + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +type Config struct { + DataRoot string `json:"data_root"` + Locale i18n.Locale `json:"locale"` + ActiveRuntime string `json:"active_runtime,omitempty"` + AutoPinPCores bool `json:"auto_pin_pcores"` + DefaultGPU string `json:"default_gpu,omitempty"` +} + +func DefaultDataRoot() string { + if v := os.Getenv("REIMS_GO_DATA_ROOT"); v != "" { + return v + } + if runtime.GOOS == "windows" { + if st, err := os.Stat(`D:\`); err == nil && st.IsDir() { + return `D:\Data\reims-go` + } + } + home, err := os.UserHomeDir() + if err != nil { + return "reims-go-data" + } + return filepath.Join(home, "reims-go-data") +} + +func DefaultConfigPath() string { + return filepath.Join(DefaultDataRoot(), "reims-go.json") +} + +func Default() *Config { + return &Config{ + DataRoot: DefaultDataRoot(), + Locale: i18n.Detect(), + AutoPinPCores: true, + DefaultGPU: "auto", + } +} + +func Load(path string) (*Config, error) { + if path == "" { + path = DefaultConfigPath() + } + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return Default(), nil + } + return nil, err + } + cfg := Default() + if err := json.Unmarshal(raw, cfg); err != nil { + return nil, err + } + if cfg.DataRoot == "" { + cfg.DataRoot = DefaultDataRoot() + } + cfg.Locale = i18n.Normalize(string(cfg.Locale)) + return cfg, nil +} + +func Save(path string, cfg *Config) error { + if path == "" { + path = filepath.Join(cfg.DataRoot, "reims-go.json") + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return err + } + return os.WriteFile(path, append(data, '\n'), 0o644) +} + +func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") } +func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") } +func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") } +func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") } +func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") } + +func (c *Config) EnsureDirs() error { + for _, d := range []string{ + c.DataRoot, + c.RuntimesDir(), + c.XDGConfigDir(), + c.XDGDataDir(), + c.XDGCacheDir(), + c.ImagesDir(), + } { + if err := os.MkdirAll(d, 0o755); err != nil { + return err + } + } + return nil +} diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go new file mode 100644 index 0000000..1c2c107 --- /dev/null +++ b/internal/driver/reims/reims.go @@ -0,0 +1,230 @@ +package reims + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os/exec" + "strconv" + "strings" + + "github.com/Nwflower/reims-go/internal/config" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +// Client wraps reims-ctl invocations using an isolated portable runtime. +type Client struct { + Binary string + Env []string +} + +func NewClient(cfg *config.Config, installed rt.Installed) *Client { + return &Client{ + Binary: installed.ReimsCtlPath(), + Env: rt.BuildChildEnv(cfg, installed), + } +} + +type CreateOpts struct { + Name string `json:"name"` + Dir string `json:"dir,omitempty"` + MacOS string `json:"macos,omitempty"` + CPUs int `json:"cpus,omitempty"` + Memory string `json:"memory,omitempty"` + DiskSize string `json:"disk_size,omitempty"` + Disk string `json:"disk,omitempty"` + DiskMode string `json:"disk_mode,omitempty"` + Graphics string `json:"graphics,omitempty"` + GPU string `json:"gpu,omitempty"` + Resolution string `json:"resolution,omitempty"` + Displays int `json:"displays,omitempty"` + Borderless *bool `json:"borderless,omitempty"` + Audio *bool `json:"audio,omitempty"` + Network *bool `json:"network,omitempty"` + SSHPort int `json:"ssh_port,omitempty"` + Logs *bool `json:"logs,omitempty"` + Start bool `json:"start,omitempty"` +} + +type SetOpts struct { + Name string `json:"name"` + CPUs int `json:"cpus,omitempty"` + Memory string `json:"memory,omitempty"` + Graphics string `json:"graphics,omitempty"` + GPU string `json:"gpu,omitempty"` + Resolution string `json:"resolution,omitempty"` + Displays int `json:"displays,omitempty"` + Borderless *bool `json:"borderless,omitempty"` + Audio *bool `json:"audio,omitempty"` + Network *bool `json:"network,omitempty"` + SSHPort *int `json:"ssh_port,omitempty"` + Logs *bool `json:"logs,omitempty"` + ExtraArgs string `json:"extra_args,omitempty"` +} + +// BuildCreateArgs converts CreateOpts into deterministic reims-ctl CLI arguments. +func BuildCreateArgs(o CreateOpts) ([]string, error) { + if strings.TrimSpace(o.Name) == "" { + return nil, fmt.Errorf("vm name is required") + } + args := []string{"create", o.Name} + if o.Dir != "" { + args = append(args, "--dir", o.Dir) + } + if o.MacOS != "" { + args = append(args, "--macos", o.MacOS) + } + if o.CPUs > 0 { + args = append(args, "--cpus", strconv.Itoa(o.CPUs)) + } + if o.Memory != "" { + args = append(args, "--memory", o.Memory) + } + if o.DiskSize != "" { + args = append(args, "--disk-size", o.DiskSize) + } + if o.Disk != "" { + args = append(args, "--disk", o.Disk) + } + if o.DiskMode != "" { + args = append(args, "--disk-mode", o.DiskMode) + } + if o.Graphics != "" { + args = append(args, "--graphics", o.Graphics) + } + if o.GPU != "" { + args = append(args, "--gpu", o.GPU) + } + if o.Resolution != "" { + args = append(args, "--resolution", o.Resolution) + } + if o.Displays > 0 { + args = append(args, "--displays", strconv.Itoa(o.Displays)) + } + if o.Borderless != nil { + args = append(args, "--borderless", strconv.FormatBool(*o.Borderless)) + } + if o.Audio != nil { + args = append(args, "--audio", strconv.FormatBool(*o.Audio)) + } + if o.Network != nil { + args = append(args, "--network", strconv.FormatBool(*o.Network)) + } + if o.SSHPort > 0 { + args = append(args, "--ssh-port", strconv.Itoa(o.SSHPort)) + } + if o.Logs != nil { + args = append(args, "--logs", strconv.FormatBool(*o.Logs)) + } + if o.Start { + args = append(args, "--start") + } + return args, nil +} + +// BuildSetArgs converts SetOpts into reims-ctl set CLI arguments. +func BuildSetArgs(o SetOpts) ([]string, error) { + if strings.TrimSpace(o.Name) == "" { + return nil, fmt.Errorf("vm name is required") + } + args := []string{"set", o.Name} + if o.CPUs > 0 { + args = append(args, "--cpus", strconv.Itoa(o.CPUs)) + } + if o.Memory != "" { + args = append(args, "--memory", o.Memory) + } + if o.Graphics != "" { + args = append(args, "--graphics", o.Graphics) + } + if o.GPU != "" { + args = append(args, "--gpu", o.GPU) + } + if o.Resolution != "" { + args = append(args, "--resolution", o.Resolution) + } + if o.Displays > 0 { + args = append(args, "--displays", strconv.Itoa(o.Displays)) + } + if o.Borderless != nil { + args = append(args, "--borderless", strconv.FormatBool(*o.Borderless)) + } + if o.Audio != nil { + args = append(args, "--audio", strconv.FormatBool(*o.Audio)) + } + if o.Network != nil { + args = append(args, "--network", strconv.FormatBool(*o.Network)) + } + if o.SSHPort != nil { + args = append(args, "--ssh-port", strconv.Itoa(*o.SSHPort)) + } + if o.Logs != nil { + args = append(args, "--logs", strconv.FormatBool(*o.Logs)) + } + if o.ExtraArgs != "" { + args = append(args, "--extra-args", o.ExtraArgs) + } + return args, nil +} + +func (c *Client) run(ctx context.Context, stdout, stderr io.Writer, args ...string) error { + cmd := exec.CommandContext(ctx, c.Binary, args...) + cmd.Env = c.Env + if stdout != nil { + cmd.Stdout = stdout + } + if stderr != nil { + cmd.Stderr = stderr + } + return cmd.Run() +} + +func (c *Client) ListRaw(ctx context.Context) ([]map[string]any, error) { + var out, errBuf bytes.Buffer + if err := c.run(ctx, &out, &errBuf, "list", "--json"); err != nil { + return nil, fmt.Errorf("reims-ctl list: %w (%s)", err, strings.TrimSpace(errBuf.String())) + } + var list []map[string]any + if err := json.Unmarshal(bytes.TrimSpace(out.Bytes()), &list); err != nil { + return nil, fmt.Errorf("parse list --json: %w", err) + } + return list, nil +} + +func (c *Client) Create(ctx context.Context, o CreateOpts, stdout, stderr io.Writer) error { + args, err := BuildCreateArgs(o) + if err != nil { + return err + } + return c.run(ctx, stdout, stderr, args...) +} + +func (c *Client) Set(ctx context.Context, o SetOpts, stdout, stderr io.Writer) error { + args, err := BuildSetArgs(o) + if err != nil { + return err + } + return c.run(ctx, stdout, stderr, args...) +} + +func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Writer) error { + return c.run(ctx, stdout, stderr, "start", name) +} + +func (c *Client) Stop(ctx context.Context, name string, stdout, stderr io.Writer) error { + return c.run(ctx, stdout, stderr, "stop", name) +} + +func (c *Client) Eject(ctx context.Context, name string, stdout, stderr io.Writer) error { + return c.run(ctx, stdout, stderr, "eject", name) +} + +func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout, stderr io.Writer) error { + args := []string{"delete", name} + if keepFiles { + args = append(args, "--keep-files") + } + return c.run(ctx, stdout, stderr, args...) +} diff --git a/internal/driver/reims/reims_test.go b/internal/driver/reims/reims_test.go new file mode 100644 index 0000000..c959f22 --- /dev/null +++ b/internal/driver/reims/reims_test.go @@ -0,0 +1,36 @@ +package reims + +import ( + "reflect" + "testing" +) + +func TestBuildCreateArgs(t *testing.T) { + logs := true + args, err := BuildCreateArgs(CreateOpts{ + Name: "dev-mac", + Dir: `D:\VMs\dev-mac`, + MacOS: "tahoe", + CPUs: 8, + Memory: "16G", + DiskSize: "128G", + GPU: `C:\nv-vk64.json`, + Logs: &logs, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := []string{ + "create", "dev-mac", + "--dir", `D:\VMs\dev-mac`, + "--macos", "tahoe", + "--cpus", "8", + "--memory", "16G", + "--disk-size", "128G", + "--gpu", `C:\nv-vk64.json`, + "--logs", "true", + } + if !reflect.DeepEqual(args, want) { + t.Fatalf("args mismatch:\n got: %v\nwant: %v", args, want) + } +} diff --git a/internal/host/host.go b/internal/host/host.go new file mode 100644 index 0000000..e0e2ab1 --- /dev/null +++ b/internal/host/host.go @@ -0,0 +1,92 @@ +package host + +import "strings" + +type GPUKind string + +const ( + GPUDiscrete GPUKind = "discrete" + GPUIntegrated GPUKind = "integrated" + GPUVirtual GPUKind = "virtual" + GPUUnknown GPUKind = "unknown" +) + +type GPUInfo struct { + Name string `json:"name"` + VulkanICD string `json:"vulkan_icd"` + Kind GPUKind `json:"kind"` +} + +type WHPXState string + +const ( + WHPXReady WHPXState = "ready" + WHPXNoHypervisor WHPXState = "no_hypervisor" + WHPXMissing WHPXState = "missing" + WHPXUnsupported WHPXState = "unsupported" +) + +type Report struct { + OS string `json:"os"` + Arch string `json:"arch"` + LogicalCPUs int `json:"logical_cpus"` + PhysicalCores int `json:"physical_cores"` + HasHybridCores bool `json:"has_hybrid_cores"` + PCoreCount int `json:"p_core_count"` + ECoreCount int `json:"e_core_count"` + PCoreMask uint64 `json:"p_core_mask"` + PCoreMaskHex string `json:"p_core_mask_hex"` + PCoreLogicalCPUs []int `json:"p_core_logical_cpus,omitempty"` + ECoreLogicalCPUs []int `json:"e_core_logical_cpus,omitempty"` + TotalRAMGB float64 `json:"total_ram_gb"` + AvailRAMGB float64 `json:"avail_ram_gb"` + DataRoot string `json:"data_root"` + FreeDiskGB float64 `json:"free_disk_gb"` + WHPX WHPXState `json:"whpx"` + GPUs []GPUInfo `json:"gpus"` + RecommendedGPU *GPUInfo `json:"recommended_gpu,omitempty"` +} + +// ClassifyGPU distinguishes discrete, integrated, and virtual display adapters. +func ClassifyGPU(name string) GPUKind { + low := strings.ToLower(name) + for _, v := range []string{"todesk", "gameviewer", "parsec", "virtual", "idd", "microsoft basic", "spacedesk"} { + if strings.Contains(low, v) { + return GPUVirtual + } + } + for _, d := range []string{"nvidia", "geforce", "rtx", "gtx", "quadro", "radeon rx", "radeon pro", "intel(r) arc"} { + if strings.Contains(low, d) { + return GPUDiscrete + } + } + for _, i := range []string{"intel(r) uhd", "intel(r) hd", "intel(r) iris", "radeon(tm) graphics"} { + if strings.Contains(low, i) { + return GPUIntegrated + } + } + return GPUUnknown +} + +// PickRecommendedGPU selects the best Vulkan GPU (preferring discrete over integrated, skipping virtual). +func PickRecommendedGPU(gpus []GPUInfo) *GPUInfo { + for i := range gpus { + if gpus[i].Kind == GPUDiscrete && gpus[i].VulkanICD != "" { + cp := gpus[i] + return &cp + } + } + for i := range gpus { + if gpus[i].Kind == GPUIntegrated && gpus[i].VulkanICD != "" { + cp := gpus[i] + return &cp + } + } + for i := range gpus { + if gpus[i].Kind != GPUVirtual && gpus[i].VulkanICD != "" { + cp := gpus[i] + return &cp + } + } + return nil +} diff --git a/internal/host/host_other.go b/internal/host/host_other.go new file mode 100644 index 0000000..635d654 --- /dev/null +++ b/internal/host/host_other.go @@ -0,0 +1,23 @@ +//go:build !windows + +package host + +import ( + "fmt" + "runtime" +) + +// Inspect returns basic host facts on non-Windows dev machines (e.g., macOS). +func Inspect(dataRoot string) Report { + return Report{ + OS: runtime.GOOS, + Arch: runtime.GOARCH, + LogicalCPUs: runtime.NumCPU(), + DataRoot: dataRoot, + WHPX: WHPXUnsupported, + } +} + +func PinProcessToPCores(pid uint32, mask uint64) error { + return fmt.Errorf("P-core affinity pinning is only supported on Windows (current OS: %s)", runtime.GOOS) +} diff --git a/internal/host/host_test.go b/internal/host/host_test.go new file mode 100644 index 0000000..747e2ce --- /dev/null +++ b/internal/host/host_test.go @@ -0,0 +1,24 @@ +package host + +import "testing" + +func TestGPUClassificationAndRecommendation(t *testing.T) { + gpus := []GPUInfo{ + {Name: "Todesk Virtual Display Adapter", VulkanICD: "", Kind: ClassifyGPU("Todesk Virtual Display Adapter")}, + {Name: "Intel(R) UHD Graphics 770", VulkanICD: `C:\igvk64.json`, Kind: ClassifyGPU("Intel(R) UHD Graphics 770")}, + {Name: "NVIDIA GeForce RTX 4070 Ti", VulkanICD: `C:\nv-vk64.json`, Kind: ClassifyGPU("NVIDIA GeForce RTX 4070 Ti")}, + } + if gpus[0].Kind != GPUVirtual { + t.Fatalf("expected virtual, got %s", gpus[0].Kind) + } + if gpus[1].Kind != GPUIntegrated { + t.Fatalf("expected integrated, got %s", gpus[1].Kind) + } + if gpus[2].Kind != GPUDiscrete { + t.Fatalf("expected discrete, got %s", gpus[2].Kind) + } + rec := PickRecommendedGPU(gpus) + if rec == nil || rec.VulkanICD != `C:\nv-vk64.json` { + t.Fatalf("expected NVIDIA discrete GPU to be recommended, got %#v", rec) + } +} diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go new file mode 100644 index 0000000..8f9e44c --- /dev/null +++ b/internal/host/host_windows.go @@ -0,0 +1,273 @@ +//go:build windows + +package host + +import ( + "encoding/binary" + "fmt" + "path/filepath" + "runtime" + "strings" + "syscall" + "unsafe" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetLogicalProcessorInformationEx = kernel32.NewProc("GetLogicalProcessorInformationEx") + procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx") + procGetDiskFreeSpaceExW = kernel32.NewProc("GetDiskFreeSpaceExW") + procOpenProcess = kernel32.NewProc("OpenProcess") + procSetProcessAffinityMask = kernel32.NewProc("SetProcessAffinityMask") + procCloseHandle = kernel32.NewProc("CloseHandle") + + advapi32 = syscall.NewLazyDLL("advapi32.dll") + procRegOpenKeyExW = advapi32.NewProc("RegOpenKeyExW") + procRegQueryValueExW = advapi32.NewProc("RegQueryValueExW") + procRegCloseKey = advapi32.NewProc("RegCloseKey") +) + +const ( + hkeyLocalMachine = 0x80000002 + keyRead = 0x20019 + regSZ = 1 + regExpandSZ = 2 + regMultiSZ = 7 + processSetInformation = 0x0200 + whvCapHypervisorPresent = 0x00000001 +) + +type memoryStatusEx struct { + Length uint32 + MemoryLoad uint32 + TotalPhys uint64 + AvailPhys uint64 + TotalPageFile uint64 + AvailPageFile uint64 + TotalVirtual uint64 + AvailVirtual uint64 + AvailExtendedVirtual uint64 +} + +// Inspect collects Windows host capabilities without requiring administrator privileges. +func Inspect(dataRoot string) Report { + rep := Report{ + OS: "windows", + Arch: runtime.GOARCH, + LogicalCPUs: runtime.NumCPU(), + DataRoot: dataRoot, + WHPX: probeWHPX(), + GPUs: probeVulkanGPUs(), + } + rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs) + + if cores, pCount, eCount, pMask, pLPs, eLPs, ok := probeHybridTopology(); ok { + rep.PhysicalCores = cores + rep.PCoreCount = pCount + rep.ECoreCount = eCount + rep.HasHybridCores = eCount > 0 + rep.PCoreMask = pMask + rep.PCoreMaskHex = fmt.Sprintf("0x%X", pMask) + rep.PCoreLogicalCPUs = pLPs + rep.ECoreLogicalCPUs = eLPs + } + if totalGB, availGB, ok := probeMemoryGB(); ok { + rep.TotalRAMGB = totalGB + rep.AvailRAMGB = availGB + } + if freeGB, ok := probeFreeDiskGB(dataRoot); ok { + rep.FreeDiskGB = freeGB + } + return rep +} + +// PinProcessToPCores restricts the given PID's affinity mask to P-cores. +func PinProcessToPCores(pid uint32, mask uint64) error { + if mask == 0 { + return fmt.Errorf("invalid affinity mask 0") + } + h, _, err := procOpenProcess.Call(uintptr(processSetInformation), 0, uintptr(pid)) + if h == 0 { + return fmt.Errorf("OpenProcess(%d): %w", pid, err) + } + defer procCloseHandle.Call(h) + r, _, err := procSetProcessAffinityMask.Call(h, uintptr(mask)) + if r == 0 { + return fmt.Errorf("SetProcessAffinityMask(%d, 0x%X): %w", pid, mask, err) + } + return nil +} + +func probeWHPX() WHPXState { + mod := syscall.NewLazyDLL("WinHvPlatform.dll") + if err := mod.Load(); err != nil { + return WHPXMissing + } + proc := mod.NewProc("WHvGetCapability") + if err := proc.Find(); err != nil { + return WHPXMissing + } + var capVal uint64 + var written uint32 + hr, _, _ := proc.Call( + uintptr(whvCapHypervisorPresent), + uintptr(unsafe.Pointer(&capVal)), + uintptr(unsafe.Sizeof(capVal)), + uintptr(unsafe.Pointer(&written)), + ) + if int32(hr) < 0 { + return WHPXNoHypervisor + } + if capVal&1 != 0 { + return WHPXReady + } + return WHPXNoHypervisor +} + +func probeHybridTopology() (phys, pCount, eCount int, pMask uint64, pLPs, eLPs []int, ok bool) { + var bufLen uint32 + procGetLogicalProcessorInformationEx.Call(0, 0, uintptr(unsafe.Pointer(&bufLen))) + if bufLen == 0 { + return + } + buf := make([]byte, bufLen) + r, _, _ := procGetLogicalProcessorInformationEx.Call( + 0, // RelationProcessorCore + uintptr(unsafe.Pointer(&buf[0])), + uintptr(unsafe.Pointer(&bufLen)), + ) + if r == 0 { + return + } + type coreRec struct { + eff byte + mask uint64 + } + var cores []coreRec + var maxEff byte + for off := uint32(0); off+48 <= bufLen; { + size := binary.LittleEndian.Uint32(buf[off+4 : off+8]) + if size < 48 || off+size > bufLen { + break + } + eff := buf[off+9] + mask := binary.LittleEndian.Uint64(buf[off+32 : off+40]) + if eff > maxEff { + maxEff = eff + } + cores = append(cores, coreRec{eff: eff, mask: mask}) + off += size + } + if len(cores) == 0 { + return + } + phys = len(cores) + var eMask uint64 + for _, c := range cores { + if c.eff == maxEff { + pCount++ + pMask |= c.mask + } else { + eCount++ + eMask |= c.mask + } + } + for i := 0; i < 64; i++ { + if (pMask>>uint(i))&1 != 0 { + pLPs = append(pLPs, i) + } + if (eMask>>uint(i))&1 != 0 { + eLPs = append(eLPs, i) + } + } + ok = true + return +} + +func probeMemoryGB() (totalGB, availGB float64, ok bool) { + var ms memoryStatusEx + ms.Length = uint32(unsafe.Sizeof(ms)) + r, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&ms))) + if r == 0 { + return 0, 0, false + } + const gb = 1024 * 1024 * 1024 + return float64(ms.TotalPhys) / gb, float64(ms.AvailPhys) / gb, true +} + +func probeFreeDiskGB(path string) (float64, bool) { + vol := filepath.VolumeName(path) + if vol != "" { + path = vol + `\` + } + p, err := syscall.UTF16PtrFromString(path) + if err != nil { + return 0, false + } + var freeBytesAvail, totalBytes, totalFree uint64 + r, _, _ := procGetDiskFreeSpaceExW.Call( + uintptr(unsafe.Pointer(p)), + uintptr(unsafe.Pointer(&freeBytesAvail)), + uintptr(unsafe.Pointer(&totalBytes)), + uintptr(unsafe.Pointer(&totalFree)), + ) + if r == 0 { + return 0, false + } + return float64(freeBytesAvail) / (1024 * 1024 * 1024), true +} + +func probeVulkanGPUs() []GPUInfo { + const baseKey = `SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}` + var out []GPUInfo + for i := 0; i < 32; i++ { + sub := fmt.Sprintf(`%s\%04d`, baseKey, i) + desc, okDesc := regReadString(hkeyLocalMachine, sub, "DriverDesc") + if !okDesc || desc == "" { + continue + } + icd, _ := regReadString(hkeyLocalMachine, sub, "VulkanDriverName") + if icd == "" { + continue + } + out = append(out, GPUInfo{ + Name: desc, + VulkanICD: icd, + Kind: ClassifyGPU(desc), + }) + } + return out +} + +func regReadString(root uintptr, subKey, valueName string) (string, bool) { + sk, err := syscall.UTF16PtrFromString(subKey) + if err != nil { + return "", false + } + var hKey uintptr + r, _, _ := procRegOpenKeyExW.Call(root, uintptr(unsafe.Pointer(sk)), 0, keyRead, uintptr(unsafe.Pointer(&hKey))) + if r != 0 { + return "", false + } + defer procRegCloseKey.Call(hKey) + + vn, err := syscall.UTF16PtrFromString(valueName) + if err != nil { + return "", false + } + var typ, size uint32 + r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), 0, uintptr(unsafe.Pointer(&size))) + if r != 0 || size == 0 { + return "", false + } + buf := make([]uint16, (size+1)/2) + r, _, _ = procRegQueryValueExW.Call(hKey, uintptr(unsafe.Pointer(vn)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))) + if r != 0 { + return "", false + } + if typ != regSZ && typ != regExpandSZ && typ != regMultiSZ { + return "", false + } + // For REG_MULTI_SZ, take the first NUL-terminated entry (64-bit Vulkan ICD JSON). + return strings.TrimSpace(syscall.UTF16ToString(buf)), true +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..9768c8d --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,119 @@ +package i18n + +import ( + "fmt" + "os" + "strings" +) + +type Locale string + +const ( + ZhCN Locale = "zh-CN" + EnUS Locale = "en-US" +) + +// Normalize maps user or OS locale strings to supported locales. +func Normalize(raw string) Locale { + s := strings.ToLower(strings.TrimSpace(raw)) + switch { + case strings.HasPrefix(s, "zh"): + return ZhCN + case strings.HasPrefix(s, "en"): + return EnUS + default: + return ZhCN + } +} + +// Detect returns the preferred locale from REIMS_GO_LANG / LANG / LC_ALL, +// defaulting to zh-CN. +func Detect() Locale { + for _, k := range []string{"REIMS_GO_LANG", "LC_ALL", "LANG"} { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return Normalize(v) + } + } + return ZhCN +} + +var catalog = map[Locale]map[string]string{ + ZhCN: { + "doctor.title": "reims-go 宿主机环境体检", + "doctor.os": "操作系统", + "doctor.cpu": "处理器与核心拓扑", + "doctor.pcores": "P-Core 性能核", + "doctor.ecores": "E-Core 能效核", + "doctor.ram": "宿主机内存", + "doctor.disk": "数据盘剩余空间", + "doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)", + "doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)", + "doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)", + "doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)", + "doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)", + "doctor.gpu": "Vulkan 显卡列表", + "doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动", + "doctor.gpu.recommended": "推荐独显", + "doctor.runtime": "便携运行时", + "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", + "doctor.runtime.active": "当前激活:%s(%s)", + "runtime.installed": "便携运行时已安装:%s -> %s", + "runtime.activated": "已切换激活运行时:%s", + "runtime.empty": "尚未安装任何便携运行时。", + "vm.empty": "当前没有已创建的虚拟机。", + "vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):", + "vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。", + "vm.install_guide.step2": "2. 退出磁盘工具,选择「重新安装 macOS Tahoe」并等待完成。", + "vm.install_guide.step3": "3. 进入桌面后,运行 `reims-go vm eject %s`(或在界面点击「弹出安装盘」)。", + "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", + }, + EnUS: { + "doctor.title": "reims-go Host Environment Check", + "doctor.os": "Operating System", + "doctor.cpu": "CPU & Core Topology", + "doctor.pcores": "P-Cores (Performance)", + "doctor.ecores": "E-Cores (Efficiency)", + "doctor.ram": "Host Memory", + "doctor.disk": "Data Drive Free Space", + "doctor.whpx": "Windows Hypervisor Platform (WHPX)", + "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", + "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", + "doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)", + "doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)", + "doctor.gpu": "Vulkan GPUs", + "doctor.gpu.none": "No registered Vulkan ICD driver found", + "doctor.gpu.recommended": "Recommended discrete GPU", + "doctor.runtime": "Portable Runtime", + "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", + "doctor.runtime.active": "Active: %s (%s)", + "runtime.installed": "Portable runtime installed: %s -> %s", + "runtime.activated": "Active runtime switched to: %s", + "runtime.empty": "No portable runtimes installed.", + "vm.empty": "No virtual machines found.", + "vm.install_guide.title": "macOS Setup Steps (Recovery UI):", + "vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.", + "vm.install_guide.step2": "2. Quit Disk Utility, choose 'Reinstall macOS Tahoe', and wait for completion.", + "vm.install_guide.step3": "3. Once on the desktop, run `reims-go vm eject %s` (or click 'Eject Installer').", + "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", + }, +} + +// T looks up a localized template and formats optional args. +func T(loc Locale, key string, args ...any) string { + table, ok := catalog[loc] + if !ok { + table = catalog[EnUS] + } + tmpl, ok := table[key] + if !ok { + if fallback, ok2 := catalog[EnUS][key]; ok2 { + tmpl = fallback + } else { + return key + } + } + if len(args) == 0 { + return tmpl + } + return fmt.Sprintf(tmpl, args...) +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go new file mode 100644 index 0000000..7da740d --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,23 @@ +package i18n + +import ( + "strings" + "testing" +) + +func TestBilingualCatalog(t *testing.T) { + if got := Normalize("zh_CN.UTF-8"); got != ZhCN { + t.Fatalf("expected zh-CN, got %s", got) + } + if got := Normalize("en_US.UTF-8"); got != EnUS { + t.Fatalf("expected en-US, got %s", got) + } + zhStep := T(ZhCN, "vm.install_guide.step1") + enStep := T(EnUS, "vm.install_guide.step1") + if !strings.Contains(zhStep, "磁盘工具") { + t.Fatalf("zh step should reference Simplified Chinese macOS UI, got %q", zhStep) + } + if !strings.Contains(enStep, "Disk Utility") { + t.Fatalf("en step should reference English macOS UI, got %q", enStep) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go new file mode 100644 index 0000000..847d6cc --- /dev/null +++ b/internal/runtime/runtime.go @@ -0,0 +1,383 @@ +package runtime + +import ( + "archive/zip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/config" +) + +type Manifest struct { + SchemaVersion int `json:"schema_version"` + Name string `json:"name"` + Platform string `json:"platform"` + UpstreamRepo string `json:"upstream_repo"` + Commit string `json:"commit"` + FullCommit string `json:"full_commit"` + QemuVersion string `json:"qemu_version"` + UtilVersion string `json:"util_version"` + BuiltAt string `json:"built_at"` + FileCount int `json:"file_count"` + DLLCount int `json:"dll_count"` + RawBytes int64 `json:"raw_bytes"` + SHA256 map[string]string `json:"sha256"` +} + +type Installed struct { + Commit string `json:"commit"` + Dir string `json:"dir"` + Active bool `json:"active"` + Manifest Manifest `json:"manifest"` +} + +func (r Installed) ReimsCtlPath() string { + name := "reims-ctl" + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(r.Dir, "bin", name) +} + +func (r Installed) ReimsUtilPath() string { + name := "reims-util" + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(r.Dir, "bin", name) +} + +func (r Installed) QemuPath() string { + name := "qemu-system-x86_64" + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(r.Dir, "qemu", "bin", name) +} + +func (r Installed) QemuImgPath() string { + name := "qemu-img" + if runtime.GOOS == "windows" { + name += ".exe" + } + return filepath.Join(r.Dir, "qemu", "bin", name) +} + +// List returns all valid portable runtimes installed under cfg.RuntimesDir(). +func List(cfg *config.Config) ([]Installed, error) { + entries, err := os.ReadDir(cfg.RuntimesDir()) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + return nil, err + } + var out []Installed + for _, e := range entries { + if !e.IsDir() || strings.HasSuffix(e.Name(), ".tmp") { + continue + } + dir := filepath.Join(cfg.RuntimesDir(), e.Name()) + m, err := readManifest(filepath.Join(dir, "manifest.json")) + if err != nil { + continue + } + commit := m.Commit + if commit == "" { + commit = e.Name() + } + out = append(out, Installed{ + Commit: commit, + Dir: dir, + Active: commit == cfg.ActiveRuntime, + Manifest: m, + }) + } + sort.Slice(out, func(i, j int) bool { + return out[i].Manifest.BuiltAt > out[j].Manifest.BuiltAt + }) + return out, nil +} + +// ResolveActive returns the currently active installed runtime. +func ResolveActive(cfg *config.Config) (*Installed, error) { + list, err := List(cfg) + if err != nil { + return nil, err + } + for i := range list { + if list[i].Commit == cfg.ActiveRuntime { + return &list[i], nil + } + } + if len(list) == 1 { + return &list[0], nil + } + return nil, errors.New("no active runtime installed") +} + +// BuildChildEnv returns a clean, D-drive-isolated environment for invoking reims-ctl. +func BuildChildEnv(cfg *config.Config, rt Installed) []string { + binDir := filepath.Join(rt.Dir, "bin") + overrides := map[string]string{ + "XDG_CONFIG_HOME": cfg.XDGConfigDir(), + "XDG_DATA_HOME": cfg.XDGDataDir(), + "XDG_CACHE_HOME": cfg.XDGCacheDir(), + "REIMS_CTL_QEMU": rt.QemuPath(), + } + env := os.Environ() + out := make([]string, 0, len(env)+len(overrides)) + seenPath := false + for _, kv := range env { + idx := strings.IndexByte(kv, '=') + if idx <= 0 { + continue + } + k := kv[:idx] + v := kv[idx+1:] + if strings.EqualFold(k, "PATH") { + out = append(out, k+"="+binDir+string(os.PathListSeparator)+v) + seenPath = true + continue + } + skip := false + for ok := range overrides { + if strings.EqualFold(k, ok) { + skip = true + break + } + } + if !skip { + out = append(out, kv) + } + } + if !seenPath { + out = append(out, "PATH="+binDir) + } + for k, v := range overrides { + out = append(out, k+"="+v) + } + return out +} + +// InstallFromArchive verifies and atomically extracts a .tar.zst or .zip runtime archive. +func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, error) { + if err := cfg.EnsureDirs(); err != nil { + return nil, err + } + if err := verifySidecarSHA256(archivePath); err != nil { + return nil, err + } + + tmpDir, err := os.MkdirTemp(cfg.RuntimesDir(), "install-*.tmp") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmpDir) + + low := strings.ToLower(archivePath) + switch { + case strings.HasSuffix(low, ".tar.zst"): + if err := extractTarZst(archivePath, tmpDir); err != nil { + return nil, err + } + case strings.HasSuffix(low, ".zip"): + if err := extractZip(archivePath, tmpDir); err != nil { + return nil, err + } + default: + return nil, fmt.Errorf("unsupported archive format: %s (expected .tar.zst or .zip)", archivePath) + } + + bundleDir, err := findBundleRoot(tmpDir) + if err != nil { + return nil, err + } + m, err := readManifest(filepath.Join(bundleDir, "manifest.json")) + if err != nil { + return nil, fmt.Errorf("read manifest.json: %w", err) + } + if m.Commit == "" { + return nil, errors.New("manifest.json missing commit") + } + for rel, expected := range m.SHA256 { + fp := filepath.Join(bundleDir, filepath.FromSlash(rel)) + got, err := fileSHA256(fp) + if err != nil { + return nil, fmt.Errorf("hash %s: %w", rel, err) + } + if !strings.EqualFold(got, expected) { + return nil, fmt.Errorf("SHA256 mismatch for %s: expected %s, got %s", rel, expected, got) + } + } + + finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit) + _ = os.RemoveAll(finalDir) + if err := os.Rename(bundleDir, finalDir); err != nil { + return nil, fmt.Errorf("activate runtime dir: %w", err) + } + return &Installed{ + Commit: m.Commit, + Dir: finalDir, + Active: true, + Manifest: m, + }, nil +} + +func readManifest(path string) (Manifest, error) { + var m Manifest + raw, err := os.ReadFile(path) + if err != nil { + return m, err + } + // Strip UTF-8 BOM if written by Windows PowerShell Set-Content -Encoding utf8. + raw = []byte(strings.TrimPrefix(string(raw), "\uFEFF")) + err = json.Unmarshal(raw, &m) + return m, err +} + +func findBundleRoot(dir string) (string, error) { + if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err == nil { + return dir, nil + } + entries, err := os.ReadDir(dir) + if err != nil { + return "", err + } + for _, e := range entries { + if e.IsDir() { + sub := filepath.Join(dir, e.Name()) + if _, err := os.Stat(filepath.Join(sub, "manifest.json")); err == nil { + return sub, nil + } + } + } + return "", errors.New("manifest.json not found in extracted runtime archive") +} + +func verifySidecarSHA256(archivePath string) error { + sidecar := archivePath + ".sha256" + raw, err := os.ReadFile(sidecar) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err + } + fields := strings.Fields(string(raw)) + if len(fields) == 0 { + return nil + } + got, err := fileSHA256(archivePath) + if err != nil { + return err + } + if !strings.EqualFold(got, fields[0]) { + return fmt.Errorf("archive SHA256 mismatch: expected %s, got %s", fields[0], got) + } + return nil +} + +func fileSHA256(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +func extractTarZst(archivePath, destDir string) error { + // Windows 10/11 built-in bsdtar supports .tar.zst natively on modern builds; + // fall back to zstd -dc | tar -xf if needed. + cmd := exec.Command("tar", "-xf", archivePath, "-C", destDir) + if out, err := cmd.CombinedOutput(); err == nil { + return nil + } else { + zstdBin := findZstd() + if zstdBin == "" { + return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out))) + } + z := exec.Command(zstdBin, "-dc", archivePath) + t := exec.Command("tar", "-xf", "-", "-C", destDir) + pipe, err := z.StdoutPipe() + if err != nil { + return err + } + t.Stdin = pipe + if err := z.Start(); err != nil { + return err + } + tOut, tErr := t.CombinedOutput() + zErr := z.Wait() + if tErr != nil { + return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut))) + } + return zErr + } +} + +func findZstd() string { + for _, c := range []string{"zstd", `D:\DevTools\msys64\usr\bin\zstd.exe`, `D:\DevTools\msys64\clang64\bin\zstd.exe`} { + if p, err := exec.LookPath(c); err == nil { + return p + } + } + return "" +} + +func extractZip(archivePath, destDir string) error { + r, err := zip.OpenReader(archivePath) + if err != nil { + return err + } + defer r.Close() + for _, f := range r.File { + target := filepath.Join(destDir, f.Name) + if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(destDir)+string(os.PathSeparator)) { + return fmt.Errorf("illegal zip path: %s", f.Name) + } + if f.FileInfo().IsDir() { + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + continue + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + rc, err := f.Open() + if err != nil { + return err + } + out, err := os.Create(target) + if err != nil { + rc.Close() + return err + } + _, copyErr := io.Copy(out, rc) + rc.Close() + closeErr := out.Close() + if copyErr != nil { + return copyErr + } + if closeErr != nil { + return closeErr + } + } + return nil +} diff --git a/patches/README.md b/patches/README.md new file mode 100644 index 0000000..114a747 --- /dev/null +++ b/patches/README.md @@ -0,0 +1,13 @@ +# 上游临时补丁队列(Upstream Patch Queue) + +本目录仅存放**尚未被上游合入的最小兼容性补丁**,由本地打包脚本与 CI 构建流程在编译 `vendor/qemu` 前通过 `git apply` 自动应用。 + +## 原则 +1. **内核/引擎 Bug 优先上游化**:补丁同步提交 PR/Issue 给上游(`steelbrain/qemu-reims-vgpu` / `steelbrain/reims-vgpu`),绝不长期维护独立 fork。 +2. **合入即退役**:一旦上游目标 commit 包含等价修复,立即从本目录移除对应补丁文件。 + +## 当前补丁清单 + +| 文件 | 目标仓库 / 基准 commit | 解决的问题 | 上游状态 | +| :--- | :--- | :--- | :--- | +| `qemu-whpx-win10-compat.patch` | `steelbrain/qemu-reims-vgpu` (`4571bc5`) | 修复 Windows 10 19045 上 WHPX 两处必现崩溃:① `whpx_tsc_deadline_refused()` 在正式 partition 上删建 vCPU 0 导致 `WHvCreateVirtualProcessor` 返回 `0x80070057`;② `whpx_set_registers()` 调用 Win11 新增的 `WHvResetPartition` 未判空导致 `0xc0000005` 崩溃 | 待提交上游 PR | diff --git a/patches/qemu-whpx-win10-compat.patch b/patches/qemu-whpx-win10-compat.patch new file mode 100644 index 0000000..9836d5b --- /dev/null +++ b/patches/qemu-whpx-win10-compat.patch @@ -0,0 +1,77 @@ +diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c +index 5aa46bc..4ef32ee 100644 +--- a/target/i386/whpx/whpx-all.c ++++ b/target/i386/whpx/whpx-all.c +@@ -530,7 +530,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level) + assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu)); + + /* Assumes that cpu_synchronize_all_post_reset() runs cpu 0 first. */ +- if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0) { ++ if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0 && ++ whp_dispatch.WHvResetPartition) { + hr = whp_dispatch.WHvResetPartition(whpx->partition); + if (FAILED(hr)) { + error_report("WHPX: Failed to reset partition, hr=%08lx", hr); +@@ -3211,22 +3212,56 @@ static bool whpx_tsc_deadline_refused(void) + { + WHV_REGISTER_NAME name = WHvX64RegisterTscDeadline; + WHV_REGISTER_VALUE value = {}; ++ WHV_PARTITION_HANDLE probe = NULL; ++ WHV_PARTITION_PROPERTY prop = {}; + HRESULT hr; ++ bool refused = false; + +- hr = whp_dispatch.WHvCreateVirtualProcessor(whpx_global.partition, 0, 0); ++ /* ++ * Probe on a throwaway partition: on Windows 10 (e.g. 19045), deleting ++ * vCPU 0 on the real partition causes a subsequent WHvCreateVirtualProcessor ++ * for vCPU 0 in whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057). ++ */ ++ hr = whp_dispatch.WHvCreatePartition(&probe); + if (FAILED(hr)) { + return false; + } +- hr = whp_dispatch.WHvSetVirtualProcessorRegisters(whpx_global.partition, +- 0, &name, 1, &value); +- whp_dispatch.WHvDeleteVirtualProcessor(whpx_global.partition, 0); ++ prop.ProcessorCount = 1; ++ hr = whp_dispatch.WHvSetPartitionProperty( ++ probe, WHvPartitionPropertyCodeProcessorCount, &prop, sizeof(prop)); ++ if (FAILED(hr)) { ++ goto out; ++ } ++ if (whpx_irqchip_in_kernel()) { ++ WHV_X64_LOCAL_APIC_EMULATION_MODE mode = ++ WHvX64LocalApicEmulationModeX2Apic; ++ hr = whp_dispatch.WHvSetPartitionProperty( ++ probe, WHvPartitionPropertyCodeLocalApicEmulationMode, ++ &mode, sizeof(mode)); ++ if (FAILED(hr)) { ++ goto out; ++ } ++ } ++ hr = whp_dispatch.WHvSetupPartition(probe); ++ if (FAILED(hr)) { ++ goto out; ++ } ++ hr = whp_dispatch.WHvCreateVirtualProcessor(probe, 0, 0); ++ if (FAILED(hr)) { ++ goto out; ++ } ++ hr = whp_dispatch.WHvSetVirtualProcessorRegisters(probe, 0, &name, 1, &value); ++ whp_dispatch.WHvDeleteVirtualProcessor(probe, 0); + if (FAILED(hr)) { + warn_report("WHPX: Hyper-V refuses the TSC deadline timer's register," + " hr=%08lx: the guest is offered no TSC deadline timer", + hr); +- return true; ++ refused = true; + } +- return false; ++ ++out: ++ whp_dispatch.WHvDeletePartition(probe); ++ return refused; + } + + int whpx_accel_init(AccelState *as, MachineState *ms) diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 new file mode 100644 index 0000000..756b817 --- /dev/null +++ b/scripts/pack-runtime.ps1 @@ -0,0 +1,147 @@ +<# +.SYNOPSIS + Pack a standalone, MSYS2-free portable reims-vgpu runtime bundle for Windows x64. + +.DESCRIPTION + Collects reims-ctl.exe, reims-util.exe, and the self-contained QEMU directory + (with its bundled CLANG64/libva DLLs and share/ data), generates manifest.json + with SHA-256 hashes, copies NOTICE.md and upstream LICENSE files, and compresses + the bundle into a .tar.zst archive (falling back to .zip if zstd is unavailable). + +.EXAMPLE + .\scripts\pack-runtime.ps1 + .\scripts\pack-runtime.ps1 -OutDir D:\Data\reims-go\releases -ZstdLevel 15 +#> +[CmdletBinding()] +param( + [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$CargoBin = 'D:\DevTools\cargo\bin', + [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', + [string]$OutDir = 'D:\Data\reims-go\releases', + [string]$TempRoot = 'D:\Build\Temp', + [int]$ZstdLevel = 15 +) + +$ErrorActionPreference = 'Stop' + +function Resolve-Zstd { + $candidates = @( + (Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source), + 'D:\DevTools\msys64\usr\bin\zstd.exe', + 'D:\DevTools\msys64\clang64\bin\zstd.exe' + ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } + return ($candidates | Select-Object -First 1) +} + +# 1. Verify inputs +$ctlExe = Join-Path $CargoBin 'reims-ctl.exe' +$utilExe = Join-Path $CargoBin 'reims-util.exe' +$qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe' +foreach ($p in @($ctlExe, $utilExe, $qemuExe)) { + if (-not (Test-Path -LiteralPath $p)) { + throw "Required runtime binary not found: $p" + } +} + +$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim() +$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim() +$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() +$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() + +$bundleName = "reims-runtime-win-x64-$commit" +$stageRoot = Join-Path $TempRoot "pack-$bundleName" +$bundleDir = Join-Path $stageRoot $bundleName + +if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot } +New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", $OutDir | Out-Null + +Write-Host "==> Staging $bundleName ..." +Copy-Item -LiteralPath $ctlExe -Destination "$bundleDir\bin\reims-ctl.exe" +Copy-Item -LiteralPath $utilExe -Destination "$bundleDir\bin\reims-util.exe" + +# Resolve junction target so robocopy/copy gets real files cleanly +$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target +if (-not $resolvedQemu) { $resolvedQemu = $QemuDir } +Copy-Item -Path "$resolvedQemu\*" -Destination "$bundleDir\qemu" -Recurse -Force + +# Copy NOTICE.md and upstream license(s) +$repoRoot = Split-Path -Parent $PSScriptRoot +Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md" +$upstreamLicense = Join-Path $ReimsRepo 'LICENSE' +if (Test-Path -LiteralPath $upstreamLicense) { + Copy-Item -LiteralPath $upstreamLicense -Destination "$bundleDir\licenses\reims-vgpu-LICENSE.txt" +} +$qemuLicense = Join-Path $ReimsRepo 'vendor\qemu\COPYING' +if (Test-Path -LiteralPath $qemuLicense) { + Copy-Item -LiteralPath $qemuLicense -Destination "$bundleDir\licenses\qemu-COPYING.txt" +} + +# 2. Compute file inventory & key hashes +$allFiles = Get-ChildItem -LiteralPath $bundleDir -Recurse -File +$rawBytes = ($allFiles | Measure-Object Length -Sum).Sum +$dllCount = @(Get-ChildItem -Path "$bundleDir\qemu\bin\*.dll" -ErrorAction SilentlyContinue).Count + +$keyFiles = @( + 'bin/reims-ctl.exe', + 'bin/reims-util.exe', + 'qemu/bin/qemu-system-x86_64.exe', + 'qemu/bin/qemu-img.exe', + 'qemu/bin/reims-vgpu-compile.exe' +) +$hashes = [ordered]@{} +foreach ($rel in $keyFiles) { + $fp = Join-Path $bundleDir ($rel -replace '/', '\') + if (Test-Path -LiteralPath $fp) { + $hashes[$rel] = (Get-FileHash -Algorithm SHA256 -LiteralPath $fp).Hash.ToLowerInvariant() + } +} + +$manifest = [ordered]@{ + schema_version = 1 + name = $bundleName + platform = 'windows-x86_64' + upstream_repo = 'https://github.com/steelbrain/reims-vgpu' + commit = $commit + full_commit = $fullCommit + qemu_version = $qemuVersionLine + util_version = $utilVersionLine + built_at = (Get-Date).ToString('o') + file_count = $allFiles.Count + dll_count = $dllCount + raw_bytes = $rawBytes + sha256 = $hashes +} +$manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath "$bundleDir\manifest.json" -Encoding utf8 + +# 3. Compress +$zstd = Resolve-Zstd +$archivePath = $null +if ($zstd) { + $tarPath = Join-Path $stageRoot "$bundleName.tar" + $archivePath = Join-Path $OutDir "$bundleName.tar.zst" + Write-Host "==> Creating tar archive..." + & tar.exe -cf $tarPath -C $stageRoot $bundleName + if ($LASTEXITCODE -ne 0) { throw "tar.exe failed with exit code $LASTEXITCODE" } + Write-Host "==> Compressing with zstd (level $ZstdLevel, multi-threaded)..." + & $zstd -T0 -$ZstdLevel -f $tarPath -o $archivePath + if ($LASTEXITCODE -ne 0) { throw "zstd failed with exit code $LASTEXITCODE" } +} else { + $archivePath = Join-Path $OutDir "$bundleName.zip" + Write-Host "==> zstd not found; compressing with Compress-Archive (.zip)..." + Compress-Archive -Path $bundleDir -DestinationPath $archivePath -Force +} + +$archiveSizeMB = [math]::Round((Get-Item -LiteralPath $archivePath).Length / 1MB, 1) +$rawSizeMB = [math]::Round($rawBytes / 1MB, 1) +$archiveHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archivePath).Hash.ToLowerInvariant() +"$archiveHash $(Split-Path -Leaf $archivePath)" | Set-Content -LiteralPath "$archivePath.sha256" -Encoding ascii + +# 4. Clean staging dir +Remove-Item -Recurse -Force -LiteralPath $stageRoot + +Write-Host "" +Write-Host "==> Done!" -ForegroundColor Green +Write-Host " Archive : $archivePath" +Write-Host " Raw : $rawSizeMB MB ($($allFiles.Count) files, $dllCount DLLs)" +Write-Host " Packed : $archiveSizeMB MB (ratio $([math]::Round($archiveSizeMB / $rawSizeMB * 100, 1))%)" +Write-Host " SHA256 : $archiveHash"