Compare commits

...
Author SHA1 Message Date
YXC0915 975889078f release: prepare v0.2.13
Release Reims-Go / release (push) Canceled after 0s
Archive the bilingual changelog and synchronize the app and frontend release versions.
2026-12-04 21:57:55 +08:00
Xiaochi You 90a9e476d2 Merge pull request #168 from yxc0915/codex/fix-precision-log-severity
fix(logs): 修正 QEMU 精度提示误报为错误
2026-12-04 21:36:30 +08:00
YXC0915 d4c2099de9 docs(changelog): record the precision log fix 2026-12-04 21:29:54 +08:00
YXC0915 2e480d99b7 fix(logs): classify successful Metal precision notes as info
Ignore the Metal selector when a QEMU message reports a successful precision note. Reuse the same severity for log rows and the unread-error badge.
2026-12-04 21:23:18 +08:00
Nwflower 8b467563c7 Merge branch 'ci/review-code-only' 2026-12-04 05:16:10 -07:00
千川白浪 0ba805754e Merge pull request #135 from icaruszezen/fix/vm-delete-cleanup-and-dir-check
fix(vm,ui): retry deleted VM directory cleanup and validate non-empty target dirs
2026-12-04 18:43:04 +08:00
千川白浪 254eacc937 Merge pull request #152 from ELDment/feat/auto-apply-qemu-aslr
feat(host,ui): add a switch to auto-apply ASLR to the selected QEMU runtime
2026-12-04 18:38:02 +08:00
NwflowerandClaude Opus 5.5 c7db42ac03 fix(vm): keep the directory of a running create when cloning
A running reims-ctl create looks the same as a killed one: it is unregistered and has no vm.toml until it ends. Cloning or creating through the driver no longer deletes such a directory. Also drop a wrapper only tests called.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 03:36:45 -07:00
NwflowerandClaude Opus 5.5 cc1daf32d8 Merge branch 'main' into fix/vm-delete-cleanup-and-dir-check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 03:36:45 -07:00
ELDment e9dc282fb0 Merge upstream/main into feat/auto-apply-qemu-aslr 2026-12-04 18:27:09 +08:00
ELDment c665f32627 Merge upstream/main into feat/auto-apply-qemu-aslr 2026-12-04 18:07:22 +08:00
IcarusZezen 1752f03df8 fix(vm): harden delete cleanup, target dir validation, and monitor timeouts 2026-12-04 09:38:41 +08:00
IcarusZezen fce4de7b82 Merge branch 'main' into fix/vm-delete-cleanup-and-dir-check 2026-12-04 09:23:08 +08:00
ELDment 77cb246c66 Merge upstream/main into feat/auto-apply-qemu-aslr 2026-12-04 08:37:47 +08:00
ELDment a8b7894208 fix(runtime): keep QEMU ASLR in sync across runtime and data folder changes 2026-12-04 08:11:39 +08:00
ELDment 7049f3e388 fix(runtime): separate ASLR repair from VM start and retry activation 2026-12-03 23:37:43 +08:00
ELDment f1eeff2ee3 fix(runtime): keep ASLR updates responsive and follow runtime switches 2026-12-03 23:23:55 +08:00
ELDment b43cd9e16e feat(host,ui): add a switch to auto-apply ASLR to the selected QEMU runtime 2026-12-03 22:56:16 +08:00
千川白浪 a7f6d6a4b7 fix(vm): reconcile partial deletes and check all driver directories
model: magpie-responses/codex/gpt-6.2-sol
agent: Codex
2026-12-03 22:18:02 +08:00
千川白浪 e2cb665bee fix(vm): protect registered VM data during directory cleanup
model: magpie-responses/codex/gpt-6.2-sol
agent: Codex
2026-12-03 22:10:43 +08:00
Nwflower 164ea7f7ba ci: keep PR reviews focused on code findings 2026-12-03 04:50:41 -07:00
IcarusZezen d09990709e fix(vm,ui): retry deleted VM directory cleanup and validate non-empty target dirs 2026-12-03 14:18:26 +08:00
106 changed files with 3890 additions and 682 deletions

No files matched your search

-44
View File
@@ -16,33 +16,11 @@ export const english = {
coverageComplete: "Complete for the selected scope",
findings: "Reported defects",
withheld: "Candidates missing required evidence fields",
evidenceIncomplete: "Some candidates lack the evidence needed to assess them.",
questions: "Decisions needed before merging",
clarify: "Clarify the expected behavior",
clarifyReason: "Resolve the contract questions above before merging.",
warnings: "Incomplete review tasks",
tests: "CI for this PR commit",
ciRun: "CI run",
ciPassed: "Passed",
ciFailed: "Failed",
ciNoPass: "No passing result",
ciActionRequired: "CI needs manual action.",
ciPending: "Pending",
ciMissing: "No CI run found for this commit.",
recommendation: "Merge recommendation",
merge: "Ready to merge",
changes: "Revise and review again",
inspect: "Review the remaining changes",
awaitCI: "No code blockers found. Awaiting CI.",
conflict: "GitHub detected merge conflicts. Resolve them and request another review.",
mainMoved: "The default branch moved during this review.",
ciRequired: "This commit has no passing CI result yet.",
fixCI: "Resolve the CI failure before merging.",
fixFindings: "Address the actionable findings below before merging.",
incomplete: "Some changes or review tasks were not covered; complete the review before merging.",
inline: "Inline findings",
unanchored: "Findings without a stable inline diff anchor",
noFindings: "No actionable issues found in the reviewed changes.",
noDiff: "No reviewable text changes remained after generated and lock files were excluded.",
inlineFallback: "GitHub could not attach inline comments. See the findings below.",
};
@@ -65,33 +43,11 @@ export const chinese = {
coverageComplete: "已完成所选范围",
findings: "已报告缺陷",
withheld: "缺少必需证据字段的候选意见",
evidenceIncomplete: "部分候选意见缺少必要证据,需要人工核对。",
questions: "合并前需确认的问题",
clarify: "确认预期行为",
clarifyReason: "合并前确认上方列出的行为约定。",
warnings: "未完成的审查任务",
tests: "当前 PR 提交的 CI",
ciRun: "CI 运行记录",
ciPassed: "通过",
ciFailed: "失败",
ciNoPass: "无通过结果",
ciActionRequired: "CI 需要人工处理。",
ciPending: "尚未完成",
ciMissing: "未找到对应提交的 CI 记录。",
recommendation: "合并建议",
merge: "可以合并",
changes: "修改后再审",
inspect: "先审完剩余改动",
awaitCI: "代码未见阻塞,等待 CI",
conflict: "GitHub 检测到合并冲突,解决后重新审核。",
mainMoved: "审核期间主线有更新。",
ciRequired: "当前提交还没有 CI 通过记录。",
fixCI: "合并前处理 CI 失败项。",
fixFindings: "合并前处理下方有证据的实质问题。",
incomplete: "部分改动或审查任务未覆盖,合并前补齐审查。",
inline: "行内问题",
unanchored: "无法稳定定位到差异行的有效问题",
noFindings: "已审核的差异中未发现可报告的问题。",
noDiff: "排除生成文件与锁文件后,没有可审核的文本改动。",
inlineFallback: "GitHub 未能附加行内评论,审核意见如下。",
};
+3 -68
View File
@@ -434,25 +434,6 @@ async function listChangedFiles(github, path) {
return files.slice(0, MAX_FILES);
}
export async function waitForCI(github, repoPath, pull, number, { wait = false } = {}) {
if (wait) throw new Error("CI polling is disabled for PR review");
if (pull.base.ref !== pull.base.repo.default_branch || !pull.head.repo) return { status: "unavailable" };
const path = repoPath + "/actions/workflows/ci.yml/runs?event=pull_request&per_page=20&head_sha=" + pull.head.sha;
const { data } = await github(path);
const run = data.workflow_runs.find((run) => run.head_sha === pull.head.sha
&& run.head_repository?.full_name === pull.head.repo.full_name && run.head_branch === pull.head.ref
&& (!run.pull_requests.length || run.pull_requests.some((pr) => pr.number === Number(number))));
if (run?.status !== "completed") return { status: run?.status ?? "unavailable", id: run?.id, attempt: run?.run_attempt, url: run?.html_url };
const { data: jobs } = await github(repoPath + "/actions/runs/" + run.id + "/attempts/" + run.run_attempt + "/jobs");
const verify = jobs.jobs.find((job) => job.name === "verify");
const steps = verify?.steps.filter((step) => /^(CI tests|Frontend test|Go test|Bundle frontend|Build reims-go|WebView2)/.test(step.name));
return {
status: "completed", id: run.id, attempt: run.run_attempt, url: run.html_url,
conclusion: verify?.conclusion ?? run.conclusion,
steps: (steps ?? []).map(({ name, conclusion }) => ({ name, conclusion })),
};
}
async function mainlineContext(github, repoPath, pull, files) {
const branch = pull.base.repo.default_branch;
const refPath = repoPath + "/git/ref/heads/" + encodeURIComponent(branch);
@@ -482,21 +463,12 @@ async function mainlineContext(github, repoPath, pull, files) {
};
}
export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, total = 0, withheld = 0, questions = [], fallback = [] }) {
export function reviewSummary(copy, assessment, { incomplete, total = 0, withheld = 0, questions = [], fallback = [] }) {
const lines = [];
lines.push("- **" + copy.coverage + "** " + (incomplete ? copy.coveragePartial : copy.coverageComplete));
lines.push("- **" + copy.findings + "** " + total);
if (withheld) lines.push("- **" + copy.withheld + "** " + withheld);
if (assessment.warnings?.length) lines.push("- **" + copy.warnings + "** " + assessment.warnings.length);
const ciPassed = ci.status === "completed" && ci.conclusion === "success";
const ciFailed = ci.status === "completed" && ["failure", "timed_out"].includes(ci.conclusion);
const ciNeedsAction = ci.conclusion === "action_required" || ci.status === "action_required";
let ciStatus = ci.id ? copy.ciPending : copy.ciMissing;
if (ciNeedsAction) ciStatus = copy.ciActionRequired;
else if (ciPassed) ciStatus = copy.ciPassed;
else if (ci.status === "completed") ciStatus = (ciFailed ? copy.ciFailed : copy.ciNoPass) + " (`" + ci.conclusion + "`)";
lines.push("\n**" + copy.tests + "** " + ciStatus + (ci.url ? " · [" + copy.ciRun + "](" + ci.url + ")" : ""));
for (const step of ci.steps ?? []) lines.push("- " + plainMarkdown(step.name) + " · " + plainMarkdown(step.conclusion ?? "—"));
if (fallback.length) {
lines.push("\n**" + copy.unanchored + "**");
for (const finding of fallback) lines.push(summaryFinding(finding));
@@ -505,31 +477,6 @@ export function reviewSummary(copy, assessment, ci, { incomplete, mergeable, tot
lines.push("\n**" + copy.questions + "**");
for (const question of questions) lines.push("- " + plainMarkdown(shortText(question, 500)));
}
let decision = "merge";
let reason = copy.noFindings;
if (mergeable === false) {
decision = "changes";
reason = copy.conflict;
} else if (ciFailed) {
decision = "changes";
reason = copy.fixCI;
} else if (total > 0) {
decision = "changes";
reason = copy.fixFindings;
} else if (incomplete) {
decision = "inspect";
reason = copy.incomplete;
} else if (withheld) {
decision = "inspect";
reason = copy.evidenceIncomplete;
} else if (questions.length) {
decision = "clarify";
reason = copy.clarifyReason;
} else if (!ciPassed) {
decision = "awaitCI";
reason = copy.ciRequired;
}
lines.push("\n**" + copy.recommendation + " · " + copy[decision] + "** " + reason);
return lines.join("\n");
}
@@ -967,18 +914,6 @@ export async function run() {
return current.state === "open" && snapshot(current).join(":") === revision ? current : null;
}
if (!(await currentPR())) {
console.log("PR changed while the review was running");
return;
}
let ci;
try {
ci = await waitForCI(github, repoPath, pull, number, { wait: false });
} catch (error) {
console.warn("Could not read current CI status: " + error.message);
ci = { status: "unavailable" };
}
const latestPR = await currentPR();
if (!latestPR) {
console.log("PR changed before the review could be published");
return;
}
@@ -1000,8 +935,8 @@ export async function run() {
const incremental = range.incremental ? "\n\n" + copy.incremental + " `" + range.lastHeadSha.slice(0, 12) + "`" : "";
const incomplete = assessment.status === "partial" || assessment.status === "completed_with_errors"
|| assessment.warnings.length > 0 || (assessment.status === "skipped" && stats.files > 0);
const summaryBody = reviewSummary(copy, assessment, ci, {
incomplete, mergeable: latestPR.mergeable, total, withheld, questions, fallback,
const summaryBody = reviewSummary(copy, assessment, {
incomplete, total, withheld, questions, fallback,
});
const publishedMarker = reviewMarker(pull, mainline.sha, incomplete);
const summary = publishedMarker + "\n## " + copy.heading + "\n\n" + copy.mainline + " `" + mainline.sha.slice(0, 12) + "` · " + coverage
+16 -40
View File
@@ -29,7 +29,6 @@ import {
reviewWithOCR,
selectReviewRange,
shouldSkipAutoReview,
waitForCI,
} from "./pr-review.mjs";
const A = "a".repeat(40);
@@ -225,8 +224,8 @@ test("finding filtering sorts severity and renders plain single-line and multi-l
assert.doesNotMatch(result.comments[1].body, /suggestion|keepOldConfig/);
assert.equal(result.fallback.length, 1);
assert.equal(result.total, 3);
assert.match(reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "success" }, {
incomplete: false, mergeable: true, total: 3, fallback: result.fallback,
assert.match(reviewSummary(chinese, { comments: [], warnings: [] }, {
incomplete: false, total: 3, fallback: result.fallback,
}), /无法稳定定位到差异行的有效问题[\s\S]*99.*backup is rejected/);
});
@@ -241,7 +240,7 @@ test("public reviews retain prose around model code blocks and require opt-in fo
assert.doesNotMatch(comment.body, /callMissingMethod|cancelTask|```/);
const [suggestion] = classifyFindings(input, locations, { publishSuggestions: true }).comments;
assert.match(suggestion.body, /```suggestion\ncancelTask\(id\)\n```/);
const summary = reviewSummary(english, { message: "One issue found.\n~~~js\nignoreThis()\n~~~" }, {}, {});
const summary = reviewSummary(english, { message: "One issue found.\n~~~js\nignoreThis()\n~~~" }, {});
assert.match(summary, /Reported defects.*0/);
assert.doesNotMatch(summary, /One issue found/);
assert.doesNotMatch(summary, /ignoreThis/);
@@ -275,50 +274,27 @@ test("publication requires evidence and keeps merge-relevant contract questions
assert.equal(result.withheld, 3);
assert.equal(result.questions.length, 1);
assert.ok(result.comments.every(({ body }) => !/Trigger:|Impact:|Evidence:/.test(body)));
const summary = reviewSummary(english, { warnings: [{}], message: "8 findings" }, { status: "completed", conclusion: "success" }, { ...result, incomplete: true });
const summary = reviewSummary(english, { warnings: [{}], message: "8 findings" }, { ...result, incomplete: true });
assert.match(summary, /Review coverage.*Incomplete/);
assert.match(summary, /Reported defects.*3/);
assert.match(summary, /Decisions needed before merging[\s\S]*Should an open dialog close/);
assert.doesNotMatch(summary, /8 findings/);
const questionOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { incomplete: false, questions: result.questions });
assert.match(questionOnly, /Clarify the expected behavior/);
const withheldOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { withheld: 3 });
assert.match(withheldOnly, /Some candidates lack the evidence/);
const questionOnly = reviewSummary(english, {}, { incomplete: false, questions: result.questions });
assert.match(questionOnly, /Decisions needed before merging/);
const withheldOnly = reviewSummary(english, {}, { withheld: 3 });
assert.match(withheldOnly, /Candidates missing required evidence fields.*3/);
assert.doesNotMatch(withheldOnly, /Ready to merge/);
});
const pull = {
base: { ref: "main", repo: { default_branch: "main" } },
head: { sha: B, ref: "feature", repo: { full_name: "fork/Reims-Go" } },
};
const run = { id: 100, run_attempt: 2, head_sha: B, head_branch: "feature", head_repository: pull.head.repo, pull_requests: [] };
test("CI publication lookup is a single non-blocking request and preserves step summaries", async () => {
let calls = 0;
const queued = await waitForCI(async () => {
calls++;
return { data: { workflow_runs: [{ ...run, status: "queued" }] } };
}, "/repos/test/Reims-Go", pull, 42, { wait: false });
assert.equal(queued.status, "queued");
assert.equal(calls, 1);
const passed = await waitForCI(async (route) => route.endsWith("/100/attempts/2/jobs")
? { data: { jobs: [{ name: "verify", conclusion: "success", steps: [{ name: "Go test", conclusion: "success" }] }] } }
: { data: { workflow_runs: [{ ...run, status: "completed", conclusion: "success", html_url: "https://github.com/test/run/100" }] } },
"/repos/test/Reims-Go", pull, 42, { wait: false });
const summary = reviewSummary(english, { message: "No issues", comments: [], warnings: [] }, passed, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(summary, /Go test · success/);
assert.match(summary, /Ready to merge/);
const waiting = reviewSummary(chinese, { comments: [], warnings: [] }, queued, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(waiting, /代码未见阻塞,等待 CI/);
});
test("CI failures and incomplete OCR results affect the final recommendation independently", () => {
const failed = reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "failure" }, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(failed, /修改后再审/);
assert.match(failed, /处理 CI 失败项/);
const partial = reviewSummary(chinese, { comments: [], warnings: [{}] }, { status: "completed", conclusion: "success" }, { incomplete: true, mergeable: true, hasFindings: false });
assert.match(partial, /先审完剩余改动/);
test("a code-only review reports coverage and defects without restating GitHub checks", () => {
const complete = reviewSummary(english, { warnings: [] }, { incomplete: false });
assert.match(complete, /Review coverage.*Complete for the selected scope/);
assert.match(complete, /Reported defects.*0/);
assert.doesNotMatch(complete, /CI|merge/i);
const partial = reviewSummary(chinese, { warnings: [{}] }, { incomplete: true });
assert.match(partial, /审查覆盖.*部分完成/);
assert.match(partial, /未完成的审查任务/);
assert.doesNotMatch(partial, /CI|合并建议/);
});
async function fakeOCR(t, { exitCode = 0, stdout = null } = {}) {
+94
View File
@@ -4,6 +4,100 @@
Client releases are listed newest first. Release notes for portable runtimes (`runtime-*`) are available on [GitHub Releases](https://github.com/Nwflower/Reims-Go/releases).
## v0.2.13 — 2026-12-04
[中文](#cn-v0.2.13) | [English](#en-v0.2.13)
<h3 id="cn-v0.2.13">新增功能</h3>
- 支持在 Windows 与 macOS 虚拟机之间复制粘贴文件和文件夹。Windows 中剪切的文件可粘贴到 macOS,原文件和剪切状态会保留。可在插件页或虚拟机设置中调整文件同步和传输上限。已有虚拟机可更新至 Guest Tools `v21`,一并获得双向文件同步和最新拖放修复。 [#108](https://github.com/Nwflower/Reims-Go/pull/108) — [@YinLiaoCo](https://github.com/YinLiaoCo), [@staytomorrow](https://github.com/staytomorrow), [@yxc0915](https://github.com/yxc0915)
- 可在设置中开启快捷键,在虚拟机窗口内切换无边框全屏。默认关闭,默认组合键为 `Ctrl+Shift+F`,可自行录制。 — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 支持由插件接入非 macOS 虚拟机,可在客户端查看其状态,并通过 SSH、WSL、远程桌面、Hyper-V 连接或 ADB 打开。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。 — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- 启用内置的「macOS 应用窗口」插件后,可从运行中的虚拟机菜单把单屏 macOS 客体的前台应用打开为 Windows 无边框窗口,并在宿主与客体之间复制粘贴。 [#118](https://github.com/Nwflower/Reims-Go/pull/118) — [@yxc0915](https://github.com/yxc0915)
- 沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。 — [@Nwflower](https://github.com/Nwflower)
- 「内核」页新增 QEMU ASLR 开关,默认关闭。启用后,虚拟机冷启动时可能恢复 Dock 图标。规则随运行时版本切换,关闭时仅移除自动添加的规则。 — [@ELDment](https://github.com/ELDment)
- 「设置」页新增默认关闭的「Hyper-V 启动切换」选项,开启后可确认切换 Windows Hypervisor 下次启动状态以兼容独占模式的 VMware,并在「内核」页区分 Hypervisor 关闭与 BIOS 虚拟化未开启。 [#122](https://github.com/Nwflower/Reims-Go/issues/122) — [@Dnyo666](https://github.com/Dnyo666)
### 体验优化
- 运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。 — [@Nwflower](https://github.com/Nwflower)
### 问题修复
- 修复 macOS 剪贴板含有无法读取的格式时,无法粘贴从 Windows 复制的文件的问题。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- 修复虚拟机交互期间的启停、挂起和截图输入竞争,清理桌面重启后遗留的 MCP 临时虚拟机,并确保 MCP 控制通道在长请求、输入结束和请求失败时正确传递响应。登录密码通过键盘输入,不再经过客体剪贴板。 — [@bvzrays](https://github.com/bvzrays)
- 文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。 — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Windows 文件复制到 macOS 时,挂载文件不可读会改用下载回退。诊断报告会记录客体确认写入文件剪贴板的次数。 — [@yxc0915](https://github.com/yxc0915)
- 修复 QEMU 的 Metal 精度提示误标为错误,避免这些提示增加未读错误计数。 — [@yxc0915](https://github.com/yxc0915)
- 修复放入默认共享文件夹的文件在虚拟机中不显示或同步过慢的问题,移动便携目录后共享文件夹也会使用新位置。升级后需在虚拟机内重新安装 Guest Tools。 — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 清理无法恢复的挂起残留,并在 Windows 短暂占用文件时重试封存和清理。挂起和恢复支持存放在长路径下的虚拟机。已有可恢复状态时,启动会提示先恢复或放弃该状态。 [#109](https://github.com/Nwflower/Reims-Go/pull/109) — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- 修复物理网卡绑定 Hyper-V 外部虚拟交换机后无法启用 Npcap 桥接的问题,自动使用关联管理虚拟网卡的地址转发宿客流量。 — [@ssdsl0126](https://github.com/ssdsl0126)
- 修复文件同步或 WebDAV 挂载耗时较长时,虚拟机中的 Win → ⌘ 快捷键意外打开 Windows 开始菜单的问题。 — [@reiasu2](https://github.com/reiasu2)
- 修复 MCP 创建临时 macOS 虚拟机时的名称校验错误,并开放已授权虚拟机的挂起和恢复操作。 — [@Nwflower](https://github.com/Nwflower)
- 在插件列表和设置中提示当前运行时不支持的插件设置。 — [@cosimawei](https://github.com/cosimawei)
- 修复插件设置中的已保存密钥在清空后仍显示旧掩码,以及连续修改同一设置时保存顺序错乱的问题。 — [@bvzrays](https://github.com/bvzrays)
- 修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。 — [@Nwflower](https://github.com/Nwflower)
- 从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。 — [@Nwflower](https://github.com/Nwflower)
- 修复删除虚拟机后可能因文件句柄占用残留旧目录并在重建同名虚拟机时报错的问题。删除前先等待日志监控退出并关闭桥接通道,注销后目录仍被短暂占用时自动重试清理;同时在新建向导、命令行与克隆前提前校验目标目录是否非空,避免保留文件或残留目录拖到建机阶段才失败。删除和清理残留目录前检查其中是否有其他已注册虚拟机的数据。 — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- 修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。 — [@Nwflower](https://github.com/Nwflower)
### 移除
- 主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。 — [@Nwflower](https://github.com/Nwflower)
### 其他变更
- 新建 Issue 后自动提示补充信息、疑似重复和提交位置,并定期诊断代码、创建改进 Issue。 — [@Nwflower](https://github.com/Nwflower)
- PR 自动审查改用 OpenCodeReview,支持隔离的只读仓库分析、跨提交增量审查和即时 CI 状态。 — [@Nwflower](https://github.com/Nwflower)
- 提高 PR 自动审查的 token 预算,部分任务出错时仍发布已完成的审查结果。 — [@Nwflower](https://github.com/Nwflower)
- 自动审查要求说明缺陷触发条件、实际后果和代码证据,并在摘要中显示覆盖状态。 — [@Nwflower](https://github.com/Nwflower)
- 自动审查意见优先说明触发条件和实际后果,默认省略代码建议。 — [@Nwflower](https://github.com/Nwflower)
<h3 id="en-v0.2.13">New Features</h3>
- Copy and paste files and folders between Windows and macOS VMs. Pasting files cut in Windows into macOS preserves the original files and the Windows cut state. Adjust file sync and transfer limits in the plugin or VM settings. Update Guest Tools to `v21` in existing VMs for bidirectional file sync and the latest drag-and-drop fixes. [#108](https://github.com/Nwflower/Reims-Go/pull/108) — [@YinLiaoCo](https://github.com/YinLiaoCo), [@staytomorrow](https://github.com/staytomorrow), [@yxc0915](https://github.com/yxc0915)
- Add an optional shortcut in Settings to toggle borderless full screen from the VM window. It is off by default, uses `Ctrl+Shift+F`, and can be customized. — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Let plugins add non-macOS VMs, with their state shown in the app and access through SSH, WSL, Remote Desktop, VMConnect, or ADB. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and the `pkg/drivertest` contract test suite is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74)). — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- Enable the built-in macOS App Windows plugin to open the foreground app from a running, single-display macOS VM in a borderless Windows window, with copy and paste between host and guest. [#118](https://github.com/Nwflower/Reims-Go/pull/118) — [@yxc0915](https://github.com/yxc0915)
- Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage. — [@Nwflower](https://github.com/Nwflower)
- Add an opt-in QEMU ASLR switch on the Engine page. It may restore missing Dock icons after a cold start. Rules follow the selected runtime. Turning it off removes only Reims-Go's rules. — [@ELDment](https://github.com/ELDment)
- Add an opt-in Hyper-V boot switch in Settings to toggle Windows Hypervisor launch on next boot for exclusive-mode VMware coexistence, and distinguish hypervisor launch off from disabled BIOS virtualization on the Engine page. [#122](https://github.com/Nwflower/Reims-Go/issues/122) — [@Dnyo666](https://github.com/Dnyo666)
### Improvements
- Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`. — [@Nwflower](https://github.com/Nwflower)
### Bug Fixes
- Fix pasting files copied from Windows when the macOS clipboard contains an unreadable format. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- Fix races between VM lifecycle and console operations, clean up orphaned MCP temporary VMs after desktop restarts, and preserve MCP control-channel responses during long requests, input shutdown, and request failures. Login passwords are entered as keystrokes without passing through the guest clipboard. — [@bvzrays](https://github.com/bvzrays)
- File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs. — [@YinLiaoCo](https://github.com/YinLiaoCo)
- When Windows clipboard files cannot be read from the mounted share on macOS, Guest Tools uses the download fallback. Diagnostics count file clipboard writes confirmed by the guest. — [@yxc0915](https://github.com/yxc0915)
- Show QEMU Metal precision notes as informational logs so they do not increase the unread error count. — [@yxc0915](https://github.com/yxc0915)
- Fix files added to the default shared folder not appearing or syncing slowly in the VM, and use the new location after moving a portable directory. Reinstall Guest Tools in the VM after upgrading. — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Clean up orphaned suspend files and retry sealing or cleaning up state when Windows briefly holds the files open. Suspend and resume support VMs stored under long paths. Starting a VM with a recoverable state asks you to resume or discard it first. [#109](https://github.com/Nwflower/Reims-Go/pull/109) — [@reiasu2](https://github.com/reiasu2), [@Nwflower](https://github.com/Nwflower)
- Fix Npcap bridging when a physical adapter is bound to a Hyper-V external virtual switch by using its associated management adapter for host and guest traffic. — [@ssdsl0126](https://github.com/ssdsl0126)
- Fix Win → Command shortcuts opening the Windows Start menu during slow file sync or WebDAV mounting. — [@reiasu2](https://github.com/reiasu2)
- Fix name validation for temporary macOS VMs created by MCP and expose suspend and resume for authorized VMs. — [@Nwflower](https://github.com/Nwflower)
- Show which settings the active runtime does not support in the plugin list and settings dialog. — [@cosimawei](https://github.com/cosimawei)
- Fix saved plugin secrets remaining masked after being cleared and preserve save order when the same setting is edited repeatedly. — [@bvzrays](https://github.com/bvzrays)
- Keep the highlight on the current option of a segmented control after it was briefly disabled while saving. — [@Nwflower](https://github.com/Nwflower)
- Include Guest Tools and network log lines when a VM fails to start from the command line. — [@Nwflower](https://github.com/Nwflower)
- Fix deleted VMs leaving behind their directory on Windows due to transient file locks and breaking subsequent creation of a VM with the same name. Wait for the log monitor to exit and close bridge sockets before deletion, retry directory removal if the VM was already unregistered, and validate non-empty target directories upfront in the create wizard, CLI, and clone flows. Check whether another registered VM uses the directory before removing it. — [@icaruszezen](https://github.com/icaruszezen), [@Nwflower](https://github.com/Nwflower)
- Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off. — [@Nwflower](https://github.com/Nwflower)
### Removals
- Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds. — [@Nwflower](https://github.com/Nwflower)
### Chores
- Guide new issues with missing details, possible duplicates, and where to submit them, and regularly diagnose the code to open improvement issues. — [@Nwflower](https://github.com/Nwflower)
- Use OpenCodeReview for PR reviews with isolated read-only repository analysis, incremental commit ranges, and non-blocking CI status. — [@Nwflower](https://github.com/Nwflower)
- Raise the token budget for automated PR reviews and publish completed results when some review tasks fail. — [@Nwflower](https://github.com/Nwflower)
- Require automated review findings to include a trigger, impact, and code evidence, and report coverage in the summary. — [@Nwflower](https://github.com/Nwflower)
- Automated PR reviews lead with the trigger and impact and omit code suggestions by default. — [@Nwflower](https://github.com/Nwflower)
## v0.2.12 — 2026-12-03
[中文](#cn-v0.2.12) | [English](#en-v0.2.12)
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["YinLiaoCo"],
"zh": "修复 macOS 剪贴板含有无法读取的格式时,无法粘贴从 Windows 复制的文件的问题。",
"en": "Fix pasting files copied from Windows when the macOS clipboard contains an unreadable format."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["YinLiaoCo", "staytomorrow", "yxc0915"],
"zh": "支持在 Windows 与 macOS 虚拟机之间复制粘贴文件和文件夹。Windows 中剪切的文件可粘贴到 macOS,原文件和剪切状态会保留。可在插件页或虚拟机设置中调整文件同步和传输上限。已有虚拟机需将 Guest Tools 更新至 `v16` 以使用双向文件同步。",
"en": "Copy and paste files and folders between Windows and macOS VMs. Pasting files cut in Windows into macOS preserves the original files and the Windows cut state. Adjust file sync and transfer limits in the plugin or VM settings. Update Guest Tools to `v16` in existing VMs for bidirectional file sync."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["bvzrays"],
"zh": "修复虚拟机交互期间的启停、挂起和截图输入竞争,清理桌面重启后遗留的 MCP 临时虚拟机,并确保 MCP 控制通道在长请求、输入结束和请求失败时正确传递响应。登录密码通过键盘输入,不再经过客体剪贴板。",
"en": "Fix races between VM lifecycle and console operations, clean up orphaned MCP temporary VMs after desktop restarts, and preserve MCP control-channel responses during long requests, input shutdown, and request failures. Login passwords are entered as keystrokes without passing through the guest clipboard."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["YinLiaoCo"],
"zh": "文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。",
"en": "File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["yxc0915"],
"zh": "Windows 文件复制到 macOS 时,挂载文件不可读会改用下载回退。诊断报告会记录客体确认写入文件剪贴板的次数。",
"en": "When Windows clipboard files cannot be read from the mounted share on macOS, Guest Tools uses the download fallback. Diagnostics count file clipboard writes confirmed by the guest."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "修复放入默认共享文件夹的文件在虚拟机中不显示或同步过慢的问题,移动便携目录后共享文件夹也会使用新位置。升级后需在虚拟机内重新安装 Guest Tools。",
"en": "Fix files added to the default shared folder not appearing or syncing slowly in the VM, and use the new location after moving a portable directory. Reinstall Guest Tools in the VM after upgrading."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "自动清理无法恢复的挂起残留,避免它们阻止再次挂起,并修复 Windows 上文件仍被短暂占用时挂起封存或清理失败的问题。挂起与恢复支持存放在长路径下的虚拟机。已保存可恢复快照的虚拟机在启动时会改为拒绝并提示先恢复或放弃挂起状态,旧版启动入口同样适用,不再直接冷启动覆盖快照。",
"en": "Clear orphaned suspend files that block later suspend attempts and avoid snapshot publication or cleanup failures when Windows files are briefly still in use. Suspend and resume also support VMs stored under long paths. A VM that holds a recoverable snapshot now refuses to start and asks you to resume or discard that state first, including through the older start path, instead of cold-starting over the snapshot."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["reiasu2", "Nwflower"],
"zh": "可在设置中开启快捷键,在虚拟机窗口内切换无边框全屏。默认关闭,默认组合键为 `Ctrl+Shift+F`,可自行录制。",
"en": "Add an optional shortcut in Settings to toggle borderless full screen from the VM window. It is off by default, uses `Ctrl+Shift+F`, and can be customized."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["icaruszezen", "Nwflower"],
"zh": "支持由插件接入非 macOS 虚拟机,可在客户端查看其状态,并通过 SSH、WSL、远程桌面、Hyper-V 连接或 ADB 打开。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。",
"en": "Let plugins add non-macOS VMs, with their state shown in the app and access through SSH, WSL, Remote Desktop, VMConnect, or ADB. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and the `pkg/drivertest` contract test suite is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74))."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["ssdsl0126"],
"zh": "修复物理网卡绑定 Hyper-V 外部虚拟交换机后无法启用 Npcap 桥接的问题,自动使用关联管理虚拟网卡的地址转发宿客流量。",
"en": "Fix Npcap bridging when a physical adapter is bound to a Hyper-V external virtual switch by using its associated management adapter for host and guest traffic."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "新建 Issue 后自动提示补充信息、疑似重复和提交位置,并定期诊断代码、创建改进 Issue。",
"en": "Guide new issues with missing details, possible duplicates, and where to submit them, and regularly diagnose the code to open improvement issues."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "修复文件同步或 WebDAV 挂载耗时较长时,虚拟机中的 Win → ⌘ 快捷键意外打开 Windows 开始菜单的问题。",
"en": "Fix Win → Command shortcuts opening the Windows Start menu during slow file sync or WebDAV mounting."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["yxc0915"],
"zh": "启用「macOS 应用窗口」内置插件后,可在 Windows 无边框窗口中操作虚拟机的前台应用,并在宿主与客体之间复制粘贴。",
"en": "Enable the built-in macOS App Windows plugin to use a VM’s foreground app in a borderless Windows window with bidirectional copy and paste."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复 MCP 创建临时 macOS 虚拟机时的名称校验错误,并开放已授权虚拟机的挂起和恢复操作。",
"en": "Fix name validation for temporary macOS VMs created by MCP and expose suspend and resume for authorized VMs."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "PR 自动审查改用 OpenCodeReview,支持隔离的只读仓库分析、跨提交增量审查和即时 CI 状态。",
"en": "Use OpenCodeReview for PR reviews with isolated read-only repository analysis, incremental commit ranges, and non-blocking CI status."
}
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["cosimawei"],
"zh": "在插件列表和设置中提示当前运行时不支持的插件设置。",
"en": "Show which settings the active runtime does not support in the plugin list and settings dialog."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["bvzrays"],
"zh": "修复插件设置中的已保存密钥在清空后仍显示旧掩码,以及连续修改同一设置时保存顺序错乱的问题。",
"en": "Fix saved plugin secrets remaining masked after being cleared and preserve save order when the same setting is edited repeatedly."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["Nwflower"],
"zh": "沙箱页面插件新增四种视图位置、宿主表单与导航、虚拟机和设置访问、授权文件读写、任务进度、受控网络请求及事件订阅,并支持确认、复制、外链和私有存储。",
"en": "Add four view locations, host forms and navigation, VM and settings access, authorized file I/O, task progress, controlled HTTP requests, and event subscriptions to sandboxed plugins, alongside confirmations, clipboard copy, external links, and private storage."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "提高 PR 自动审查的 token 预算,部分任务出错时仍发布已完成的审查结果。",
"en": "Raise the token budget for automated PR reviews and publish completed results when some review tasks fail."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "自动审查要求说明缺陷触发条件、实际后果和代码证据,并在摘要中显示覆盖状态。",
"en": "Require automated review findings to include a trigger, impact, and code evidence, and report coverage in the summary."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "chores",
"order": 0,
"authors": ["Nwflower"],
"zh": "自动审查意见优先说明触发条件和实际后果,默认省略代码建议。",
"en": "Automated PR reviews lead with the trigger and impact and omit code suggestions by default."
}
-9
View File
@@ -1,9 +0,0 @@
{
"group": "improvements",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。",
"en": "Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。",
"en": "Keep the highlight on the current option of a segmented control after it was briefly disabled while saving."
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "new",
"order": 0,
"authors": ["Dnyo666"],
"zh": "「设置」页新增默认关闭的「Hyper-V 启动切换」选项,开启后可确认切换 Windows Hypervisor 下次启动状态以兼容独占模式的 VMware,并在「内核」页区分 Hypervisor 关闭与 BIOS 虚拟化未开启。 [#122](https://github.com/Nwflower/Reims-Go/issues/122)",
"en": "Add an opt-in Hyper-V boot switch in Settings to toggle Windows Hypervisor launch on next boot for exclusive-mode VMware coexistence, and distinguish hypervisor launch off from disabled BIOS virtualization on the Engine page. [#122](https://github.com/Nwflower/Reims-Go/issues/122)"
}
-7
View File
@@ -1,7 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": ["Nwflower"],
"zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。",
"en": "Include Guest Tools and network log lines when a VM fails to start from the command line."
}
-9
View File
@@ -1,9 +0,0 @@
{
"group": "removals",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。",
"en": "Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds."
}
-9
View File
@@ -1,9 +0,0 @@
{
"group": "fixes",
"order": 0,
"authors": [
"Nwflower"
],
"zh": "修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。",
"en": "Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off."
}
+2 -2
View File
@@ -75,9 +75,9 @@ OCR 输出中的 `critical`、`high`、`medium` 且非 style/documentation 问
发布前检查每条缺陷是否说明当前代码中的触发条件、可观察后果,以及已有保护为何无法阻止它。审核规则要求核对实际调用方、权限、掩码和事件过滤。影响本次合并且需要维护者明确约定的问题只在摘要展示。摘要分别显示审查覆盖、已报告缺陷和缺少必需字段的候选意见数。
审核启动后不再等待 CI。发布 Review 前只做一次即时查询,附上当前 PR 提交的 CI 记录和关键步骤。CI 排队、需要人工处理或缺少通过记录时,代码无实质问题的结论为「代码未见阻塞,等待 CI」。OCR 部分完成、存在失败任务、主线对照覆盖不全或 PR 文件列表截断时会标明覆盖限制。回复语言由 PR 正文去除代码块、引用和模板标题后的文字决定,含中文时使用中文,否则参考标题并使用英文。
自动代码审核与 CI 并行运行。Review 摘要只展示代码审查结果,CI 状态和合并条件由 GitHub 的检查列表与合并区展示。OCR 部分完成、存在失败任务、主线对照覆盖不全或 PR 文件列表截断时会标明覆盖限制。回复语言由 PR 正文去除代码块、引用和模板标题后的文字决定,含中文时使用中文,否则参考标题并使用英文。
工作流直接缓存并校验官方 Release 的单个静态二进制,不安装 Node 依赖或运行 `npm install`。全部外部 Action 固定到 commit SHA,workflow 顶层 `permissions` 为空。GitHub App 需要读取 Contents 和 Actions、写入 Pull requests,并仅安装到目标仓库。
工作流直接缓存并校验官方 Release 的单个静态二进制,不安装 Node 依赖或运行 `npm install`。全部外部 Action 固定到 commit SHA,workflow 顶层 `permissions` 为空。GitHub App 需要读取 Contents、写入 Pull requests,并仅安装到目标仓库。
在目标仓库的 **Settings → Secrets and variables → Actions** 配置以下项目。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "reims-go-frontend",
"private": true,
"version": "0.2.12",
"version": "0.2.13",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1 +1 @@
548bdba60bd8bd89e3828b675ad94fc2
5cadb9d7959628b248656a4d92bd9c1a
+31
View File
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadTestModule } from './load-test-module.mjs'
const { createLogLine } = await loadTestModule(`export * from './lib/logs'`)
const renderSelector = 'newRenderPipelineStateWithDescriptor:error:'
const computeSelector = 'newComputePipelineStateWithDescriptor:options:reflection:error:'
const precisionNote = (selector, code) =>
`[QEMU] reims-vgpu: ${selector}: metal2vulkan-runtime made it with a precision note (metal2vulkan-degrade-${code}): its answers there can differ from Metal's on this device; the first of its kind, each make that carries it counted`
test('successful render and compute precision notes keep their text as informational logs', () => {
for (const line of [
precisionNote(renderSelector, 'device-denormals'),
precisionNote(computeSelector, 'simdgroup-access-order'),
]) {
const row = createLogLine({ line })
assert.equal(row.level, 'info')
assert.equal(row.line, line)
}
})
test('pipeline refusals and fatal errors retain their error level', () => {
for (const line of [
`[QEMU] reims-vgpu: platform call ${renderSelector}: the runtime refused it`,
'[QEMU] reims-vgpu: fatal: Vulkan device was lost',
`${precisionNote(renderSelector, 'device-denormals')}; error: failed to submit the command buffer`,
]) {
assert.equal(createLogLine({ line }).level, 'error')
}
})
+20 -5
View File
@@ -16,7 +16,7 @@ import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolve
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints'
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
import { LogLine, appendLog } from './lib/logs'
import { LogLine, appendLog, createLogLine } from './lib/logs'
import { macOSMajor } from './macos/macosRelease'
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
@@ -200,11 +200,11 @@ export const App: React.FC = () => {
// Logs never pop the panel open (see docs/design-guidelines.md); errors only bump a badge.
const offLog = events.onLog((entry) => {
if (!entry || typeof entry !== 'object') return
const lineText = typeof entry.line === 'string' ? entry.line : String(entry.line ?? '')
if (!logsOpenRef.current && /\b(error|failed|fatal|panic)\b/i.test(lineText)) {
const line = createLogLine(entry)
if (!logsOpenRef.current && line.level === 'error') {
setUnseenErrors((n) => n + 1)
}
setLogLines((prev) => appendLog(prev, entry))
setLogLines((prev) => appendLog(prev, line))
})
// Tasks: seed from the backend, then follow events.
api.GetTasks().then((list) => {
@@ -451,6 +451,17 @@ export const App: React.FC = () => {
useEffect(() => () => { disposeActiveThemeAndLocaleFonts() }, [])
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const pushToast = toasts.push
useEffect(() => events.onRuntimeWarning((message) => {
const { summary, code, rawDetail } = parseAppError(message)
pushToast({
kind: 'warning',
title: summary,
errorCode: code,
rawDetail,
detailsLabel: t(locale, 'errRawDetailsToggle'),
copyDetailsLabel: t(locale, 'errCopyDetails'),
})
}), [locale, pushToast])
useEffect(() => events.onHostDrop(({ delivered, mode }) => {
if (mode !== 'l1_share' || delivered.length === 0) return
const title = delivered.length === 1
@@ -534,6 +545,7 @@ export const App: React.FC = () => {
await api.InstallRuntimeArchive(file)
await refresh()
} catch (e) {
if (parseAppError(e).code === 'E_RUNTIME_ACTIVATION') await refresh()
fail(tr('failRuntime'), e)
}
}
@@ -653,8 +665,10 @@ export const App: React.FC = () => {
const loadQemu = (name?: string) => loadVMLog(false, name)
const fail = (title: string, e: unknown) => {
const toast = errorToast(locale, title, e)
toasts.push({
...errorToast(locale, title, e),
...toast,
title: toast.errorCode === 'E_RUNTIME_ACTIVATION' ? tr('runtimeActivationFailed') : title,
action: { label: tr('viewLogs'), onClick: () => openLogs('app') },
})
}
@@ -1335,6 +1349,7 @@ export const App: React.FC = () => {
runtimeTask={runtimeTask}
onChannel={setChannel}
onInstallRuntime={installRuntime}
onImportRuntime={importRuntime}
onCancelTask={cancelTask}
/>
)}
+12 -2
View File
@@ -95,6 +95,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
const [driverCreating, setDriverCreating] = useState(false)
const [dependencyBusy, setDependencyBusy] = useState(false)
const [dependencyRefresh, setDependencyRefresh] = useState(0)
const [validationRefresh, setValidationRefresh] = useState(0)
useEffect(() => {
let live = true
@@ -204,6 +205,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
? Math.ceil((chosenRelease.size * 1.1) / 1e9)
: 0
useEffect(() => {
if (!reviewed || issues.length === 0) return
const onFocus = () => setValidationRefresh((n) => n + 1)
window.addEventListener('focus', onFocus)
return () => window.removeEventListener('focus', onFocus)
}, [reviewed, issues.length])
useEffect(() => {
if (!reviewed && step !== REVIEW_STEP) return
let live = true
@@ -221,7 +229,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
.finally(() => { if (live) setChecking(false) })
}, 200)
return () => { live = false; clearTimeout(timer) }
}, [step, reviewed, opts])
}, [step, reviewed, opts, validationRefresh])
const pickDir = async () => {
const dir = await api.PickDirectory(tr('vmDir'))
@@ -835,7 +843,8 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
]
const nameIssue = issues.find((i) => i.field === 'name')?.message
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name')
const dirIssue = issues.find((i) => i.field === 'dir')?.message
const general = issues.filter((i) => stepOfIssue(i) === REVIEW_STEP && i.field !== 'name' && i.field !== 'dir')
const copy = async () => {
try {
@@ -859,6 +868,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
<SetRow
title={tr('vmDir')}
desc={opts.dir ? <span className="mono path-text" title={opts.dir}>{opts.dir}</span> : tr('summaryDefaultDir')}
error={dirIssue}
control={
<div className="hstack">
{opts.dir && <Button variant="ghost" onClick={() => onDir('')}>{tr('useDefault')}</Button>}
+26 -8
View File
@@ -7,25 +7,28 @@ import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib
import { describeHostWHPX } from '../lib/hypervisor'
import { AppState, Locale, StorageBreakdown, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Switch } from '../ui/settings'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
state: AppState
locale: Locale
onRefresh: () => void
onRefresh: () => Promise<void>
onNewVM?: () => void
onError: (title: string, e: unknown) => void
onToast?: (title: string) => void
runtimeTask: Task | null
onChannel: (alpha: boolean) => void
onInstallRuntime: (commit: string) => void
onImportRuntime: () => Promise<void>
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onImportRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [savingASLR, setSavingASLR] = useState(false)
const [confirmDelete, setConfirmDelete] = useState('')
const [removing, setRemoving] = useState('')
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
@@ -43,7 +46,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
const guard = (fn: () => Promise<unknown>) => async () => {
try {
await fn()
onRefresh()
await onRefresh()
} catch (e) {
onError(tr('failGeneric'), e)
}
@@ -63,13 +66,19 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
}
}
const setQEMUASLR = async (enabled: boolean) => {
setSavingASLR(true)
await guard(() => api.SetQEMUASLR(enabled))()
setSavingASLR(false)
}
const importRuntime = async () => {
setImporting(true)
await guard(async () => {
const file = await api.PickFile(tr('importRuntime'), '*.tar.zst;*.zip')
if (file) await api.InstallRuntimeArchive(file)
})()
setImporting(false)
try {
await onImportRuntime()
} finally {
setImporting(false)
}
}
const removeRuntime = async (commit: string) => {
@@ -207,6 +216,15 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('qemuASLR')}</div>
<div className="row-sub">{tr('qemuASLRHint')}</div>
</div>
<div className="row-right">
<Switch label={tr('qemuASLR')} checked={!!config.qemu_aslr} disabled={savingASLR} onChange={setQEMUASLR} />
</div>
</div>
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main">
+22
View File
@@ -203,6 +203,18 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
const ready = !!state.active_runtime
const { host } = state
const [enabling, setEnabling] = useState(false)
const [activating, setActivating] = useState('')
const activate = async (commit: string) => {
setActivating(commit)
try {
await api.UseRuntime(commit)
onFolderDone()
} catch (e) {
onError(tr('runtimeActivationFailed'), e)
} finally {
setActivating('')
}
}
const enableWHPX = async () => {
setEnabling(true)
try {
@@ -294,6 +306,16 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
{(state.runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main"><div className="row-title mono">{rt.commit}</div></div>
<div className="row-right">
<Button busy={activating === rt.commit} disabled={!!activating} onClick={() => activate(rt.commit)}>
{tr('activate')}
</Button>
</div>
</div>
))}
</div>
<div className="setup-foot">
<Button variant="ghost" onClick={onImportRuntime}>{tr('setupImport')}</Button>
+2
View File
@@ -142,6 +142,7 @@ export const coreZh: Record<string, string> = {
"resizeLogPanel": "拖动调整日志高度",
"resolution": "分辨率",
"restart": "重启",
"runtimeActivationFailed": "运行时激活失败",
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
"safeModeManagePlugins": "管理插件",
"save": "保存",
@@ -353,6 +354,7 @@ export const coreEn: Record<string, string> = {
"resizeLogPanel": "Drag to resize log panel",
"resolution": "Resolution",
"restart": "Restart",
"runtimeActivationFailed": "Runtime activation failed",
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
"safeModeManagePlugins": "Manage plugins",
"save": "Save",
@@ -443,6 +443,8 @@ export const settingsZh: Record<string, string> = {
"optUnavailable": "不可用",
"pendingChanges": "{n, plural, other {# 项更改,下次启动生效}}",
"platformReadonly": "机型、序列号等平台身份信息不在界面显示",
"qemuASLR": "自动为 QEMU 启用 ASLR",
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
"recommendedBadge": "推荐",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
@@ -985,6 +987,8 @@ export const settingsEn: Record<string, string> = {
"optUnavailable": "Unavailable",
"pendingChanges": "{n, plural, one {# change · applies on next start} other {# changes · applies on next start}}",
"platformReadonly": "Model, serial number and other platform identity are never shown",
"qemuASLR": "Automatically enable ASLR for QEMU",
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
"recommendedBadge": "Recommended",
"resCustom": "Custom",
"resCustomSub": "Width × height",
+3
View File
@@ -862,6 +862,8 @@ export type I18nKey =
| "pluginTrustOfficial"
| "pluginTrustVerified"
| "pluginViewLog"
| "qemuASLR"
| "qemuASLRHint"
| "quitFailed"
| "quitInProgress"
| "recommendedBadge"
@@ -880,6 +882,7 @@ export type I18nKey =
| "restartToApply"
| "resume"
| "resumeUnavailable"
| "runtimeActivationFailed"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
+7 -4
View File
@@ -14,18 +14,21 @@ const MAX_LOG_LINES = 2000
// backend tags them explicitly.
const ERROR_RE = /\b(error|failed|fatal|panic)\b/i
const WARN_RE = /\bwarn(ing)?\b/i
// Successful vGPU precision notes include the Metal selector's error: argument.
const PRECISION_NOTE_PREFIX = /^(?:\[QEMU\] )?reims-vgpu: [\w:]+: metal2vulkan-runtime made it with a precision note \(metal2vulkan-degrade-[a-z0-9-]+\): /
let nextId = 1
function classify(entry: LogEntry): LogLine {
export function createLogLine(entry: LogEntry): LogLine {
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
const source = typeof entry?.source === 'string' ? entry.source : ''
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
const level: LogLevel = ERROR_RE.test(line) ? 'error' : WARN_RE.test(line) ? 'warn' : 'info'
const message = line.replace(PRECISION_NOTE_PREFIX, '')
const level: LogLevel = ERROR_RE.test(message) ? 'error' : WARN_RE.test(message) ? 'warn' : 'info'
return { ts, source, line, id: nextId++, level }
}
export function appendLog(prev: LogLine[], entry: LogEntry): LogLine[] {
const next = [...prev, classify(entry)]
export function appendLog(prev: LogLine[], line: LogLine): LogLine[] {
const next = [...prev, line]
return next.length > MAX_LOG_LINES ? next.slice(next.length - MAX_LOG_LINES) : next
}
+2 -1
View File
@@ -999,6 +999,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
.toast.ok .toast-main-row > svg { color: var(--status-running); }
.toast.warning .toast-main-row > svg { color: var(--status-busy); }
.toast.error .toast-main-row > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.toast-title-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
@@ -1160,7 +1161,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
.srow-fieldset { border: 0; padding: 0; margin: 0; min-width: 0; transition: opacity var(--dur-fast) var(--ease-out); }
.srow-fieldset:disabled { opacity: 0.42; }
.srow[data-disabled] .srow-title { color: var(--text-2); }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); overflow-wrap: anywhere; }
.srow-error svg { flex-shrink: 0; margin-top: 2px; }
.srow-kv .srow-value { min-width: 0; text-align: right; font-size: var(--fs-13); color: var(--text-2); overflow-wrap: anywhere; user-select: text; font-variant-numeric: tabular-nums; }
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
+5 -3
View File
@@ -1,5 +1,5 @@
import * as RToast from '@radix-ui/react-toast'
import { Check, CircleCheck, CircleX, X } from 'lucide-react'
import { AlertTriangle, Check, CircleCheck, CircleX, X } from 'lucide-react'
import { HostIcon } from './themeVisuals'
import { emitThemeEvent } from '../lib/themeEngine'
import React, { useCallback, useState } from 'react'
@@ -8,7 +8,7 @@ import type { Locale } from '../types'
import { IconButton } from './controls'
export interface ToastInput {
kind: 'ok' | 'error'
kind: 'ok' | 'warning' | 'error'
title: string
description?: string
errorCode?: string
@@ -79,7 +79,7 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
<RToast.Root
className={`toast rg-p-toast ${item.kind}${item.rawDetail || item.action ? ' has-extra' : ''}`}
data-tone={item.kind}
duration={expanded ? 600_000 : item.kind === 'error' ? 10_000 : item.action ? 8000 : 3000}
duration={expanded ? 600_000 : item.kind !== 'ok' ? 10_000 : item.action ? 8000 : 3000}
onOpenChange={(open) => {
if (!open) onRemove(item.id)
}}
@@ -87,6 +87,8 @@ const ToastCard: React.FC<ToastCardProps> = ({ item, onRemove, closeLabel }) =>
<div className="toast-main-row">
{item.kind === 'ok' ? (
<CircleCheck size={16} aria-hidden="true" />
) : item.kind === 'warning' ? (
<HostIcon name="warning"><AlertTriangle size={16} aria-hidden="true" /></HostIcon>
) : (
<HostIcon name="error"><CircleX size={16} aria-hidden="true" /></HostIcon>
)}
+1
View File
@@ -200,6 +200,7 @@ export const events = {
onTask: (cb: (task: Task) => void) => eventsOn('reims:task', cb),
onStateChanged: (cb: () => void) => eventsOn('reims:state-changed', cb),
onLog: (cb: (entry: LogEntry) => void) => eventsOn('reims:log', cb),
onRuntimeWarning: (cb: (message: string) => void) => eventsOn('reims:runtime-warning', cb),
// Market install progress (internal/app/plugins_flow.go InstallMarketPlugin).
onPluginInstall: (cb: (p: MarketInstallProgress) => void) => eventsOn('reims:plugin-install', cb),
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
+2
View File
@@ -268,6 +268,8 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetPluginSettings(arg1:string,arg2:string,arg3:Record<string, any>):Promise<void>;
export function SetQEMUASLR(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
+4
View File
@@ -514,6 +514,10 @@ export function SetPluginSettings(arg1, arg2, arg3) {
return window['go']['app']['App']['SetPluginSettings'](arg1, arg2, arg3);
}
export function SetQEMUASLR(arg1) {
return window['go']['app']['App']['SetQEMUASLR'](arg1);
}
export function SetRuntimeChannel(arg1) {
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
}
+2
View File
@@ -809,6 +809,7 @@ export namespace config {
auto_pin_pcores: boolean;
default_gpu?: string;
runtime_channel?: string;
qemu_aslr?: boolean;
app_update_channel?: string;
minimize_to_tray?: boolean;
sync_host_memory_smbios?: boolean;
@@ -830,6 +831,7 @@ export namespace config {
this.auto_pin_pcores = source["auto_pin_pcores"];
this.default_gpu = source["default_gpu"];
this.runtime_channel = source["runtime_channel"];
this.qemu_aslr = source["qemu_aslr"];
this.app_update_channel = source["app_update_channel"];
this.minimize_to_tray = source["minimize_to_tray"];
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
+156 -74
View File
@@ -100,6 +100,8 @@ type App struct {
vmNetworkLocksMu sync.Mutex
ctx context.Context
mu sync.Mutex
configMu sync.Mutex // serializes config writes and data root changes
selectionMu sync.Mutex // keeps a GUI selection in its data root across UAC
cfg *config.Config
transitions map[string]string
pendingChanges map[string][]PendingChange
@@ -365,8 +367,8 @@ func (a *App) emitLog(source, line string) {
func (a *App) GetState() AppState {
a.noteUIAlive()
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
trCopy := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
trCopy[k] = v
@@ -447,9 +449,10 @@ func (a *App) GetState() AppState {
}
func (a *App) SetLocale(raw string) error {
if err := a.setPreference(func(cfg *config.Config) { cfg.Locale = i18n.ParsePreference(raw) }); err != nil {
return err
}
a.mu.Lock()
a.cfg.Locale = i18n.ParsePreference(raw)
err := a.saveConfigLocked()
eff := i18n.EffectiveLocale(a.cfg.Locale)
mgr := a.pluginMgr
a.mu.Unlock()
@@ -457,30 +460,19 @@ func (a *App) SetLocale(raw string) error {
mgr.NotifyLocaleChanged(eff)
}
a.emitStateChanged()
return err
return nil
}
func (a *App) SetAutoPinPCores(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.AutoPinPCores = enabled
return a.saveConfigLocked()
return a.setPreference(func(cfg *config.Config) { cfg.AutoPinPCores = enabled })
}
func (a *App) SetMinimizeToTray(enabled bool) error {
a.mu.Lock()
v := enabled
a.cfg.MinimizeToTray = &v
err := a.saveConfigLocked()
a.mu.Unlock()
return err
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
}
func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.SyncHostMemorySMBIOS = enabled
return a.saveConfigLocked()
return a.setPreference(func(cfg *config.Config) { cfg.SyncHostMemorySMBIOS = enabled })
}
// showMainWindow restores and focuses the Wails window from the system tray.
@@ -514,9 +506,9 @@ func (a *App) startTray() {
OnVMAction: a.trayVMAction,
OnQuit: a.QuitApp,
GetSnapshot: func() tray.Snapshot {
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
loc := a.cfg.Locale
loc := cfgCopy.Locale
cached := append([]driver.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
@@ -631,38 +623,40 @@ func (a *App) resetDataRootCaches() {
}
func (a *App) SetDataRoot(dir string) error {
return a.setDataRoot(dir, host.SyncQEMUASLR)
}
func (a *App) checkDataRootSwitch(loc i18n.Locale) error {
a.mu.Lock()
loc := i18n.EffectiveLocale(a.cfg.Locale)
prev := a.cfg.DataRoot
curLocalePref := a.cfg.Locale
curAutoPin := a.cfg.AutoPinPCores
curRuntimeChannel := a.cfg.RuntimeChannel
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS
curEnableHvSwitch := a.cfg.EnableHypervisorSwitch
curHostDNS := a.hostDNSConfigLocked()
curFullscreenHotkeyEnabled := a.cfg.FullscreenHotkeyEnabled
curFullscreenHotkey := a.cfg.FullscreenHotkey
defer a.mu.Unlock()
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
for _, tr := range a.transitions {
if tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
a.mu.Unlock()
// Plugin tasks do not block the switch; resetDataRootCaches cancels them.
if hostTaskRunning() {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
}
return nil
}
func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, string) error) (err error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.mu.Lock()
prev := *a.cfg
wasReadOnly, setup := a.root.ReadOnly, a.needsSetup
a.mu.Unlock()
loc := i18n.EffectiveLocale(prev.Locale)
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
dir = strings.TrimSpace(dir)
if dir != "" {
dir = filepath.Clean(dir)
@@ -675,41 +669,95 @@ func (a *App) SetDataRoot(dir string) error {
return dataroot.Error(loc, st)
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if _, statErr := os.Stat(cfgPath); statErr != nil {
nextCfg.Locale = curLocalePref
nextCfg.AutoPinPCores = curAutoPin
nextCfg.RuntimeChannel = curRuntimeChannel
nextCfg.AppUpdateChannel = curAppUpdateChannel
nextCfg.MinimizeToTray = curMinToTray
nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS
nextCfg.EnableHypervisorSwitch = curEnableHvSwitch
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL
nextCfg.FullscreenHotkeyEnabled = curFullscreenHotkeyEnabled
nextCfg.FullscreenHotkey = curFullscreenHotkey
}
if err := nextCfg.EnsureDirs(); err != nil {
target := config.Config{DataRoot: dir}
if err := target.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, nextCfg); err != nil {
st := dataroot.Open(dir, version.Version)
if st.ReadOnly {
return dataroot.Error(loc, st)
}
ctx := a.baseCtx()
changed := !sameDataFolder(prev.DataRoot, dir)
source := ""
if changed && !setup && !wasReadOnly {
if _, err := os.Stat(prev.DataRoot); err == nil {
source = prev.RuntimesDir()
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
release, err := lockDataRootSelections(ctx, source, target.RuntimesDir())
if err != nil {
return err
}
defer release()
if changed && !setup && !wasReadOnly {
if err := rt.RefreshSelection(&prev); err != nil {
// A damaged source config must still allow switching to a healthy folder.
a.emitLog("runtime", "Read previous runtime selection: "+err.Error())
}
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.LoadExisting(cfgPath)
fresh := errors.Is(err, os.ErrNotExist)
if fresh {
nextCfg = config.Default()
nextCfg.Locale = prev.Locale
nextCfg.QEMUASLR = prev.QEMUASLR
} else if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if changed && !setup {
restore, policyErr := a.moveDataRootASLR(ctx, &prev, nextCfg, fresh, syncPolicy)
if policyErr != nil {
return policyErr
}
defer func() {
if err != nil {
err = errors.Join(err, restore())
}
}()
}
a.configMu.Lock()
defer a.configMu.Unlock()
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
if fresh {
// Keep preference edits made while Windows was asking for consent.
a.mu.Lock()
cur := *a.cfg
a.mu.Unlock()
nextCfg.Locale = cur.Locale
nextCfg.AutoPinPCores = cur.AutoPinPCores
nextCfg.RuntimeChannel = cur.RuntimeChannel
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
nextCfg.MinimizeToTray = cur.MinimizeToTray
nextCfg.SyncHostMemorySMBIOS = cur.SyncHostMemorySMBIOS
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
nextCfg.FullscreenHotkeyEnabled = cur.FullscreenHotkeyEnabled
nextCfg.FullscreenHotkey = cur.FullscreenHotkey
} else {
// Preserve independent preference saves in the destination during UAC.
nextCfg, err = config.LoadExisting(cfgPath)
if err != nil {
return err
}
nextCfg.DataRoot = dir
}
if err := rt.SavePreferences(nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
// A folder created just now gets its version stamp here.
st := dataroot.Open(dir, version.Version)
a.mu.Lock()
wasReadOnly := a.root.ReadOnly
a.cfg = nextCfg
if a.guestTools != nil {
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
@@ -721,7 +769,7 @@ func (a *App) SetDataRoot(dir string) error {
// Leaving a read-only folder starts the plugins and polling it held back,
// even when the user picked the same folder again after fixing it.
rootChanged := filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly
rootChanged := changed || wasReadOnly
if rootChanged {
a.resetDataRootCaches()
}
@@ -763,11 +811,14 @@ func (a *App) OpenProcessorScheduling() error {
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
a.mu.Lock()
cfg := a.cfg
cfg := *a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return nil, err
}
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
inst, err := rt.InstallFromArchive(cfg, archivePath)
inst, err := rt.InstallFromArchive(&cfg, archivePath)
if err != nil {
a.emitLog("runtime", "Install failed: "+err.Error())
if errors.Is(err, rt.ErrRuntimeInUse) {
@@ -775,28 +826,59 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
}
return nil, err
}
a.mu.Lock()
a.cfg.ActiveRuntime = inst.Commit
_ = a.saveConfigLocked()
a.mu.Unlock()
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
inst.Active = false
a.emitLog("runtime", err.Error())
return inst, err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
return inst, nil
}
func (a *App) UseRuntime(commit string) error {
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.ActiveRuntime = commit
return a.saveConfigLocked()
return a.activateRuntime("", commit)
}
func (a *App) activateInstalledRuntime(cfg *config.Config, commit string) error {
if err := a.activateRuntime(cfg.DataRoot, commit); err != nil {
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_RUNTIME_ACTIVATION",
"runtime.installed_not_activated", i18n.Vars{"commit": commit}, err)
}
return nil
}
func (a *App) activateRuntime(dataRoot, commit string) error {
return a.updateSelection(func(cfg *config.Config) error {
if dataRoot != "" && cfg.DataRoot != dataRoot {
return errors.New("data folder changed during runtime install")
}
return rt.Activate(a.baseCtx(), cfg, commit, a.warnRuntime)
})
}
func (a *App) warnRuntime(warning error) {
message := warning.Error()
a.emitLog("runtime", message)
a.emit("reims:runtime-warning", message)
}
func (a *App) SetQEMUASLR(enabled bool) error {
return a.updateSelection(func(cfg *config.Config) error {
return rt.SetQEMUASLR(a.baseCtx(), cfg, enabled)
})
}
func (a *App) RemoveRuntime(commit string) error {
a.mu.Lock()
cfg := a.cfg
loc := i18n.EffectiveLocale(a.cfg.Locale)
if err := a.requireWritableDataRootLocked(); err != nil {
a.mu.Unlock()
return err
}
cfg := *a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
inst, err := rt.Remove(cfg, commit)
inst, err := rt.Remove(&cfg, commit)
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
+22 -8
View File
@@ -39,9 +39,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
if opts.NetworkMode == "bridge" {
opts.SSHPort = 0
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
cfgCopy := a.runtimeConfig()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return err
@@ -65,11 +63,27 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
}
a.emitVMLog(opts.Name, "Creating VM "+opts.Name+"...")
existingVMs, _ := c.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, existingVMs); rerr != nil {
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
} else if removed != "" {
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
targetDir := reims.ResolveCreateTargetDir(cfgCopy.XDGDataDir(), opts)
if reims.IsAbortedCreateDir(targetDir) {
vms, err := a.listVMsInternal(ctx)
if err != nil {
finishTask(err)
return err
}
registered := make([]reims.VMListItem, 0, len(vms))
for _, vm := range vms {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Dir})
}
if issue := reims.ValidateCreateTargetDir(cfgCopy.XDGDataDir(), opts, registered, cfgCopy.Locale); issue != nil {
err := errors.New(issue.Message)
finishTask(err)
return err
}
if removed, rerr := reims.CleanAbortedCreateDir(cfgCopy.XDGDataDir(), opts, registered); rerr != nil {
a.emitVMLog(opts.Name, "Warning: could not clean unfinished VM directory: "+rerr.Error())
} else if removed != "" {
a.emitVMLog(opts.Name, "Removed unfinished directory from an earlier interrupted create: "+removed)
}
}
// Ensure any requested macOS installer is downloaded via installer.Client
+90
View File
@@ -0,0 +1,90 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func sameDataFolder(a, b string) bool {
if rel, err := filepath.Rel(a, b); err == nil && rel == "." {
return true
}
left, errA := os.Stat(a)
right, errB := os.Stat(b)
return errA == nil && errB == nil && os.SameFile(left, right)
}
// Order both selection locks so simultaneous switches in opposite directions
// cannot deadlock. Ordinary preference saves can finish during the switch.
func lockDataRootSelections(ctx context.Context, source, target string) (func(), error) {
if source == "" || sameDataFolder(source, target) {
return rt.LockSelection(ctx, target)
}
if strings.ToLower(source) > strings.ToLower(target) {
source, target = target, source
}
first, err := rt.LockSelection(ctx, source)
if err != nil {
return nil, err
}
second, err := rt.LockSelection(ctx, target)
if err != nil {
first()
return nil, err
}
return func() {
second()
first()
}, nil
}
// Return a rollback for a later config or location save failure. Existing
// destination preferences already authorize their own rule.
func (a *App) moveDataRootASLR(ctx context.Context, prev, next *config.Config, fresh bool, syncPolicy func(context.Context, string, string) error) (func() error, error) {
path, err := rt.QEMUASLRPath(next)
if err != nil {
return nil, err
}
restoreSource := func() error {
oldPath, err := rt.QEMUASLRPath(prev)
if err != nil || oldPath == "" {
return err
}
return syncPolicy(context.WithoutCancel(ctx), prev.RuntimesDir(), oldPath)
}
if err := syncPolicy(ctx, prev.RuntimesDir(), ""); err != nil {
report := rt.QEMUASLRPolicyError(prev, err)
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
return nil, report
}
return nil, errors.Join(report, restoreSource())
}
if path == "" {
return restoreSource, nil
}
restore := func() error {
var err error
if fresh {
err = syncPolicy(context.WithoutCancel(ctx), next.RuntimesDir(), "")
}
return errors.Join(err, restoreSource())
}
if err := syncPolicy(ctx, next.RuntimesDir(), path); err != nil {
if errors.Is(err, host.ErrQEMUASLRImagePolicy) {
a.warnRuntime(rt.QEMUASLRPolicyError(next, err))
return restoreSource, nil
}
if errors.Is(err, host.ErrElevationDeclined) || errors.Is(err, context.Canceled) {
return nil, errors.Join(rt.QEMUASLRPolicyError(next, err), restoreSource())
}
return nil, errors.Join(err, restore())
}
return restore, nil
}
+172
View File
@@ -0,0 +1,172 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestDataRootSwitchCarriesASLRAndCleansSource(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old")}
a := &App{cfg: &old}
saved := old
saved.QEMUASLR = true // The CLI enabled it after the desktop opened.
saved.ActiveRuntime = "cli-selection"
if err := config.Save("", &saved); err != nil {
t.Fatal(err)
}
target := filepath.Join(dir, "new")
calls := 0
err := a.setDataRoot(target, func(_ context.Context, root, path string) error {
calls++
if root != old.RuntimesDir() || path != "" {
t.Fatalf("unexpected policy update %q, %q", root, path)
}
// A preference save must finish while the Windows consent prompt is open.
if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F9"}); err != nil {
return err
}
return a.SetSyncHostMemorySMBIOS(true)
})
if err != nil || calls != 1 {
t.Fatalf("switch: calls=%d err=%v", calls, err)
}
stored, err := config.LoadExisting(filepath.Join(target, "reims-go.json"))
if err != nil || !stored.QEMUASLR || !stored.SyncHostMemorySMBIOS || a.cfg.DataRoot != target {
t.Fatalf("new config: %+v, %v", stored, err)
}
if !stored.FullscreenHotkeyEnabled || stored.FullscreenHotkey != "F9" {
t.Fatalf("new folder lost the fullscreen shortcut: %+v", stored)
}
source, err := config.LoadExisting(filepath.Join(old.DataRoot, "reims-go.json"))
if err != nil || !source.QEMUASLR || source.ActiveRuntime != saved.ActiveRuntime {
t.Fatalf("shortcut save replaced the CLI selection: %+v, %v", source, err)
}
if err := a.setDataRoot(target, func(context.Context, string, string) error {
t.Fatal("same directory must retain its rule")
return nil
}); err != nil {
t.Fatal(err)
}
}
func TestDataRootSwitchUsesDestinationPolicy(t *testing.T) {
for _, enabled := range []bool{false, true} {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: !enabled}
next := config.Config{DataRoot: filepath.Join(dir, "next"), QEMUASLR: enabled, ActiveRuntime: "new"}
if err := config.Save("", &next); err != nil {
t.Fatal(err)
}
runtimeDir := folderTestDir(t, next.RuntimesDir(), "new")
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
a := &App{cfg: &old}
var updates [][2]string
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
updates = append(updates, [2]string{root, path})
return nil
})
want := [][2]string{{old.RuntimesDir(), ""}}
if enabled {
runtime := rt.Installed{Dir: runtimeDir}
want = append(want, [2]string{next.RuntimesDir(), runtime.QemuPath()})
}
if err != nil || a.cfg.QEMUASLR != enabled || !reflect.DeepEqual(updates, want) {
t.Fatalf("destination enabled=%v: cfg=%+v updates=%v err=%v", enabled, a.cfg, updates, err)
}
}
}
func TestDataRootSwitchRestoresSourceOnPublishFailure(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "old"}
if err := config.SaveLocation(old.DataRoot); err != nil {
t.Fatal(err)
}
runtimeDir := folderTestDir(t, old.RuntimesDir(), "old")
if err := os.WriteFile(filepath.Join(runtimeDir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
next := filepath.Join(dir, "next")
a := &App{cfg: &old}
var paths []string
err := a.setDataRoot(next, func(_ context.Context, root, path string) error {
if root != old.RuntimesDir() {
return errors.New("unexpected registry root")
}
paths = append(paths, path)
if path == "" {
// The destination can no longer accept the config after the source rule was cleared.
folderTestDir(t, next, "reims-go.json")
}
return nil
})
runtime := rt.Installed{Dir: runtimeDir}
location, ok := config.ReadLocation()
if err == nil || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot || !reflect.DeepEqual(paths, []string{"", runtime.QemuPath()}) {
t.Fatalf("failed switch: cfg=%+v, location=%s, updates=%v err=%v", a.cfg, location, paths, err)
}
}
func TestDataRootSwitchRollsBackPartialPolicyWrites(t *testing.T) {
dir := t.TempDir()
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(dir, "location.json"))
old := config.Config{DataRoot: filepath.Join(dir, "old"), QEMUASLR: true, ActiveRuntime: "installed"}
next := config.Config{DataRoot: filepath.Join(dir, "next")}
if err := config.SaveLocation(old.DataRoot); err != nil {
t.Fatal(err)
}
for _, cfg := range []config.Config{old, next} {
dir := folderTestDir(t, cfg.RuntimesDir(), "installed")
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
}
oldRuntime := rt.Installed{Dir: filepath.Join(old.RuntimesDir(), "installed")}
nextRuntime := rt.Installed{Dir: filepath.Join(next.RuntimesDir(), "installed")}
clearOld := [2]string{old.RuntimesDir(), ""}
restoreOld := [2]string{old.RuntimesDir(), oldRuntime.QemuPath()}
enableNext := [2]string{next.RuntimesDir(), nextRuntime.QemuPath()}
clearNext := [2]string{next.RuntimesDir(), ""}
partial := errors.New("incomplete registry write")
for _, tc := range []struct {
name string
failAt [2]string
err error
want [][2]string
}{
{"source", clearOld, partial, [][2]string{clearOld, restoreOld}},
{"target", enableNext, partial, [][2]string{clearOld, enableNext, clearNext, restoreOld}},
{"declined", clearOld, host.ErrElevationDeclined, [][2]string{clearOld}},
} {
t.Run(tc.name, func(t *testing.T) {
var updates [][2]string
a := &App{cfg: &old}
err := a.setDataRoot(next.DataRoot, func(_ context.Context, root, path string) error {
operation := [2]string{root, path}
updates = append(updates, operation)
if operation == tc.failAt {
return tc.err
}
return nil
})
location, ok := config.ReadLocation()
if !errors.Is(err, tc.err) || !reflect.DeepEqual(updates, tc.want) || a.cfg.DataRoot != old.DataRoot || !ok || location != old.DataRoot {
t.Fatalf("updates=%v, location=%q, cfg=%+v, err=%v", updates, location, a.cfg, err)
}
})
}
}
+71 -10
View File
@@ -8,6 +8,7 @@ import (
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -54,24 +55,80 @@ func (a *App) dataRootUsable() bool {
func (a *App) requireWritableDataRoot() error {
a.mu.Lock()
defer a.mu.Unlock()
return a.requireWritableDataRootLocked()
}
func (a *App) requireWritableDataRootLocked() error {
if a.needsSetup {
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
}
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
}
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
// a.cfg points at a suggested folder the user has not chosen, so changes stay
// in memory until CompleteSetup writes them into the chosen folder. A folder
// open read-only refuses the write.
func (a *App) saveConfigLocked() error {
if a.needsSetup {
return nil
}
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
func (a *App) setPreference(edit func(*config.Config)) error {
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
cfg := *a.cfg
setup := a.needsSetup
err := a.requireWritableDataRootLocked()
a.mu.Unlock()
if err != nil && !setup {
return err
}
return config.Save("", a.cfg)
edit(&cfg)
if !setup {
if err := rt.SavePreferences(&cfg); err != nil {
return err
}
}
a.mu.Lock()
a.cfg = &cfg
a.mu.Unlock()
return nil
}
// Runtime policy may wait for UAC. Publish only its two fields over the
// current settings once the disk transaction has finished.
func (a *App) updateSelection(persist func(*config.Config) error) error {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.mu.Lock()
err := a.requireWritableDataRootLocked()
cfg := *a.cfg
a.mu.Unlock()
if err != nil {
return err
}
if err := persist(&cfg); err != nil {
return err
}
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
latest := *a.cfg
latest.ActiveRuntime, latest.QEMUASLR = cfg.ActiveRuntime, cfg.QEMUASLR
a.cfg = &latest
a.mu.Unlock()
return nil
}
// runtimeConfig includes the last selection made by either the GUI or CLI.
func (a *App) runtimeConfig() config.Config {
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
return config.Config{}
}
cfg := *a.cfg
usable := !a.needsSetup && !a.root.ReadOnly
a.mu.Unlock()
if usable {
if err := rt.RefreshSelection(&cfg); err != nil {
a.emitLog("runtime", "Read runtime selection: "+err.Error())
}
}
return cfg
}
// ReopenDataRoot opens the current data folder again: after another process
@@ -79,6 +136,10 @@ func (a *App) saveConfigLocked() error {
// a damaged version record on the user's request. When the folder becomes
// writable, the parts that were held back start.
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
if a.needsSetup {
st := a.root
+1 -1
View File
@@ -135,8 +135,8 @@ func (a *App) ExportDiagnostics(driverID, name string) (string, error) {
return "", err
}
}
cfgCopy := a.runtimeConfig()
a.mu.Lock()
cfgCopy := *a.cfg
appLogs := append([]string(nil), a.recentLogs...)
a.mu.Unlock()
rep := host.Inspect(cfgCopy.DataRoot)
+8 -12
View File
@@ -3,6 +3,7 @@ package app
import (
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
)
@@ -49,20 +50,15 @@ func (a *App) SetFullscreenHotkey(req FullscreenHotkeyConfig) (FullscreenHotkeyS
if err != nil {
return FullscreenHotkeyStatus{}, err
}
a.mu.Lock()
oldEnabled, oldHotkey := a.cfg.FullscreenHotkeyEnabled, a.cfg.FullscreenHotkey
if req.Enabled != oldEnabled && strings.TrimSpace(req.Hotkey) == "" {
canonical = effectiveFullscreenHotkey(oldHotkey)
}
a.cfg.FullscreenHotkeyEnabled = req.Enabled
a.cfg.FullscreenHotkey = canonical
if err := a.saveConfigLocked(); err != nil {
a.cfg.FullscreenHotkeyEnabled = oldEnabled
a.cfg.FullscreenHotkey = oldHotkey
a.mu.Unlock()
if err := a.setPreference(func(cfg *config.Config) {
if req.Enabled != cfg.FullscreenHotkeyEnabled && strings.TrimSpace(req.Hotkey) == "" {
canonical = effectiveFullscreenHotkey(cfg.FullscreenHotkey)
}
cfg.FullscreenHotkeyEnabled = req.Enabled
cfg.FullscreenHotkey = canonical
}); err != nil {
return FullscreenHotkeyStatus{}, err
}
a.mu.Unlock()
a.syncFullscreenHotkeyTargets()
a.emitStateChanged()
+7 -7
View File
@@ -5,6 +5,7 @@ import (
"os"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/guesttools"
)
@@ -22,16 +23,15 @@ func (a *App) SetHostDNSConfig(cfg guesttools.HostDNSConfig) error {
if err := cfg.Validate(); err != nil {
return err
}
a.mu.Lock()
defer a.mu.Unlock()
prev := a.hostDNSConfigLocked()
a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = cfg.Mode, cfg.DoHURL
if err := a.saveConfigLocked(); err != nil {
a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = prev.Mode, prev.DoHURL
if err := a.setPreference(func(c *config.Config) {
c.HostDNSMode, c.HostDNSDoHURL = cfg.Mode, cfg.DoHURL
}); err != nil {
return err
}
a.mu.Lock()
defer a.mu.Unlock()
if a.guestTools != nil {
a.guestTools.SetHostDNSConfig(cfg)
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
}
return nil
}
+5 -11
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -20,18 +21,11 @@ var (
// Hyper-V / WHPX boot switch in Settings. Toggling this flag alone never runs
// any system virtualization or boot configuration command.
func (a *App) SetEnableHypervisorSwitch(enabled bool) error {
a.mu.Lock()
prev := a.cfg.EnableHypervisorSwitch
a.cfg.EnableHypervisorSwitch = enabled
err := a.saveConfigLocked()
if err != nil {
a.cfg.EnableHypervisorSwitch = prev
if err := a.setPreference(func(cfg *config.Config) { cfg.EnableHypervisorSwitch = enabled }); err != nil {
return err
}
a.mu.Unlock()
if err == nil {
a.emitStateChanged()
}
return err
a.emitStateChanged()
return nil
}
// SetHypervisorBoot prompts for UAC and updates Windows hypervisor boot launch
+1 -3
View File
@@ -13,9 +13,7 @@ import (
)
func (a *App) installerClient() (*installer.Client, error) {
a.mu.Lock()
cfg := *a.cfg
a.mu.Unlock()
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return nil, err
+18 -10
View File
@@ -307,12 +307,14 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
if err != nil {
return err
}
return a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
ref := vm.Ref()
ref := vm.Ref()
removedVM := false
err = a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
key := ref.Key()
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
if vm.State != "running" && ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcher(ref.Name)
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
var deleteErr error
@@ -338,7 +340,10 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
} else if err := svc.DeleteResolved(ctx, d, vm, keepFiles, w, w); err != nil {
return err
}
removedVM = true
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcher(ref.Name)
stopVMMonitor(ref.Name)
a.stopPacketBridge(ref.Name)
}
a.mu.Lock()
@@ -348,13 +353,6 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
delete(a.procSamples, key)
gt := a.guestTools
a.mu.Unlock()
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
releaseVMTyping(ref.Name)
releaseVMThumbnail(ref.Name)
} else {
releaseVMTypingForDriver(ref.DriverID, ref.Name)
releaseVMThumbnailForDriver(ref.DriverID, ref.Name)
}
a.stateTable().Delete(ref)
a.discardMaterializedSecretsForVM(key)
if gt != nil {
@@ -364,4 +362,14 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error {
a.emitStateChanged()
return deleteErr
})
if removedVM {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
releaseVMTyping(ref.Name)
releaseVMThumbnail(ref.Name)
} else {
releaseVMTypingForDriver(ref.DriverID, ref.Name)
releaseVMThumbnailForDriver(ref.DriverID, ref.Name)
}
}
return err
}
+225
View File
@@ -11,17 +11,62 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/macosdriver"
"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/tray"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
for _, version := range []string{"current", "backup"} {
dir := folderTestDir(t, cfg.RuntimesDir(), version)
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), []byte("{}"), 0o600); err != nil {
t.Fatal(err)
}
}
a := &App{cfg: &cfg}
d := macosdriver.NewReimsMacOSDriver(a.runtimeConfig, macosdriver.Options{OwnerID: "test.macos"})
ref := driver.NewVMRef(d.ID(), "test")
for _, version := range []string{"current", "backup", "current"} {
saved := cfg
saved.ActiveRuntime = version
if err := config.Save("", &saved); err != nil {
t.Fatal(err)
}
want := rt.Installed{Dir: filepath.Join(cfg.RuntimesDir(), version)}
prep, err := a.prep(ref.Name)
if err != nil {
t.Fatal(err)
}
c, err := a.client()
if err != nil {
t.Fatal(err)
}
if c.Binary != want.ControlPath() || prep.Client.Binary != c.Binary || a.activeQemuPath() != want.QemuPath() {
t.Fatalf("%s: native clients or bridge selected the wrong runtime", version)
}
// Only manifests are installed. The attempted control executable
// identifies which runtime the same driver used for each new request.
_, startErr := d.Start(t.Context(), driver.StartRequest{Ref: ref})
_, resumeErr := d.Resume(t.Context(), driver.ResumeRequest{Ref: ref})
for _, err := range []error{startErr, resumeErr} {
if err == nil || !strings.Contains(err.Error(), want.ControlPath()) {
t.Fatalf("expected a launch attempt with %q, got %v", want.ControlPath(), err)
}
}
}
}
func TestPrepareLegacyColdStart(t *testing.T) {
log := func(line string) { t.Log(line) }
t.Run("recoverable snapshot", func(t *testing.T) {
@@ -311,3 +356,183 @@ func TestSameNameVMsAcrossDriversStayIndependent(t *testing.T) {
t.Fatalf("tray restart: mac stops=%d starts=%d, linux stops=%d starts=%d", mac.stops, mac.starts, lin.stops, lin.starts)
}
}
func TestStopVMMonitorWaitsForExitAndAllowsDirRemoval(t *testing.T) {
vmDir := t.TempDir()
logDir := filepath.Join(vmDir, "logs")
if err := os.MkdirAll(logDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte("boot\n"), 0o644); err != nil {
t.Fatal(err)
}
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}}
if _, err := vmstart.SaveVMDisplay(vmDir, vmstart.VMDisplayConfig{TargetDisplay: "DISPLAY2"}); err != nil {
t.Fatal(err)
}
const vmName = "monitor-wait-test"
a.startVMMonitor(vmName, driver.VMInfo{
Name: vmName,
DriverID: driver.BuiltinReimsMacOSDriverID,
Directory: vmDir,
}, time.Now())
stopVMMonitor(vmName)
vmMonitors.mu.Lock()
_, stillRegistered := vmMonitors.entries[vmName]
vmMonitors.mu.Unlock()
if stillRegistered {
t.Fatal("monitor entry still registered after stopVMMonitor")
}
if err := os.RemoveAll(vmDir); err != nil {
t.Fatalf("removing VM dir after stopVMMonitor failed: %v", err)
}
}
func TestStoppingVMMonitorStaysRegisteredUntilExit(t *testing.T) {
const name = "monitor-concurrent-stop-test"
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
vmMonitors.mu.Lock()
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
vmMonitors.mu.Unlock()
t.Cleanup(func() {
vmMonitors.mu.Lock()
delete(vmMonitors.entries, name)
vmMonitors.mu.Unlock()
})
stopped := make(chan struct{})
go func() {
stopVMMonitor(name)
close(stopped)
}()
defer func() {
close(done)
<-stopped
}()
select {
case <-ctx.Done():
case <-time.After(time.Second):
t.Fatal("stop did not cancel the monitor")
}
vmMonitors.mu.Lock()
entry, ok := vmMonitors.entries[name]
vmMonitors.mu.Unlock()
if !ok || entry.done != done {
t.Fatal("concurrent callers lost the monitor completion channel before exit")
}
}
func TestStopVMMonitorRespectsTimeoutWhenStuck(t *testing.T) {
origTimeout := vmMonitorStopTimeout
vmMonitorStopTimeout = 30 * time.Millisecond
t.Cleanup(func() { vmMonitorStopTimeout = origTimeout })
const name = "monitor-stuck-timeout-test"
ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
vmMonitors.mu.Lock()
vmMonitors.entries[name] = vmMonitorEntry{cancel: cancel, done: done}
vmMonitors.mu.Unlock()
t.Cleanup(func() {
vmMonitors.mu.Lock()
delete(vmMonitors.entries, name)
vmMonitors.mu.Unlock()
close(done)
})
finished := make(chan struct{})
go func() {
stopVMMonitor(name)
close(finished)
}()
select {
case <-finished:
case <-time.After(time.Second):
t.Fatal("stopVMMonitor hung indefinitely when monitor goroutine did not exit")
}
if ctx.Err() == nil {
t.Fatal("stopVMMonitor did not cancel the monitor context")
}
allFinished := make(chan struct{})
go func() {
stopAllVMMonitors()
close(allFinished)
}()
select {
case <-allFinished:
case <-time.After(time.Second):
t.Fatal("stopAllVMMonitors hung indefinitely when monitor goroutine did not exit")
}
}
func TestValidateCreateProtectsDirectoryOfAnotherDriver(t *testing.T) {
const driverID = "test.driver.linux"
target := t.TempDir()
child := filepath.Join(target, "ubuntu")
if err := os.Mkdir(child, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(target, ".reims-ctl-creating"), nil, 0o600); err != nil {
t.Fatal(err)
}
drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: "ubuntu", DriverID: driverID, Directory: child}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{Manifest: plugin.Manifest{ID: "test.linux", Version: "1.0.0"},
Source: plugin.SourceBuiltin, Desired: true, Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, driverID, drv)
return nil
}}); err != nil {
t.Fatal(err)
}
reg.Reconcile(t.Context())
a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)}
issues := a.ValidateCreate(reims.CreateOpts{Name: "new-mac", Dir: target})
for _, issue := range issues {
if issue.Field == "dir" && issue.Code == "dir_not_empty" {
return
}
}
t.Fatalf("expected directory conflict for VM registered by another driver, got %+v", issues)
}
func TestValidateCreateRejectsLeftoverNonEmptyVMDir(t *testing.T) {
dataRoot := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dataRoot}}
leftoverDir := filepath.Join(a.cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
if err := os.MkdirAll(leftoverDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(leftoverDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
opts := reims.CreateOpts{
Name: "macos-tahoe2",
SourceMode: "apple",
MacOS: "tahoe",
CPUs: 2,
Memory: "4G",
DiskSize: "64G",
}
hasDirIssue := func(issues []reims.ValidationIssue) bool {
for _, is := range issues {
if is.Field == "dir" && is.Code == "dir_not_empty" {
return true
}
}
return false
}
if issues := a.ValidateCreate(opts); !hasDirIssue(issues) {
t.Fatalf("expected dir_not_empty issue for leftover directory, got %+v", issues)
}
if err := os.RemoveAll(leftoverDir); err != nil {
t.Fatal(err)
}
if issues := a.ValidateCreate(opts); hasDirIssue(issues) {
t.Fatalf("unexpected dir_not_empty issue after clearing directory: %+v", issues)
}
}
+6 -11
View File
@@ -43,14 +43,12 @@ func (a *App) client() (*reims.Client, error) {
if err := a.requireMacOSEnabled(); err != nil {
return nil, err
}
a.mu.Lock()
cfg := a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(cfg)
cfg := a.runtimeConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil {
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
}
return reims.NewClient(cfg, *active), nil
return reims.NewClient(&cfg, *active), nil
}
func enrichMacOSVMListStates(vms []driver.VMListItem) {
@@ -96,14 +94,11 @@ func (a *App) tempDir() string {
}
func (a *App) activeQemuPath() string {
a.mu.Lock()
if a.cfg == nil {
a.mu.Unlock()
cfg := a.runtimeConfig()
if cfg.DataRoot == "" {
return ""
}
cfgCopy := *a.cfg
a.mu.Unlock()
active, err := rt.ResolveActive(&cfgCopy)
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return ""
}
+39 -17
View File
@@ -599,33 +599,55 @@ func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
if err != nil {
return err
}
return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, name, keepFiles, c)
removed := false
err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed)
})
if removed {
releaseVMTyping(name)
releaseVMThumbnail(name)
}
return err
}
func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error {
name := detail.Name
if detail.State != "running" {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
if err := c.Delete(ctx, name, keepFiles, w, w); err != nil {
a.emitVMLog(name, "Delete error: "+err.Error())
return err
deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error {
return c.Delete(ctx, name, keepFiles, w, w)
}, func() (bool, error) {
vms, err := c.List(ctx)
if err != nil {
return false, err
}
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
return true, nil
}
}
return false, nil
})
if deleteErr != nil {
a.emitVMLog(name, "Delete error: "+deleteErr.Error())
}
if !deleted {
return deleteErr
}
*removed = true
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.stopPacketBridge(name)
a.mu.Lock()
delete(a.pendingChanges, vmKey(name))
delete(a.transitions, vmKey(name))
delete(a.diskPaths, vmKey(name))
delete(a.procSamples, vmKey(name))
gt := a.guestTools
a.mu.Unlock()
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
a.mu.Lock()
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
@@ -636,7 +658,7 @@ func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bo
}
a.wakePoll()
a.emitStateChanged()
return nil
return deleteErr
}
// OpenVMFolder shows the VM's directory in File Explorer.
+23 -5
View File
@@ -27,17 +27,37 @@ import (
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
a.mu.Lock()
root := a.cfg.DataRoot
xdgDataDir := ""
if strings.TrimSpace(root) != "" {
xdgDataDir = a.cfg.XDGDataDir()
}
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
issues := reims.ValidateCreate(opts, host.Inspect(root), loc)
// reims-ctl refuses a name already registered; say so before the create runs.
var registered []reims.VMListItem
nameTaken := false
if vms, err := a.listVMsInternal(context.Background()); err == nil {
for _, vm := range vms {
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Dir})
if !nameTaken && strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
nameTaken = true
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
break
}
}
} else if regVMs, regErr := reims.ListRegisteredVMs(root); regErr == nil {
for _, vm := range regVMs {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Directory})
if !nameTaken && strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
nameTaken = true
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: i18n.T(loc, "validate.name_taken", vm.Name)})
}
}
}
if !nameTaken || strings.TrimSpace(opts.Dir) != "" {
if issue := reims.ValidateCreateTargetDir(xdgDataDir, opts, registered, loc); issue != nil {
issues = append(issues, *issue)
}
}
return issues
}
@@ -527,9 +547,7 @@ func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbri
}
func (a *App) ensurePacketBridge(d reims.VMDetail, adapter packetbridge.Adapter, mac, socketPath string, port int) (*packetbridge.Bridge, error) {
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
cfgCopy := a.runtimeConfig()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return nil, err
+3 -10
View File
@@ -33,10 +33,7 @@ func (a *App) prep(name string) (*startprep.Prep, error) {
if err := a.requireMacOSEnabled(); err != nil {
return nil, err
}
a.mu.Lock()
cfg := *a.cfg
a.mu.Unlock()
return startprep.New(cfg, func(line string) { a.emitVMLog(name, line) })
return startprep.New(a.runtimeConfig(), func(line string) { a.emitVMLog(name, line) })
}
// GetVMSMBIOS reads the VM's OpenCore PlatformInfo > Generic identity
@@ -46,9 +43,7 @@ func (a *App) GetVMSMBIOS(name string) (opencore.SMBIOSIdentity, error) {
if err := a.requireMacOSEnabled(); err != nil {
return opencore.SMBIOSIdentity{}, err
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
cfgCopy := a.runtimeConfig()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return opencore.SMBIOSIdentity{}, err
@@ -86,9 +81,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S
if err != nil {
return opencore.SMBIOSIdentity{}, err
}
a.mu.Lock()
cfgCopy := *a.cfg
a.mu.Unlock()
cfgCopy := a.runtimeConfig()
active, err := rt.ResolveActive(&cfgCopy)
if err != nil {
return opencore.SMBIOSIdentity{}, err
+3 -10
View File
@@ -16,7 +16,6 @@ import (
"unicode"
"unicode/utf8"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/fetch"
@@ -130,12 +129,7 @@ func (a *App) initPlugins() {
})
cb := builtin.HostCallbacks{
GetConfig: func() config.Config {
a.mu.Lock()
cp := *a.cfg
a.mu.Unlock()
return cp
},
GetConfig: a.runtimeConfig,
Log: func(source, line string) {
a.emitLog(source, line)
},
@@ -649,12 +643,11 @@ func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
func (a *App) ListPlugins() []plugin.PluginInfo {
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
if mgr == nil {
a.mu.Unlock()
return nil
}
cfg := *a.cfg
a.mu.Unlock()
cfg := a.runtimeConfig()
reg := mgr.Registry()
infos := mgr.LocalizePluginInfos(reg.ListVisible())
active, _ := rt.ResolveActive(&cfg)
+8 -16
View File
@@ -77,11 +77,11 @@ func (a *App) SetRuntimeChannel(channel string) error {
default:
return fmt.Errorf("unknown channel %q", channel)
}
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.RuntimeChannel = channel
if err := a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel }); err != nil {
return err
}
forgetRemoteRuntimes()
return a.saveConfigLocked()
return nil
}
// InstallRuntimeOnline downloads, verifies and installs a published runtime
@@ -90,9 +90,9 @@ func (a *App) SetRuntimeChannel(channel string) error {
// which resumes on the next install.
func (a *App) InstallRuntimeOnline(commit string) (string, error) {
a.mu.Lock()
if a.needsSetup {
if err := a.requireWritableDataRootLocked(); err != nil {
a.mu.Unlock()
return "", errors.New("choose a data folder first")
return "", err
}
cfg := *a.cfg
a.mu.Unlock()
@@ -165,11 +165,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
r.Commit = inst.Commit
}
a.mu.Lock()
a.cfg.ActiveRuntime = r.Commit
err = a.saveConfigLocked()
a.mu.Unlock()
if err != nil {
if err := a.activateInstalledRuntime(cfg, r.Commit); err != nil {
return "", err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel))
@@ -200,11 +196,7 @@ func (a *App) SetAppUpdateChannel(channel string) error {
default:
return fmt.Errorf("unknown app update channel %q", channel)
}
a.mu.Lock()
a.cfg.AppUpdateChannel = channel
err := a.saveConfigLocked()
a.mu.Unlock()
if err != nil {
if err := a.setPreference(func(cfg *config.Config) { cfg.AppUpdateChannel = channel }); err != nil {
return err
}
appUpdateCache.Lock()
+176
View File
@@ -0,0 +1,176 @@
package app
import (
"archive/zip"
"bytes"
"errors"
"os"
"path/filepath"
"testing"
"testing/fstest"
"testing/synctest"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestArchiveActivationCanRetryWithoutImport(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
var archive bytes.Buffer
w := zip.NewWriter(&archive)
if err := w.AddFS(fstest.MapFS{"manifest.json": {Data: []byte(`{"commit":"candidate"}`)}}); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, "runtime.zip")
if err := os.WriteFile(path, archive.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
blockActivation := filepath.Join(dir, "reims-go.json")
if err := os.Mkdir(blockActivation, 0o755); err != nil {
t.Fatal(err)
}
inst, err := a.InstallRuntimeArchive(path)
var partial *i18n.CodedError
if !errors.As(err, &partial) || partial.Code != "E_RUNTIME_ACTIVATION" || inst == nil || inst.Active {
t.Fatalf("partial install = %+v, %v", inst, err)
}
list, err := rt.List(a.cfg)
if err != nil || len(list) != 1 || list[0].Commit != "candidate" || list[0].Active {
t.Fatalf("installed list = %+v, %v", list, err)
}
for _, item := range []string{path, blockActivation} {
if err := os.Remove(item); err != nil {
t.Fatal(err)
}
}
if err := a.UseRuntime(inst.Commit); err != nil || a.cfg.ActiveRuntime != "candidate" {
t.Fatalf("activation retry = %q, %v", a.cfg.ActiveRuntime, err)
}
}
func TestRuntimeConfigFollowsExternalSelection(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir, ActiveRuntime: "current"}}
stored := *a.cfg
stored.ActiveRuntime, stored.QEMUASLR = "backup", true
if err := config.Save("", &stored); err != nil {
t.Fatal(err)
}
got := a.runtimeConfig()
if got.ActiveRuntime != "backup" || !got.QEMUASLR {
t.Fatalf("desktop reads stale selection: %+v", got)
}
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
t.Fatal(err)
}
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil {
t.Fatal(err)
}
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
t.Fatalf("saving an unrelated setting lost the selection: %+v", saved)
}
}
func TestPreferencesDoNotOverwriteDamagedConfig(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
path := filepath.Join(dir, "reims-go.json")
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if err := a.SetSyncHostMemorySMBIOS(true); err == nil {
t.Fatal("saved preferences over an unreadable selection")
}
if data, err := os.ReadFile(path); err != nil || string(data) != "{" {
t.Fatalf("damaged config replaced: %q, %v", data, err)
}
}
func TestConfigWaitDoesNotBlockApp(t *testing.T) {
for _, tc := range []struct {
name string
save func(*App) error
}{
{"ASLR", func(a *App) error { return a.SetQEMUASLR(true) }},
{"runtime", func(a *App) error { return a.UseRuntime("backup") }},
{"preference", func(a *App) error { return a.SetSyncHostMemorySMBIOS(true) }},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
// All saves will stop before a registry write after the lock releases.
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
release, err := filelock.Acquire(t.Context(), filepath.Join(cfg.RuntimesDir(), ".reims-go-runtime.lock"), 0)
if err != nil {
t.Fatal(err)
}
a := &App{cfg: cfg}
synctest.Test(t, func(t *testing.T) {
done := make(chan error, 1)
go func() { done <- tc.save(a) }()
synctest.Wait()
available := a.mu.TryLock()
if available {
a.mu.Unlock()
a.emitLog("test", "while waiting")
}
release()
if err := <-done; err == nil || !available {
t.Fatalf("global lock available = %v, save error = %v", available, err)
}
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || a.cfg.SyncHostMemorySMBIOS {
t.Fatalf("failed save published %+v", a.cfg)
}
})
})
}
}
func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
dir := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: dir}}
synctest.Test(t, func(t *testing.T) {
resume := make(chan struct{})
results := make(chan error, 2)
go func() {
results <- a.updateSelection(func(cfg *config.Config) error {
<-resume
// Model the registry operation returning and committing over
// the preferences saved while consent was pending.
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil {
return err
}
saved.ActiveRuntime, saved.QEMUASLR = "backup", true
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
return config.Save("", saved)
})
}()
synctest.Wait()
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
t.Fatal(err)
}
close(resume)
if err := <-results; err != nil {
t.Fatal(err)
}
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
t.Fatalf("concurrent updates lost: %+v, %v", saved, err)
}
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || !a.cfg.SyncHostMemorySMBIOS {
t.Fatalf("in-memory settings diverged: %+v", a.cfg)
}
})
}
+6 -1
View File
@@ -15,6 +15,7 @@ import (
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -101,6 +102,10 @@ func (a *App) CheckDataRoot(dir string) DataRootCheck {
// existing reims-go config there (its runtimes and VMs), records the choice for
// the next launch and leaves first-launch setup.
func (a *App) CompleteSetup(dir string) error {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.configMu.Lock()
defer a.configMu.Unlock()
a.mu.Lock()
locale := a.cfg.Locale
a.mu.Unlock()
@@ -129,7 +134,7 @@ func (a *App) CompleteSetup(dir string) error {
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, cfg); err != nil {
if err := rt.SavePreferences(cfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
+2 -2
View File
@@ -79,7 +79,6 @@ func (a *App) ResumeVM(driverID, name string) error {
}
a.mu.Lock()
svc := a.lifecycleSvc
cfgCopy := *a.cfg
a.mu.Unlock()
if svc == nil {
return errors.New("driver lifecycle is not initialized")
@@ -104,7 +103,8 @@ func (a *App) ResumeVM(driverID, name string) error {
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
epoch = a.vmDeleteEpoch(ref.Name)
active, rerr := rt.ResolveActive(&cfgCopy)
cfg := a.runtimeConfig()
active, rerr := rt.ResolveActive(&cfg)
hasRuntime := rerr == nil && active != nil
unicodeInput := hasRuntime && active.Manifest.HasCapability("win32-unicode-input")
windowDrop := hasRuntime && active.Manifest.HasCapability("window-file-drop")
+77 -24
View File
@@ -20,33 +20,77 @@ import (
var vmMonitors = struct {
mu sync.Mutex
seq uint64
entries map[string]struct {
id uint64
cancel context.CancelFunc
}
entries map[string]vmMonitorEntry
}{
entries: map[string]struct {
id uint64
cancel context.CancelFunc
}{},
entries: map[string]vmMonitorEntry{},
}
type vmMonitorEntry struct {
id uint64
cancel context.CancelFunc
done chan struct{}
}
var (
vmMonitorStopTimeout = 5 * time.Second
vmMonitorPollTimeout = 5 * time.Second
)
func waitVMMonitorDone(done <-chan struct{}) {
if done == nil {
return
}
timeout := vmMonitorStopTimeout
if timeout <= 0 {
<-done
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-done:
case <-timer.C:
}
}
func stopVMMonitor(name string) {
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur, ok := vmMonitors.entries[name]
if ok {
cur.cancel()
delete(vmMonitors.entries, name)
}
vmMonitors.mu.Unlock()
if ok {
waitVMMonitorDone(cur.done)
}
}
func stopAllVMMonitors() {
vmMonitors.mu.Lock()
for name, cur := range vmMonitors.entries {
waiters := make([]chan struct{}, 0, len(vmMonitors.entries))
for _, cur := range vmMonitors.entries {
cur.cancel()
delete(vmMonitors.entries, name)
if cur.done != nil {
waiters = append(waiters, cur.done)
}
}
vmMonitors.mu.Unlock()
timeout := vmMonitorStopTimeout
if timeout <= 0 {
for _, done := range waiters {
<-done
}
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
for _, done := range waiters {
select {
case <-done:
case <-timer.C:
return
}
}
}
func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Time) {
@@ -55,17 +99,20 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
return
}
ctx, cancel := context.WithCancel(a.baseCtx())
done := make(chan struct{})
var prevDone chan struct{}
vmMonitors.mu.Lock()
if cur, ok := vmMonitors.entries[name]; ok {
cur.cancel()
prevDone = cur.done
}
vmMonitors.seq++
myID := vmMonitors.seq
vmMonitors.entries[name] = struct {
id uint64
cancel context.CancelFunc
}{id: myID, cancel: cancel}
vmMonitors.entries[name] = vmMonitorEntry{id: myID, cancel: cancel, done: done}
vmMonitors.mu.Unlock()
if prevDone != nil {
waitVMMonitorDone(prevDone)
}
if vmstart.ReadVMDisplay(detail.Directory).TargetDisplay != "" {
go func() {
@@ -83,6 +130,7 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
defer func() {
cancel()
vmMonitors.mu.Lock()
close(done)
if cur, ok := vmMonitors.entries[name]; ok && cur.id == myID {
delete(vmMonitors.entries, name)
}
@@ -137,11 +185,19 @@ func (a *App) startVMMonitor(name string, detail driver.VMInfo, startAt time.Tim
}
case <-hbTicker.C:
loc := a.locale()
pid, running := a.currentVMPID(ctx, name)
hbCtx, hbCancel := context.WithTimeout(ctx, vmMonitorPollTimeout)
pid, running := a.currentVMPID(hbCtx, name)
hbCancel()
if ctx.Err() != nil {
return
}
if !running {
a.emitVMLog(name, i18n.T(loc, "monitor.exited"))
return
}
if pid <= 0 {
continue
}
now := time.Now()
dt := now.Sub(lastSampleAt).Seconds()
if dt <= 0 {
@@ -348,12 +404,9 @@ func fileSizeBytes(path string) int64 {
}
func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Report, qmpAddr string) {
a.mu.Lock()
rawLoc := a.cfg.Locale
rtCommit := a.cfg.ActiveRuntime
pinPCores := a.cfg.AutoPinPCores
a.mu.Unlock()
loc := i18n.EffectiveLocale(rawLoc)
cfg := a.runtimeConfig()
rtCommit := cfg.ActiveRuntime
loc := i18n.EffectiveLocale(cfg.Locale)
if rtCommit == "" {
rtCommit = "auto"
}
@@ -365,7 +418,7 @@ func (a *App) emitStartSummary(name string, detail driver.VMInfo, rep host.Repor
case strings.Contains(lowExtra, "kernel-irqchip=on"):
irqMode = "on"
}
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, pinPCores, detail.CPUs)
pinStr := vmstart.AffinitySummary(loc, rep, detail.Directory, cfg.AutoPinPCores, detail.CPUs)
coldStr := i18n.T(loc, "monitor.start.off")
if qmpAddr != "" {
coldStr = i18n.T(loc, "monitor.start.on")
+13 -15
View File
@@ -281,6 +281,12 @@ func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
}
}
func activateRuntime(ctx context.Context, cfg *config.Config, loc i18n.Locale, commit string) error {
return rt.Activate(ctx, cfg, commit, func(warning error) {
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, warning))
})
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use|remove>")
@@ -297,8 +303,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
}
return err
}
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
@@ -333,21 +338,14 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime use <commit>")
}
list, err := rt.List(cfg)
if err != nil {
if err := activateRuntime(context.Background(), cfg, loc, args[1]); err != nil {
if errors.Is(err, rt.ErrNotFound) {
return errors.New(i18n.T(loc, "runtime.not_found", args[1]))
}
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("%s", i18n.T(loc, "runtime.not_found", args[1]))
fmt.Println(i18n.T(loc, "runtime.activated", args[1]))
return nil
case "remove", "rm", "delete":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime remove <commit>")
+10 -2
View File
@@ -80,8 +80,16 @@ func createMacOSVM(ctx context.Context, cfg *config.Config, loc i18n.Locale, in
}
client := prep.Client
opts := reims.CreateOpts{Name: in.Name, Dir: in.Dir, MacOS: in.MacOS, CPUs: in.CPUs, Memory: in.Memory, DiskSize: in.DiskSize, GPU: in.GPU, Capture: &in.Capture, Logs: &in.Logs, GuestLang: strings.TrimSpace(in.GuestLang), Start: false}
existingVMs, _ := client.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
existingVMs, err := client.List(ctx)
if err != nil {
return fmt.Errorf("check existing VMs before create: %w", err)
}
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), opts, existingVMs, loc); issue != nil {
return errors.New(issue.Message)
}
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr != nil {
return fmt.Errorf("clean unfinished VM directory: %w", rerr)
} else if removed != "" {
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
}
if installer.ShouldPrefetchOcBinaryData(prep.Runtime.Manifest.UtilCommit, prep.Runtime.Manifest.UtilVersion) {
+1 -2
View File
@@ -90,8 +90,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
_ = os.Remove(path)
r.Commit = inst.Commit
}
cfg.ActiveRuntime = r.Commit
if err := config.Save("", cfg); err != nil {
if err := activateRuntime(ctx, cfg, loc, r.Commit); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", r.Commit))
+17 -5
View File
@@ -20,6 +20,7 @@ type Config struct {
DefaultGPU string `json:"default_gpu,omitempty"`
// RuntimeChannel is "stable" (default, also when empty) or "alpha" (legacy alias "candidate").
RuntimeChannel string `json:"runtime_channel,omitempty"`
QEMUASLR bool `json:"qemu_aslr,omitempty"`
// AppUpdateChannel is "stable" (default, also when empty), "alpha", or "dev":
// controls which Reims-Go client releases CheckAppUpdate offers, and whether
// previous executables/installers are kept on startup for rollback.
@@ -209,11 +210,22 @@ func Load(path string) (*Config, error) {
if path == "" {
path = DefaultConfigPath()
}
raw, err := os.ReadFile(path)
cfg, err := LoadExisting(path)
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return cfg, err
}
// LoadExisting reads an existing config and reports a missing file to the caller.
func LoadExisting(path string) (*Config, error) {
var raw []byte
err := retryFileConflict(func() error {
var readErr error
raw, readErr = os.ReadFile(path)
return readErr
})
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return nil, err
}
cfg := Default()
@@ -257,7 +269,7 @@ func Save(path string, cfg *Config) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return atomicfile.WriteJSON(path, cfg, 0o644)
return retryFileConflict(func() error { return atomicfile.WriteJSON(path, cfg, 0o644) })
}
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows
package config
func retryFileConflict(op func() error) error { return op() }
+23
View File
@@ -0,0 +1,23 @@
package config
import (
"errors"
"time"
"golang.org/x/sys/windows"
)
// A reader can briefly deny replacement, and an overlapping replacement
// can briefly deny a new read. A persistent permission error must surface.
func retryFileConflict(op func() error) error {
err := op()
for delay := 5 * time.Millisecond; delay <= 80*time.Millisecond; delay *= 2 {
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) && !errors.Is(err, windows.ERROR_SHARING_VIOLATION) &&
!errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
break
}
time.Sleep(delay)
err = op()
}
return err
}
@@ -0,0 +1,52 @@
package config
import (
"path/filepath"
"testing"
"testing/synctest"
"golang.org/x/sys/windows"
)
func TestConfigRecoversFromWindowsSharingConflict(t *testing.T) {
for _, operation := range []string{"load", "save"} {
t.Run(operation, func(t *testing.T) {
cfg := Config{DataRoot: t.TempDir(), ActiveRuntime: "first"}
path := filepath.Join(cfg.DataRoot, "reims-go.json")
if err := Save(path, &cfg); err != nil {
t.Fatal(err)
}
name, err := windows.UTF16PtrFromString(path)
if err != nil {
t.Fatal(err)
}
handle, err := windows.CreateFile(name, windows.GENERIC_READ, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
synctest.Test(t, func(t *testing.T) {
result := make(chan error, 1)
go func() {
if operation == "load" {
_, err := LoadExisting(path)
result <- err
return
}
cfg.ActiveRuntime = "second"
result <- Save(path, &cfg)
}()
synctest.Wait() // The operation has reached its first retry.
if err := windows.CloseHandle(handle); err != nil {
t.Fatal(err)
}
if err := <-result; err != nil {
t.Fatal(err)
}
})
got, err := LoadExisting(path)
if err != nil || got.ActiveRuntime != cfg.ActiveRuntime {
t.Fatalf("load after %s: got %+v, err %v", operation, got, err)
}
})
}
}
+10
View File
@@ -0,0 +1,10 @@
package host
import "errors"
const QEMUASLRHelperArg = "--apply-qemu-aslr"
// The elevated helper has no output channel back to the GUI.
const QEMUASLRImagePolicyExitCode = 78
var ErrQEMUASLRImagePolicy = errors.New("a QEMU path filter would shadow an image-wide Windows setting")
+14
View File
@@ -0,0 +1,14 @@
//go:build !windows
package host
import (
"context"
"errors"
)
func ApplyQEMUASLR(_, _ string) error {
return errors.New("QEMU ASLR requires Windows")
}
func SyncQEMUASLR(ctx context.Context, _, _ string) error { return ctx.Err() }
+364
View File
@@ -0,0 +1,364 @@
package host
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
const (
qemuImage = "qemu-system-x86_64.exe"
qemuIFEO = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\` + qemuImage
aslrOriginal = "ReimsGoASLROriginal"
filterMode = "ReimsGoASLRFilterMode"
createdFilter = 1 << 8
createdOptions = 1 << 9
)
// SyncQEMUASLR reconciles this runtime directory's owned mitigations. An empty
// target removes them. No elevation is needed when the rules already match.
func SyncQEMUASLR(ctx context.Context, runtimesDir, qemuPath string) error {
if err := ctx.Err(); err != nil {
return err
}
err := ApplyQEMUASLR(runtimesDir, qemuPath)
if !errors.Is(err, windows.ERROR_ACCESS_DENIED) || windows.GetCurrentProcessToken().IsElevated() {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
args := windows.ComposeCommandLine([]string{QEMUASLRHelperArg, runtimesDir, qemuPath})
// Once authorized, wait for the helper to finish before the caller commits
// or rolls back the corresponding runtime preference.
code, err := runElevatedWait(context.WithoutCancel(ctx), exe, args)
if err != nil {
return err
}
switch code {
case 0:
return nil
case QEMUASLRImagePolicyExitCode:
return ErrQEMUASLRImagePolicy
default:
return fmt.Errorf("apply QEMU ASLR: helper exited with code %d", code)
}
}
func ApplyQEMUASLR(runtimesDir, qemuPath string) error {
// Separate data directories can share the image key and its UseFilter value.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
name := windows.StringToUTF16Ptr(`Global\Reims-Go-QEMU-ASLR`)
mutex, err := windows.CreateMutex(nil, false, name)
if err != nil && !errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
return err
}
defer windows.CloseHandle(mutex)
event, err := windows.WaitForSingleObject(mutex, 5000)
if err != nil {
return err
}
if event != windows.WAIT_OBJECT_0 && event != windows.WAIT_ABANDONED {
return errors.New("timed out waiting for the QEMU policy update")
}
defer windows.ReleaseMutex(mutex)
return reconcileQEMUASLR(registry.LOCAL_MACHINE, qemuIFEO, runtimesDir, qemuPath, windows.GetCurrentProcessToken().IsElevated())
}
func runtimeQEMUPath(root, path string) bool {
rel, err := filepath.Rel(root, path)
if err != nil || !filepath.IsLocal(rel) {
return false
}
parts := strings.Split(rel, `\`)
return (len(parts) == 4 || len(parts) == 5) &&
strings.EqualFold(filepath.Join(parts[len(parts)-3:]...), filepath.Join("qemu", "bin", qemuImage))
}
// Without elevation the same checks run read-only, even if a custom ACL would
// allow writing some of the keys. Declining UAC must leave every key untouched.
func reconcileQEMUASLR(hive registry.Key, imagePath, root, target string, canWrite bool) error {
if !filepath.IsAbs(root) || !strings.EqualFold(filepath.Base(root), "runtimes") ||
(target != "" && (!filepath.IsAbs(target) || filepath.Clean(target) != target || !runtimeQEMUPath(root, target))) {
return fmt.Errorf("invalid QEMU ASLR runtime path %q in %q", target, root)
}
image, err := registry.OpenKey(hive, imagePath, registry.READ)
var createdImage bool
if errors.Is(err, registry.ErrNotExist) {
if target == "" {
return nil
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
var existed bool
image, existed, err = registry.CreateKey(hive, imagePath, registry.READ|registry.WRITE)
createdImage = !existed
}
if err != nil {
return err
}
defer image.Close()
names, err := image.ReadSubKeyNames(-1)
if err != nil {
return err
}
var active string
var stale []string
otherOwner := false
filters := len(names)
for _, name := range names {
path, owned, err := readASLRFilter(image, name)
if aslrKeyGone(err) {
filters--
continue
}
if err != nil {
return err
}
if !runtimeQEMUPath(root, path) {
otherOwner = otherOwner || owned
continue
}
if strings.EqualFold(path, target) {
if active != "" {
return fmt.Errorf("multiple QEMU policy filters for %q", path)
}
active = name
} else if owned {
stale = append(stale, name)
}
}
if target != "" {
if err := enableASLRPathFilters(image, createdImage, active == "", filters, canWrite); err != nil {
return err
}
if active == "" {
active = fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
}
if err := updateASLRFilter(image, active, target, canWrite); err != nil {
return err
}
}
for _, name := range stale {
if err := updateASLRFilter(image, name, "", canWrite); err != nil && !aslrKeyGone(err) {
return err
}
}
if target != "" || otherOwner {
return nil
}
return restoreASLRFilterMode(hive, imagePath, image, canWrite)
}
// A different policy editor can remove a filter after it was enumerated.
func aslrKeyGone(err error) bool {
return errors.Is(err, registry.ErrNotExist) || errors.Is(err, windows.ERROR_KEY_DELETED)
}
func readASLRFilter(image registry.Key, name string) (path string, owned bool, err error) {
k, err := registry.OpenKey(image, name, registry.QUERY_VALUE)
if err != nil {
return "", false, err
}
defer k.Close()
path, _, err = k.GetStringValue("FilterFullPath")
if errors.Is(err, registry.ErrNotExist) {
return "", false, nil // An existing subkey without a path still counts.
}
if err != nil {
return "", false, err
}
_, _, err = k.GetIntegerValue(aslrOriginal)
if errors.Is(err, registry.ErrNotExist) {
return path, false, nil
}
return path, err == nil, err
}
func enableASLRPathFilters(image registry.Key, createdImage, newPath bool, filters int, canWrite bool) error {
if newPath {
values, err := image.ReadValueNames(-1)
if err != nil {
return err
}
for _, v := range values {
if !strings.EqualFold(v, "UseFilter") && !strings.EqualFold(v, filterMode) {
return fmt.Errorf("%w: %q", ErrQEMUASLRImagePolicy, v)
}
}
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
if useFilter == 1 {
return nil
}
if filters != 0 || useFilter != 0 {
return errors.New("QEMU has incompatible Windows path filter settings")
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
// 1 = missing UseFilter, 2 = existing zero, 3 = newly created image.
mode := uint32(1)
if createdImage {
mode = 3
} else if err == nil {
mode = 2
}
w, err := registry.OpenKey(image, "", registry.SET_VALUE)
if err != nil {
return err
}
defer w.Close()
if err := w.SetDWordValue(filterMode, mode); err != nil {
return err
}
return w.SetDWordValue("UseFilter", 1)
}
func restoreASLRFilterMode(hive registry.Key, imagePath string, image registry.Key, canWrite bool) error {
mode, _, err := image.GetIntegerValue(filterMode)
if errors.Is(err, registry.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
info, err := image.Stat()
if err != nil {
return err
}
useFilter, _, err := image.GetIntegerValue("UseFilter")
if err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
w, err := registry.OpenKey(hive, imagePath, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if useFilter == 1 && info.SubKeyCount == 0 {
if mode == 3 && info.ValueCount == 2 {
return registry.DeleteKey(hive, imagePath)
}
if mode == 2 {
err = w.SetDWordValue("UseFilter", 0)
} else {
err = w.DeleteValue("UseFilter")
}
if err != nil {
return err
}
}
return w.DeleteValue(filterMode)
}
func updateASLRFilter(image registry.Key, name, target string, canWrite bool) error {
k, err := registry.OpenKey(image, name, registry.READ)
create := errors.Is(err, registry.ErrNotExist)
if create && target != "" {
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
var existed bool
k, existed, err = registry.CreateKey(image, name, registry.READ|registry.WRITE)
create = !existed
}
if err != nil {
return err
}
defer k.Close()
if create {
if err := k.SetStringValue("FilterFullPath", target); err != nil {
return err
}
} else if target != "" {
path, _, err := k.GetStringValue("FilterFullPath")
if err != nil || !strings.EqualFold(path, target) {
return fmt.Errorf("QEMU policy filter %q does not match %q", name, target)
}
}
options, _, err := k.GetBinaryValue("MitigationOptions")
newOptions := errors.Is(err, registry.ErrNotExist)
if newOptions {
options = make([]byte, 24)
} else if err != nil {
return err
}
if len(options) < 3 {
return errors.New("invalid QEMU MitigationOptions length")
}
original, _, err := k.GetIntegerValue(aslrOriginal)
owned := err == nil
if !owned && !errors.Is(err, registry.ErrNotExist) {
return err
}
// Windows PROCESS_CREATION_MITIGATION_POLICY_*_ASLR fields occupy bits
// 16..17 (bottom-up) and 20..21 (high entropy); value 1 means always on.
if target != "" && options[2]&0x33 == 0x11 {
return nil
}
if !canWrite {
return windows.ERROR_ACCESS_DENIED
}
w, err := registry.OpenKey(image, name, registry.READ|registry.WRITE)
if err != nil {
return err
}
defer w.Close()
if target != "" {
if !owned {
original = uint64(options[2] & 0x33)
if create {
original |= createdFilter
}
if newOptions {
original |= createdOptions
}
if err := w.SetDWordValue(aslrOriginal, uint32(original)); err != nil {
return err
}
}
options[2] = options[2]&^0x33 | 0x11
return w.SetBinaryValue("MitigationOptions", options)
}
for _, shift := range []uint{0, 4} {
mask := byte(3 << shift)
if options[2]&mask == 1<<shift {
options[2] = (options[2] &^ mask) | byte(original)&mask
}
}
if original&createdOptions != 0 && len(bytes.Trim(options, "\x00")) == 0 {
if err := w.DeleteValue("MitigationOptions"); err != nil && !errors.Is(err, registry.ErrNotExist) {
return err
}
} else if err := w.SetBinaryValue("MitigationOptions", options); err != nil {
return err
}
info, err := w.Stat()
if err != nil {
return err
}
if original&createdFilter != 0 && info.SubKeyCount == 0 && info.ValueCount == 2 {
// Only our journal and FilterFullPath remain.
return registry.DeleteKey(image, name)
}
return w.DeleteValue(aslrOriginal)
}
+260
View File
@@ -0,0 +1,260 @@
package host
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
func TestReadASLRFilterAfterEnumeration(t *testing.T) {
hive := registry.CURRENT_USER
keyPath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
image, _, err := registry.CreateKey(hive, keyPath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer registry.DeleteKey(hive, keyPath)
defer image.Close()
child, _, err := registry.CreateKey(image, "filter", registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer child.Close()
defer registry.DeleteKey(image, "filter")
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != 1 {
t.Fatalf("enumerated %v: %v", names, err)
}
name := names[0]
if _, owned, err := readASLRFilter(image, name); err != nil || owned {
t.Fatalf("existing subkey without FilterFullPath: owned %v, err %v", owned, err)
}
if err := child.SetDWordValue("FilterFullPath", 1); err != nil {
t.Fatal(err)
}
if _, _, err := readASLRFilter(image, name); err == nil || aslrKeyGone(err) {
t.Fatalf("invalid path value reported as a deleted key: %v", err)
}
if err := registry.DeleteKey(image, name); err != nil {
t.Fatal(err)
}
if _, _, err := readASLRFilter(image, name); !aslrKeyGone(err) {
t.Fatalf("reading a filter removed since enumeration: %v", err)
}
if aslrKeyGone(windows.ERROR_ACCESS_DENIED) || !aslrKeyGone(windows.ERROR_KEY_DELETED) {
t.Fatal("only disappearance should be ignored; access denied must reach UAC")
}
}
func TestQEMUASLRFollowsRuntimeAndRestoresOnlyOwnedRules(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
hive := registry.CURRENT_USER
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer func() {
names, _ := image.ReadSubKeyNames(-1)
for _, name := range names {
if err := registry.DeleteKey(image, name); err != nil {
t.Error(err)
}
}
image.Close()
if err := registry.DeleteKey(hive, imagePath); err != nil {
t.Error(err)
}
}()
root := filepath.Join(t.TempDir(), "runtimes")
current := filepath.Join(root, "current", "qemu", "bin", qemuImage)
backup := filepath.Join(root, "backup", "qemu", "bin", qemuImage)
update := func(target string) {
t.Helper()
if err := reconcileQEMUASLR(hive, imagePath, root, target, true); err != nil {
t.Fatal(err)
}
}
countFilters := func(want int) {
t.Helper()
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != want {
t.Fatalf("filters = %v, want %d, err = %v", names, want, err)
}
}
update("")
countFilters(0)
update(current)
update(current)
countFilters(1)
readByte := func(k registry.Key, want byte) {
t.Helper()
b, _, err := k.GetBinaryValue("MitigationOptions")
if err != nil || len(b) != 24 || b[2] != want {
t.Fatalf("mitigations = %x, want byte 2 = %02x, err = %v", b, want, err)
}
}
names, _ := image.ReadSubKeyNames(-1)
active, err := registry.OpenKey(image, names[0], registry.READ)
if err != nil {
t.Fatal(err)
}
readByte(active, 0x11)
active.Close()
probe := func(target string, want error) {
t.Helper()
if err := reconcileQEMUASLR(hive, imagePath, root, target, false); !errors.Is(err, want) {
t.Fatalf("read-only check for %q: got %v, want %v", target, err, want)
}
}
probe(current, nil)
probe("", windows.ERROR_ACCESS_DENIED)
countFilters(1)
// One manual OFF override and unrelated bits on the backup runtime.
manual, _, err := registry.CreateKey(image, "User filter", registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer manual.Close()
if err := manual.SetStringValue("FilterFullPath", backup); err != nil {
t.Fatal(err)
}
b := make([]byte, 24)
b[2] = 0x82
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
probe(backup, windows.ERROR_ACCESS_DENIED)
countFilters(2)
readByte(manual, 0x82)
update(backup)
countFilters(1)
readByte(manual, 0x91)
update(current)
countFilters(2)
readByte(manual, 0x82)
update("")
update("")
countFilters(1)
if _, _, err := manual.GetIntegerValue(aslrOriginal); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("ownership marker remains: %v", err)
}
// Options already ON before enabling continue to belong to the user.
b[2] = 0x91
if err := manual.SetBinaryValue("MitigationOptions", b); err != nil {
t.Fatal(err)
}
update(backup)
update("")
readByte(manual, 0x91)
}
func TestQEMUASLRRestoresImageKey(t *testing.T) {
imagePath := fmt.Sprintf(`Software\Reims-Go-ASLR-Test-%d-%d`, os.Getpid(), time.Now().UnixNano())
root := filepath.Join(t.TempDir(), "runtimes")
target := filepath.Join(root, "current", "qemu", "bin", qemuImage)
hive := registry.CURRENT_USER
update := func(target string) error { return reconcileQEMUASLR(hive, imagePath, root, target, true) }
t.Cleanup(func() {
if err := update(""); err != nil {
t.Error(err)
}
if err := registry.DeleteKey(hive, imagePath); err != nil && !errors.Is(err, registry.ErrNotExist) {
t.Error(err)
}
})
if err := reconcileQEMUASLR(hive, imagePath, root, target, false); !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
t.Fatalf("missing image must require elevation: %v", err)
}
if k, err := registry.OpenKey(hive, imagePath, registry.READ); !errors.Is(err, registry.ErrNotExist) {
k.Close()
t.Fatalf("read-only check created the image key: %v", err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if k, err := registry.OpenKey(hive, imagePath, registry.READ); !errors.Is(err, registry.ErrNotExist) {
k.Close()
t.Fatalf("new image key not removed: %v", err)
}
image, _, err := registry.CreateKey(hive, imagePath, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer image.Close()
if err := image.SetDWordValue("UseFilter", 0); err != nil {
t.Fatal(err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if mode, _, err := image.GetIntegerValue("UseFilter"); err != nil || mode != 0 {
t.Fatalf("restored UseFilter = %v, %v", mode, err)
}
if err := update(target); err != nil {
t.Fatal(err)
}
imagePolicy := []byte{1, 0, 0}
if err := image.SetBinaryValue("MitigationOptions", imagePolicy); err != nil {
t.Fatal(err)
}
next := filepath.Join(root, "upgrade", "qemu", "bin", qemuImage)
for _, canWrite := range []bool{false, true} {
if err := reconcileQEMUASLR(hive, imagePath, root, next, canWrite); !errors.Is(err, ErrQEMUASLRImagePolicy) {
t.Fatalf("expected image-wide conflict (write %v), got %v", canWrite, err)
}
}
if got, _, err := image.GetBinaryValue("MitigationOptions"); err != nil || !bytes.Equal(got, imagePolicy) {
t.Fatalf("image policy changed: %x, %v", got, err)
}
names, err := image.ReadSubKeyNames(-1)
if err != nil || len(names) != 1 {
t.Fatalf("unexpected path filters after conflict: %v, %v", names, err)
}
if path, owned, err := readASLRFilter(image, names[0]); err != nil || !owned || path != target {
t.Fatalf("previous filter changed: %q, owned %v, %v", path, owned, err)
}
if err := update(""); err != nil {
t.Fatal(err)
}
if err := image.DeleteValue("MitigationOptions"); err != nil {
t.Fatal(err)
}
if err := image.SetDWordValue("UseFilter", 1); err != nil {
t.Fatal(err)
}
name := fmt.Sprintf("Reims-Go-%x", sha256.Sum256([]byte(strings.ToLower(target))))
filter, _, err := registry.CreateKey(image, name, registry.ALL_ACCESS)
if err != nil {
t.Fatal(err)
}
defer registry.DeleteKey(image, name)
defer filter.Close()
if err := filter.SetStringValue("FilterFullPath", `C:\Other\`+qemuImage); err != nil {
t.Fatal(err)
}
if err := update(target); err == nil {
t.Fatal("unexpectedly adopted a filter for a different executable")
}
if _, _, err := filter.GetBinaryValue("MitigationOptions"); !errors.Is(err, registry.ErrNotExist) {
t.Fatalf("foreign filter was modified: %v", err)
}
}
+25
View File
@@ -187,8 +187,11 @@ var catalog = map[Locale]map[string]string{
"err.plugin.in_use": "插件「{id}」正在被虚拟机使用,无法停用或卸载:{reason}",
"err.plugin.safe_mode": "当前处于安全模式,已暂停加载和变更第三方插件",
"err.plugin.system_locked": "系统核心组件「{id}」不可停用或卸载",
"err.qemu_aslr.cancelled": "已取消 Windows 管理员授权,QEMU ASLR 设置保持原样",
"err.qemu_aslr.image_policy": "Windows 已按程序名为 qemu-system-x86_64.exe 配置防护,已跳过此运行时的 ASLR 规则。可在 Windows 安全中心的「漏洞保护 → 程序设置」中管理 QEMU 的 ASLR",
"err.quit.stop_failed": "无法关闭虚拟机「{name}」,已取消退出。",
"err.quit.timeout": "虚拟机「{name}」关机超时,已取消退出。",
"err.runtime_changed": "操作期间运行时已切换,请重试以使用当前选定的版本。",
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
"err.snapshot.name_empty": "请输入恢复点名称",
"err.snapshot.name_invalid": "恢复点名称包含不支持的控制字符或引号",
@@ -538,13 +541,16 @@ var catalog = map[Locale]map[string]string{
"runtime.empty": "尚未安装任何便携运行时。",
"runtime.install_in_use": "停止使用此运行时的虚拟机后再试一次导入",
"runtime.installed": "便携运行时已安装:{commit} -> {dir}",
"runtime.installed_not_activated": "运行时 {commit} 已安装,点击「激活」重试",
"runtime.not_found": "未找到运行时 \"{name}\"",
"runtime.qemu_aslr.warning": "本次启动未能确认 QEMU 的 ASLR 设置。可在「内核」页关闭再开启 ASLR 以重试。",
"runtime.remote.downloading": "下载运行时 {commit}({channel},{size})",
"runtime.remote.empty": "当前通道还没有发布运行时(alpha 版需要加 --alpha)。",
"runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。",
"runtime.remove_active": "不能删除当前正在使用的运行时 \"{commit}\",请先切换到其他版本",
"runtime.remove_in_use": "运行时 \"{commit}\" 正被运行中的虚拟机占用,请先停止相关虚拟机后再删除",
"runtime.removed": "已删除运行时:{commit}({dir})",
"runtimeActivationFailed": "运行时激活失败",
"safeModeBanner": "安全模式已启用:已跳过全部第三方插件并回退至内置默认主题",
"safeModeManagePlugins": "管理插件",
"save": "保存",
@@ -655,6 +661,10 @@ var catalog = map[Locale]map[string]string{
"uptimeMinutesSeconds": "{m} 分 {s} 秒",
"uptimeSeconds": "{s} 秒",
"validate.bridge_uplink_required": "选择桥接使用的出口网卡",
"validate.default_dir_not_empty": "默认目录 {dir} 非空,更换名称、选择空目录或先清理旧目录",
"validate.dir_inaccessible": "目标目录 {dir} 无法访问,检查权限或选择其他目录",
"validate.dir_not_directory": "目标路径 {dir} 不是目录,选择新目录或空目录",
"validate.dir_not_empty": "目标目录 {dir} 非空,选择新目录或空目录",
"validate.disk_not_found": "所选虚拟磁盘文件不存在",
"validate.eject_before_controller_change": "切换磁盘控制器前须先弹出 macOS 安装盘",
"validate.gpu_icd_not_found": "所选 Vulkan ICD JSON 文件不存在",
@@ -879,8 +889,11 @@ var catalog = map[Locale]map[string]string{
"err.plugin.in_use": "Plugin “{id}” is currently in use and cannot be disabled or removed: {reason}",
"err.plugin.safe_mode": "Safe mode is active; third-party plugin changes are paused",
"err.plugin.system_locked": "Core system component “{id}” cannot be disabled or removed",
"err.qemu_aslr.cancelled": "Windows authorization was canceled before the QEMU ASLR changes were applied",
"err.qemu_aslr.image_policy": "Windows already has a program-wide rule for qemu-system-x86_64.exe, so this runtime’s ASLR rule was skipped. Manage QEMU’s ASLR in Windows Security under Exploit protection → Program settings.",
"err.quit.stop_failed": "Could not shut down “{name}”. Quit canceled.",
"err.quit.timeout": "Shutdown timed out for “{name}”. Quit canceled.",
"err.runtime_changed": "The selected runtime changed during this operation. Retry to use the current selection.",
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
"err.snapshot.name_empty": "Enter a restore point name",
"err.snapshot.name_invalid": "Restore point name contains unsupported characters or quotes",
@@ -1230,13 +1243,16 @@ var catalog = map[Locale]map[string]string{
"runtime.empty": "No portable runtimes installed.",
"runtime.install_in_use": "Stop the VMs using this runtime and try the import again",
"runtime.installed": "Portable runtime installed: {commit} -> {dir}",
"runtime.installed_not_activated": "Runtime {commit} is installed. Select Activate to retry activation.",
"runtime.not_found": "runtime \"{name}\" not found",
"runtime.qemu_aslr.warning": "Starting without confirmed QEMU ASLR settings. To retry, turn ASLR off and on in Engine.",
"runtime.remote.downloading": "Downloading runtime {commit} ({channel}, {size})",
"runtime.remote.empty": "No runtime is published on this channel yet (add --alpha for alpha builds).",
"runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.",
"runtime.remove_active": "cannot remove active runtime \"{commit}\"; switch to another version first",
"runtime.remove_in_use": "runtime \"{commit}\" is in use by a running VM; stop the VM and try again",
"runtime.removed": "Removed runtime: {commit} ({dir})",
"runtimeActivationFailed": "Runtime activation failed",
"safeModeBanner": "Safe mode is active: all third-party plugins are disabled and the built-in theme is restored",
"safeModeManagePlugins": "Manage plugins",
"save": "Save",
@@ -1347,6 +1363,10 @@ var catalog = map[Locale]map[string]string{
"uptimeMinutesSeconds": "{m}m {s}s",
"uptimeSeconds": "{s}s",
"validate.bridge_uplink_required": "Choose an uplink adapter for bridged networking",
"validate.default_dir_not_empty": "Default folder {dir} is not empty; use another name, choose an empty folder, or clear it first",
"validate.dir_inaccessible": "Target folder {dir} cannot be accessed; check permissions or choose another folder",
"validate.dir_not_directory": "Target path {dir} is not a folder; choose a new or empty folder",
"validate.dir_not_empty": "Target folder {dir} is not empty; choose a new or empty folder",
"validate.disk_not_found": "Selected disk image file does not exist",
"validate.eject_before_controller_change": "Eject the macOS installer before changing disk controller",
"validate.gpu_icd_not_found": "Selected Vulkan ICD JSON file does not exist",
@@ -1525,6 +1545,7 @@ var paramOrder = map[string][]string{
"resLooksLike": {"h", "w"},
"runtime.activated": {"commit"},
"runtime.installed": {"commit", "dir"},
"runtime.installed_not_activated": {"commit"},
"runtime.not_found": {"name"},
"runtime.remote.downloading": {"commit", "channel", "size"},
"runtime.remove_active": {"commit"},
@@ -1565,6 +1586,10 @@ var paramOrder = map[string][]string{
"uptimeHoursMinutes": {"h", "m"},
"uptimeMinutesSeconds": {"m", "s"},
"uptimeSeconds": {"s"},
"validate.default_dir_not_empty": {"dir"},
"validate.dir_inaccessible": {"dir"},
"validate.dir_not_directory": {"dir"},
"validate.dir_not_empty": {"dir"},
"validate.invalid_audio_backend": {"backend"},
"validate.invalid_cpus": {"max"},
"validate.memory_exceeds_commit": {"mem", "limit", "rec"},
+8
View File
@@ -98,6 +98,14 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
if err := c.CheckCoWCloneSource(ctx, sourceName, srcDisk, cloneName); err != nil {
return err
}
cloneTargetOpts := reims.CreateOpts{Name: cloneName}
registered, err := c.List(ctx)
if err != nil {
return fmt.Errorf("check clone target directory: %w", err)
}
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), cloneTargetOpts, registered, cfg.Locale); issue != nil {
return errors.New(issue.Message)
}
if _, err := os.Lstat(overlayPath); err == nil {
return fmt.Errorf("clone overlay already exists: %s", overlayPath)
} else if !os.IsNotExist(err) {
+14
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
@@ -226,6 +227,19 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateCreate(opts, rep, cfg.Locale)
var registered []reims.VMListItem
xdgDataDir := ""
if strings.TrimSpace(cfg.DataRoot) != "" {
xdgDataDir = cfg.XDGDataDir()
if regVMs, err := reims.ListRegisteredVMs(cfg.DataRoot); err == nil {
for _, vm := range regVMs {
registered = append(registered, reims.VMListItem{Name: vm.Name, Dir: vm.Directory})
}
}
}
if issue := reims.ValidateCreateTargetDir(xdgDataDir, opts, registered, cfg.Locale); issue != nil {
issues = append(issues, *issue)
}
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
+112
View File
@@ -0,0 +1,112 @@
package macosdriver
import (
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
)
func TestReimsMacOSDriverValidateCreateRejectsLeftoverDir(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir()}
leftover := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", "macos-tahoe2")
if err := os.MkdirAll(leftover, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(leftover, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
d := NewReimsMacOSDriver(func() config.Config { return cfg })
issues := d.ValidateCreate(context.Background(), driver.CreateRequest{
Name: "macos-tahoe2",
Options: map[string]any{
"cpus": 2,
"memory": "4G",
"disk_size": "64G",
},
})
found := false
for _, is := range issues {
if is.Field == "dir" {
found = true
break
}
}
if !found {
t.Fatalf("expected dir validation issue for leftover VM folder, got %+v", issues)
}
}
// A running `reims-ctl create` is unregistered and has no vm.toml until it ends,
// so its directory looks the same as one left by a killed create.
func TestReimsMacOSDriverKeepsDirOfRunningCreate(t *testing.T) {
d := newFakeRuntimeDriver(t)
ctx := context.Background()
cfg := d.getConfig()
target := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", "new-mac")
if err := os.MkdirAll(target, 0o755); err != nil {
t.Fatal(err)
}
disk := filepath.Join(target, "disk.qcow2")
for _, path := range []string{filepath.Join(target, ".reims-ctl-creating"), disk} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
var out bytes.Buffer
if err := d.Create(ctx, driver.CreateRequest{Name: "new-mac"}, &out, &out); err == nil {
t.Fatal("Create succeeded in a directory another create is using")
}
if _, err := os.Stat(disk); err != nil {
t.Fatalf("Create removed the directory of a running create: %v", err)
}
source, err := d.Show(ctx, "recovery-vm")
if err != nil {
t.Fatal(err)
}
for name, content := range map[string]string{"vm.toml": "disk = \"disk.qcow2\"\n", "disk.qcow2": ""} {
if err := os.WriteFile(filepath.Join(source.Directory, name), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
// The fixture has no qemu-img, so the clone stops when it makes the overlay.
err = d.CloneCoW(ctx, "recovery-vm", "new-mac", &out, &out)
if err == nil || !strings.Contains(out.String(), "Creating CoW overlay") {
t.Fatalf("CloneCoW = %v, want a failure after the target directory check; output: %s", err, out.String())
}
if _, err := os.Stat(disk); err != nil {
t.Fatalf("CloneCoW removed the directory of a running create: %v", err)
}
}
func TestReimsMacOSDriverCreateProtectsRegisteredVMInAbortedDir(t *testing.T) {
d := newFakeRuntimeDriver(t)
vms, err := d.List(context.Background())
if err != nil || len(vms) == 0 {
t.Fatalf("List = %+v, %v", vms, err)
}
parent := filepath.Dir(vms[0].Directory)
marker := filepath.Join(parent, ".reims-ctl-creating")
if err := os.WriteFile(marker, nil, 0o600); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
err = d.Create(context.Background(), driver.CreateRequest{
Name: "new-mac",
Dir: parent,
}, &stdout, &stderr)
if err == nil {
t.Fatal("expected Create to reject aborted dir holding registered VMs")
}
if _, statErr := os.Stat(vms[0].Directory); statErr != nil {
t.Fatalf("registered VM dir %s must not be removed: %v", vms[0].Directory, statErr)
}
}
+138 -16
View File
@@ -14,6 +14,7 @@ import (
"strings"
"sync"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
@@ -22,12 +23,37 @@ import (
// directory and removed once vm.toml is saved (upstream 3731afd create.rs:451).
const creatingMarker = ".reims-ctl-creating"
// ResolveCreateTargetDir returns the directory `reims-ctl create` will claim
// for opts (opts.Dir if set, otherwise <xdgDataDir>/reims-ctl/vms/<name>).
func ResolveCreateTargetDir(xdgDataDir string, opts CreateOpts) string {
if target := strings.TrimSpace(opts.Dir); target != "" {
return filepath.Clean(config.ExpandHomePath(target))
}
name := strings.TrimSpace(opts.Name)
if name == "" || !reVMName.MatchString(name) || strings.TrimSpace(xdgDataDir) == "" {
return ""
}
return filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
// IsAbortedCreateDir reports whether dir holds a `.reims-ctl-creating` marker
// without `vm.toml`, indicating a previously killed `reims-ctl create` run.
func IsAbortedCreateDir(dir string) bool {
if strings.TrimSpace(dir) == "" {
return false
}
markerInfo, err := os.Stat(filepath.Join(dir, creatingMarker))
if err != nil || markerInfo.IsDir() {
return false
}
_, err = os.Stat(filepath.Join(dir, "vm.toml"))
return errors.Is(err, os.ErrNotExist)
}
// CleanAbortedCreateDir removes an unregistered VM target directory left behind
// by a previously killed `reims-ctl create` run. It only removes a directory
// when all three safety conditions hold:
// 1. opts.Name is not present in registered VMs,
// 2. `.reims-ctl-creating` exists inside the directory, and
// 3. `vm.toml` does NOT exist inside the directory.
// when the name and directory are unregistered and the directory contains
// `.reims-ctl-creating` without `vm.toml`.
//
// Returns the removed path if cleaned, or "" if nothing was touched.
func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMListItem) (string, error) {
@@ -40,18 +66,8 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
return "", nil
}
}
target := strings.TrimSpace(opts.Dir)
if target == "" {
if strings.TrimSpace(xdgDataDir) == "" {
return "", nil
}
target = filepath.Join(xdgDataDir, "reims-ctl", "vms", name)
}
markerInfo, err := os.Stat(filepath.Join(target, creatingMarker))
if err != nil || markerInfo.IsDir() {
return "", nil
}
if _, err := os.Stat(filepath.Join(target, "vm.toml")); err == nil {
target := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" || !IsAbortedCreateDir(target) || containsRegisteredVMDir(target, registered) {
return "", nil
}
if err := os.RemoveAll(target); err != nil {
@@ -60,6 +76,112 @@ func CleanAbortedCreateDir(xdgDataDir string, opts CreateOpts, registered []VMLi
return target, nil
}
var (
targetDirStat = os.Stat
targetDirReadOne = readDirHasEntries
)
func readDirHasEntries(dir string) (bool, error) {
f, err := os.Open(dir)
if err != nil {
return false, err
}
entries, readErr := f.ReadDir(1)
_ = f.Close()
if readErr != nil && !errors.Is(readErr, io.EOF) {
return false, readErr
}
return len(entries) > 0, nil
}
// ValidateCreateTargetDir checks whether the directory `reims-ctl create` will
// claim already exists with conflicting contents. Empty directories and
// unregistered aborted-create directories (cleaned by CleanAbortedCreateDir)
// are allowed.
func ValidateCreateTargetDir(xdgDataDir string, opts CreateOpts, registered []VMListItem, loc i18n.Locale) *ValidationIssue {
target := ResolveCreateTargetDir(xdgDataDir, opts)
if target == "" {
return nil
}
name := strings.TrimSpace(opts.Name)
customDir := strings.TrimSpace(opts.Dir) != ""
isRegistered := false
for _, vm := range registered {
if strings.EqualFold(vm.Name, name) {
isRegistered = true
break
}
}
// When the name itself is already registered and no custom dir was chosen,
// name_taken already reports the conflict on the name field.
if isRegistered && !customDir {
return nil
}
info, err := targetDirStat(target)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !info.IsDir() {
return &ValidationIssue{
Field: "dir",
Code: "dir_not_directory",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_not_directory", i18n.Vars{"dir": target}),
}
}
nonEmpty, readErr := targetDirReadOne(target)
if readErr != nil {
if errors.Is(readErr, os.ErrNotExist) {
return nil
}
return &ValidationIssue{
Field: "dir",
Code: "dir_inaccessible",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, "validate.dir_inaccessible", i18n.Vars{"dir": target}),
}
}
if !nonEmpty {
return nil
}
if !isRegistered && IsAbortedCreateDir(target) && !containsRegisteredVMDir(target, registered) {
return nil
}
msgKey := "validate.default_dir_not_empty"
if customDir {
msgKey = "validate.dir_not_empty"
}
return &ValidationIssue{
Field: "dir",
Code: "dir_not_empty",
Params: map[string]any{"dir": target},
Message: i18n.M(loc, msgKey, i18n.Vars{"dir": target}),
}
}
func containsRegisteredVMDir(target string, registered []VMListItem) bool {
absTarget := absoluteDiskPath(target)
for _, vm := range registered {
if vm.Dir == "" {
continue
}
absVM := absoluteDiskPath(vm.Dir)
if pathInDirectory(target, vm.Dir) || pathInDirectory(absTarget, absVM) ||
pathInDirectory(vm.Dir, target) || pathInDirectory(absVM, absTarget) {
return true
}
}
return false
}
// IsWHPXNoAcceleratorError reports whether QEMU exited because Windows
// Hypervisor was not active. In that branch QEMU logs "WHPX: No accelerator
// found" and returns -ENOSPC ("failed to initialize whpx: No space left on
+158
View File
@@ -335,6 +335,43 @@ func TestCleanAbortedCreateDir(t *testing.T) {
}
}
func TestAbortedCreatePreservesRegisteredVMInTarget(t *testing.T) {
target := filepath.Join(t.TempDir(), "unfinished")
child := filepath.Join(target, "existing")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
for _, path := range []string{filepath.Join(target, creatingMarker), filepath.Join(child, "vm.toml")} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
opts := CreateOpts{Name: "new-vm", Dir: target}
registered := []VMListItem{{Name: "existing", Dir: child}}
if removed, err := CleanAbortedCreateDir("", opts, registered); err != nil || removed != "" {
t.Fatalf("cleanup = %q, %v, want registered VM preserved", removed, err)
}
if issue := ValidateCreateTargetDir("", opts, registered, i18n.EnUS); issue == nil || issue.Code != "dir_not_empty" {
t.Fatalf("validation = %+v, want directory conflict", issue)
}
// Symmetric protection: a subdirectory inside a registered VM's folder must not be cleaned either.
nested := filepath.Join(child, "unfinished")
if err := os.MkdirAll(nested, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nested, creatingMarker), nil, 0o600); err != nil {
t.Fatal(err)
}
nestedOpts := CreateOpts{Name: "nested-vm", Dir: nested}
if removed, err := CleanAbortedCreateDir("", nestedOpts, registered); err != nil || removed != "" {
t.Fatalf("nested cleanup = %q, %v, want registered VM subtree preserved", removed, err)
}
if issue := ValidateCreateTargetDir("", nestedOpts, registered, i18n.EnUS); issue == nil || issue.Code != "dir_not_empty" {
t.Fatalf("nested validation = %+v, want directory conflict", issue)
}
}
func TestWHPXNestedVirtCompat(t *testing.T) {
sampleErr := "2026-11-28T13:04:47Z qemu: -accel whpx: WHPX: Failed to enable nested virtualization, hr=80370302\n"
if !IsWHPXNestedVirtError(sampleErr) {
@@ -462,3 +499,124 @@ func TestDiskImportAndCoWArgs(t *testing.T) {
t.Fatalf("BuildCompactDiskArgs = %q", cmp)
}
}
func TestValidateCreateTargetDir(t *testing.T) {
dataDir := t.TempDir()
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe2")
// Missing directory is allowed.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("missing dir should be allowed, got %+v", issue)
}
// Empty directory is allowed.
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("empty dir should be allowed, got %+v", issue)
}
// Unregistered aborted create dir (.reims-ctl-creating without vm.toml) is allowed
// because CleanAbortedCreateDir removes it before create runs.
marker := filepath.Join(vmDir, creatingMarker)
if err := os.WriteFile(marker, nil, 0o644); err != nil {
t.Fatal(err)
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("aborted create dir should be allowed, got %+v", issue)
}
_ = os.Remove(marker)
// Leftover non-empty directory (e.g. from --keep-files or failed delete) is rejected.
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), []byte("name = \"macos-tahoe2\"\n"), 0o644); err != nil {
t.Fatal(err)
}
issueEn := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS)
if issueEn == nil || issueEn.Field != "dir" || issueEn.Code != "dir_not_empty" || !strings.Contains(issueEn.Message, vmDir) {
t.Fatalf("leftover default dir (en-US) = %+v", issueEn)
}
issueZh := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, nil, i18n.ZhCN)
if issueZh == nil || issueZh.Field != "dir" || issueZh.Code != "dir_not_empty" || !strings.Contains(issueZh.Message, vmDir) {
t.Fatalf("leftover default dir (zh-CN) = %+v", issueZh)
}
// Suppress duplicate dir error on default dir when name itself is already registered.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "macos-tahoe2"}, []VMListItem{{Name: "macos-tahoe2"}}, i18n.EnUS); issue != nil {
t.Fatalf("registered VM default dir should defer to name_taken, got %+v", issue)
}
// Non-empty custom dir is rejected even if VM name differs or is registered.
customDir := filepath.Join(t.TempDir(), "occupied")
if err := os.MkdirAll(customDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(customDir, "notes.txt"), []byte("keep"), 0o644); err != nil {
t.Fatal(err)
}
customIssue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "fresh-vm", Dir: customDir}, nil, i18n.EnUS)
if customIssue == nil || customIssue.Field != "dir" || customIssue.Code != "dir_not_empty" || !strings.Contains(customIssue.Message, customDir) {
t.Fatalf("non-empty custom dir = %+v", customIssue)
}
// Regular file at target path is rejected as dir_not_directory.
filePath := filepath.Join(t.TempDir(), "not-a-dir")
if err := os.WriteFile(filePath, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
fileIssue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "fresh-vm", Dir: filePath}, nil, i18n.EnUS)
if fileIssue == nil || fileIssue.Field != "dir" || fileIssue.Code != "dir_not_directory" {
t.Fatalf("regular file target = %+v", fileIssue)
}
// Invalid VM name with empty Dir must not stat outside vms/.
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "../escape"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("invalid name should return nil target dir issue, got %+v", issue)
}
}
func TestValidateCreateTargetDirInaccessible(t *testing.T) {
dataDir := t.TempDir()
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "locked-vm")
if err := os.MkdirAll(vmDir, 0o755); err != nil {
t.Fatal(err)
}
origStat := targetDirStat
origRead := targetDirReadOne
t.Cleanup(func() {
targetDirStat = origStat
targetDirReadOne = origRead
})
// Non-NotExist stat error (e.g., permission denied or NTFS delete-pending) must report dir_inaccessible.
targetDirStat = func(string) (os.FileInfo, error) {
return nil, os.ErrPermission
}
issueEn := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS)
if issueEn == nil || issueEn.Field != "dir" || issueEn.Code != "dir_inaccessible" || !strings.Contains(issueEn.Message, vmDir) {
t.Fatalf("stat permission error (en-US) = %+v", issueEn)
}
issueZh := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.ZhCN)
if issueZh == nil || issueZh.Field != "dir" || issueZh.Code != "dir_inaccessible" || !strings.Contains(issueZh.Message, vmDir) {
t.Fatalf("stat permission error (zh-CN) = %+v", issueZh)
}
// Non-NotExist ReadDir error must also report dir_inaccessible.
targetDirStat = origStat
targetDirReadOne = func(string) (bool, error) {
return false, os.ErrPermission
}
issueRead := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS)
if issueRead == nil || issueRead.Field != "dir" || issueRead.Code != "dir_inaccessible" {
t.Fatalf("readdir permission error = %+v", issueRead)
}
// If directory vanished between Stat and Open/ReadDir, allow it.
targetDirReadOne = func(string) (bool, error) {
return false, os.ErrNotExist
}
if issue := ValidateCreateTargetDir(dataDir, CreateOpts{Name: "locked-vm"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("vanished dir during readdir should be allowed, got %+v", issue)
}
}
+200 -22
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"runtime"
@@ -261,13 +262,47 @@ func (c *Client) createWithDisk(ctx context.Context, o CreateOpts, args []string
return c.run(ctx, stdout, stderr, args...)
}
func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool, removeVM func() error) error {
var deleteDirRetryDelays = []time.Duration{
50 * time.Millisecond,
100 * time.Millisecond,
150 * time.Millisecond,
250 * time.Millisecond,
400 * time.Millisecond,
600 * time.Millisecond,
800 * time.Millisecond,
}
func (c *Client) lockDeleteRegistry(ctx context.Context) (func(), error) {
if c.imagesDir != "" {
return c.lockCoWRegistry(ctx)
}
if c.registryDir == "" {
return func() {}, nil
}
if err := os.MkdirAll(c.registryDir, 0o755); err != nil {
return nil, err
}
wait, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
release, err := filelock.Acquire(wait, filepath.Join(c.registryDir, ".reims-go-delete.lock"), 0)
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
return nil, i18n.NewCodedError(c.Locale, "E_COW_REGISTRY_BUSY", "err.clone.registry_busy", nil, err)
}
return release, err
}
func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool, stdout io.Writer, removeVM func() error) error {
if keepFiles {
registry, err := c.lockCoWRegistry(ctx)
if err != nil {
return err
if c.imagesDir != "" || c.registryDir != "" {
registry, err := c.lockDeleteRegistry(ctx)
if err != nil {
return err
}
defer registry()
}
defer registry()
return removeVM()
}
if c.registryDir == "" {
return removeVM()
}
@@ -276,14 +311,17 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
return err
}
vm := findRegisteredVM(vms, name)
disk, managedPath := c.deletionDisk(vm)
release, err := c.LockCoWDisks(ctx, disk)
if err != nil {
return err
var disk, managedPath string
if c.imagesDir != "" {
disk, managedPath = c.deletionDisk(vm)
release, err := c.LockCoWDisks(ctx, disk)
if err != nil {
return err
}
defer release()
}
defer release()
registry, err := c.lockCoWRegistry(ctx)
registry, err := c.lockDeleteRegistry(ctx)
if err != nil {
return err
}
@@ -299,8 +337,10 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
if vm.Directory == "" {
return removeVM()
}
if currentDisk, currentManaged := c.deletionDisk(current); currentDisk != disk || currentManaged != managedPath {
return fmt.Errorf("VM %s changed its disk while waiting to delete it", name)
if c.imagesDir != "" {
if currentDisk, currentManaged := c.deletionDisk(current); currentDisk != disk || currentManaged != managedPath {
return fmt.Errorf("VM %s changed its disk while waiting to delete it", name)
}
}
// The upstream tool only removes a directory containing vm.toml. A
@@ -309,17 +349,73 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
if cfgErr != nil && !errors.Is(cfgErr, os.ErrNotExist) {
return cfgErr
}
overlay := newDiskMatch(managedPath)
vmDir := absoluteDiskPath(vm.Directory)
match := func(path string) bool {
return overlay.matches(path) || (cfgErr == nil &&
(pathInDirectory(vm.Directory, path) || pathInDirectory(vmDir, absoluteDiskPath(path))))
hadConfig := cfgErr == nil
var overlay diskMatch
if c.imagesDir != "" {
overlay = newDiskMatch(managedPath)
vmDir := absoluteDiskPath(vm.Directory)
match := func(path string) bool {
return overlay.matches(path) || (hadConfig &&
(pathInDirectory(vm.Directory, path) || pathInDirectory(vmDir, absoluteDiskPath(path))))
}
if err := c.checkCoWBackingUse(vms, name, match); err != nil {
return err
}
}
if err := c.checkCoWBackingUse(vms, name, match); err != nil {
return err
if hadConfig && c.dirUsedByOtherVM(vms, name, vm.Directory) {
return fmt.Errorf("VM directory %s is used by another registered VM", vm.Directory)
}
if err := removeVM(); err != nil {
return err
removeErr := removeVM()
// Upstream `reims-ctl delete` writes vms.toml before calling remove_dir_all
// without retries (reims-vgpu 2df30ff cli.rs:1049-1060). On Windows, a brief
// sharing violation or NTFS delete-pending state can leave the directory behind
// after unregistration, blocking a subsequent create of the same VM name.
if hadConfig {
_, statErr := os.Stat(vm.Directory)
dirExists := !errors.Is(statErr, os.ErrNotExist)
if removeErr != nil || dirExists {
afterVMs, regErr := readRegisteredVMs(c.registryDir)
unregistered := regErr == nil && findRegisteredVM(afterVMs, name).Directory == ""
if !unregistered {
if removeErr != nil {
return removeErr
}
return nil
}
if dirExists {
if c.dirUsedByOtherVM(afterVMs, name, vm.Directory) {
if removeErr != nil {
return removeErr
}
} else if cleanupErr := removeVMDirWithRetry(ctx, vm.Directory); cleanupErr == nil {
if removeErr != nil && stdout != nil {
_, _ = fmt.Fprintf(stdout, "Removed remaining VM directory %s after retry\n", vm.Directory)
}
// In upstream reims-vgpu 2df30ff cli.rs:1049-1060, remove_dir_all is
// the only step after vms.toml is saved; once the leftover directory
// is cleanly removed, the transient remove_dir_all error is recovered
// unless the caller canceled ctx.
if ctx.Err() == nil {
removeErr = nil
}
} else if removeErr != nil {
removeErr = fmt.Errorf("%w (VM unregistered, failed to remove %s: %v)", removeErr, vm.Directory, cleanupErr)
} else {
removeErr = fmt.Errorf("remove %s: %w", vm.Directory, cleanupErr)
}
}
// If !dirExists && removeErr != nil, preserve removeErr instead of
// masking a failure that happened after the directory was already gone.
if managedPath != "" && !c.hasOtherDiskOwner(afterVMs, name, overlay) {
if err := os.Remove(managedPath); err != nil && !errors.Is(err, os.ErrNotExist) {
removeErr = errors.Join(removeErr, fmt.Errorf("remove clone disk %s: %w", managedPath, err))
}
}
return removeErr
}
} else if removeErr != nil {
return removeErr
}
if managedPath != "" && !c.hasOtherDiskOwner(vms, name, overlay) {
@@ -330,6 +426,88 @@ func (c *Client) deleteWithCoW(ctx context.Context, name string, keepFiles bool,
return nil
}
func (c *Client) dirUsedByOtherVM(vms []driver.VMInfo, excludeName, dir string) bool {
absDir := absoluteDiskPath(dir)
for _, vm := range vms {
if vm.Name == excludeName {
continue
}
if sameDiskPath(vm.Directory, dir) || sameDiskPath(absoluteDiskPath(vm.Directory), absDir) ||
pathInDirectory(dir, vm.Directory) || pathInDirectory(absDir, absoluteDiskPath(vm.Directory)) {
return true
}
var disk string
if c.imagesDir != "" {
disk = c.registeredDisk(vm)
} else if d, err := vmSystemDisk(vm.Directory); err == nil {
disk = d
}
if disk != "" && (pathInDirectory(dir, disk) || pathInDirectory(absDir, absoluteDiskPath(disk))) {
return true
}
}
return false
}
func removeVMDirWithRetry(ctx context.Context, dir string) error {
var lastErr error
for attempt := 0; attempt <= len(deleteDirRetryDelays); attempt++ {
if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
return nil
}
err := os.RemoveAll(dir)
if err == nil {
if _, statErr := os.Stat(dir); errors.Is(statErr, os.ErrNotExist) {
return nil
}
err = fmt.Errorf("directory still present after removal: %s", dir)
} else if errors.Is(err, os.ErrPermission) {
makeTreeWritable(dir)
if retryErr := os.RemoveAll(dir); retryErr == nil {
if _, statErr := os.Stat(dir); errors.Is(statErr, os.ErrNotExist) {
return nil
}
err = fmt.Errorf("directory still present after removal: %s", dir)
} else {
err = retryErr
}
}
lastErr = err
if attempt == len(deleteDirRetryDelays) {
break
}
delay := deleteDirRetryDelays[attempt]
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return errors.Join(lastErr, ctx.Err())
case <-timer.C:
}
}
return lastErr
}
func makeTreeWritable(dir string) {
_ = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.Type()&(os.ModeSymlink|os.ModeIrregular) != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() {
_ = os.Chmod(p, 0o700)
} else {
_ = os.Chmod(p, 0o600)
}
return nil
})
}
func (c *Client) deletionDisk(vm driver.VMInfo) (disk, managedPath string) {
if vm.Directory == "" {
return "", ""
+312 -5
View File
@@ -1,6 +1,7 @@
package reims
import (
"bytes"
"context"
"encoding/binary"
"errors"
@@ -8,12 +9,16 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"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/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestResolveCompactQCOW2Options(t *testing.T) {
@@ -137,7 +142,7 @@ func TestCoWRegisteredChainsAndDeletion(t *testing.T) {
damagedVM := testDiskVM(t, "damaged", filepath.Dir(empty), empty)
writeTestRegistrations(t, c, baseVM, middleVM, linkedVM, damagedVM)
err := c.deleteWithCoW(ctx, middleVM.Name, false, func() error {
err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
t.Fatal("cannot delete a managed image used by another VM")
return nil
})
@@ -151,7 +156,7 @@ func TestCoWRegisteredChainsAndDeletion(t *testing.T) {
assertCoWInUse(t, err, linkedVM.Name)
writeTestRegistrations(t, c, baseVM, middleVM, damagedVM)
if err := c.deleteWithCoW(ctx, middleVM.Name, false, func() error {
if err := c.deleteWithCoW(ctx, middleVM.Name, false, nil, func() error {
writeTestRegistrations(t, c, baseVM, damagedVM)
return nil
}); err != nil {
@@ -181,12 +186,12 @@ func TestCoWBrokenVMDeletionAndKeepFiles(t *testing.T) {
child := testDiskVM(t, "child", filepath.Join(root, "child"), overlay)
writeTestCoWFile(t, overlay, testBackingHeader(disk))
writeTestRegistrations(t, c, broken, child)
assertCoWInUse(t, c.deleteWithCoW(ctx, broken.Name, false, func() error {
assertCoWInUse(t, c.deleteWithCoW(ctx, broken.Name, false, nil, func() error {
t.Fatal("cannot delete the backing disk inside a broken VM directory")
return nil
}), child.Name)
if err := c.deleteWithCoW(ctx, child.Name, true, func() error {
if err := c.deleteWithCoW(ctx, child.Name, true, nil, func() error {
writeTestRegistrations(t, c, broken)
return nil
}); err != nil {
@@ -195,7 +200,7 @@ func TestCoWBrokenVMDeletionAndKeepFiles(t *testing.T) {
if _, err := os.Stat(overlay); err != nil {
t.Fatalf("keep-files removed the clone disk: %v", err)
}
if err := c.deleteWithCoW(ctx, broken.Name, false, func() error { return nil }); err != nil {
if err := c.deleteWithCoW(ctx, broken.Name, false, nil, func() error { return nil }); err != nil {
t.Fatalf("broken VM with no registered dependents should be deletable: %v", err)
}
}
@@ -420,3 +425,305 @@ func TestParseQCOW2CreateOptionsFromInfoJSON(t *testing.T) {
t.Fatal("expected error for raw format")
}
}
func TestDeleteRetriesDirectoryCleanupAfterUnregister(t *testing.T) {
origDelays := deleteDirRetryDelays
deleteDirRetryDelays = []time.Duration{
10 * time.Millisecond,
20 * time.Millisecond,
30 * time.Millisecond,
50 * time.Millisecond,
80 * time.Millisecond,
}
t.Cleanup(func() { deleteDirRetryDelays = origDelays })
t.Run("recovers_transient_lock_and_cleans_overlay", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("macos-tahoe2")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "macos-tahoe2")
vm := testDiskVM(t, "macos-tahoe2", vmDir, overlay)
logPath := filepath.Join(vmDir, "logs", "qemu.log")
writeTestCoWFile(t, logPath, []byte("qemu log"))
writeTestRegistrations(t, c, vm)
// Hold an open handle on Windows so the initial remove_dir_all fails,
// then release it while deleteWithCoW is retrying.
held, err := os.Open(logPath)
if err != nil {
t.Fatal(err)
}
released := make(chan struct{})
go func() {
time.Sleep(25 * time.Millisecond)
_ = held.Close()
close(released)
}()
t.Cleanup(func() { <-released })
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
// Mirror upstream reims-ctl: unregister in vms.toml first, then fail removing dir.
writeTestRegistrations(t, c)
return errors.New("remove dir: sharing violation")
})
if err != nil {
t.Fatalf("expected transient lock recovery, got %v", err)
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
}
if _, err := os.Stat(overlay); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected CoW overlay %s to be removed, stat err=%v", overlay, err)
}
})
t.Run("preserves_dir_when_still_registered", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "running-vm")
disk := filepath.Join(vmDir, "disk.qcow2")
writeTestCoWFile(t, disk, nil)
vm := testDiskVM(t, "running-vm", vmDir, disk)
writeTestRegistrations(t, c, vm)
wantErr := errors.New("running-vm is running: stop it first")
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v", err, wantErr)
}
if _, statErr := os.Stat(filepath.Join(vmDir, "vm.toml")); statErr != nil {
t.Fatalf("still-registered VM directory should remain untouched: %v", statErr)
}
})
t.Run("preserves_dir_when_used_by_other_vm", func(t *testing.T) {
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
parentDir := filepath.Join(root, "vms", "parent")
childDir := filepath.Join(parentDir, "nested-child")
parent := testDiskVM(t, "parent", parentDir, filepath.Join(parentDir, "disk.qcow2"))
child := testDiskVM(t, "child", childDir, filepath.Join(childDir, "disk.qcow2"))
writeTestRegistrations(t, c, parent, child)
err := c.deleteWithCoW(context.Background(), parent.Name, false, nil, func() error {
t.Fatal("upstream delete must not run when another VM uses the directory")
return nil
})
if err == nil || !strings.Contains(err.Error(), "used by another registered VM") {
t.Fatalf("delete = %v, want shared directory error", err)
}
if _, statErr := os.Stat(filepath.Join(childDir, "vm.toml")); statErr != nil {
t.Fatalf("shared directory holding another VM must not be removed: %v", statErr)
}
})
t.Run("cleans_readonly_files_without_images_dir", func(t *testing.T) {
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "ro-vm")
roFile := filepath.Join(vmDir, "readonly.txt")
writeTestCoWFile(t, roFile, []byte("locked-readonly"))
vm := testDiskVM(t, "ro-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
if err := os.Chmod(roFile, 0o444); err != nil {
t.Fatal(err)
}
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
return errors.New("remove dir: permission denied")
})
if err != nil {
t.Fatalf("expected readonly cleanup to succeed, got %v", err)
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be removed, stat err=%v", vmDir, err)
}
})
t.Run("reports_persistent_lock_on_windows", func(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows sharing violation semantics only")
}
root := t.TempDir()
c := &Client{registryDir: filepath.Join(root, "registry")}
vmDir := filepath.Join(root, "vms", "stuck-vm")
logPath := filepath.Join(vmDir, "logs", "qemu.log")
writeTestCoWFile(t, logPath, []byte("still open"))
vm := testDiskVM(t, "stuck-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
held, err := os.Open(logPath)
if err != nil {
t.Fatal(err)
}
defer held.Close()
err = c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
return errors.New("exit status 1")
})
if err == nil || !strings.Contains(err.Error(), vmDir) {
t.Fatalf("expected error naming locked dir %s, got %v", vmDir, err)
}
})
t.Run("preserves_error_when_dir_already_removed", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("gone-vm")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "gone-vm")
vm := testDiskVM(t, "gone-vm", vmDir, overlay)
writeTestRegistrations(t, c, vm)
wantErr := errors.New("reims-ctl exited unexpectedly after removal")
err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
writeTestRegistrations(t, c)
if rmErr := os.RemoveAll(vmDir); rmErr != nil {
t.Fatal(rmErr)
}
return wantErr
})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v (must not mask error when dir was already gone)", err, wantErr)
}
if _, statErr := os.Stat(overlay); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("expected orphaned CoW overlay %s to be cleaned, stat err=%v", overlay, statErr)
}
})
t.Run("locks_registry_and_detects_change_without_images_dir", func(t *testing.T) {
root := t.TempDir()
regDir := filepath.Join(root, "registry")
c := &Client{registryDir: regDir}
vmDir := filepath.Join(root, "vms", "race-vm")
otherDir := filepath.Join(root, "vms", "race-vm-moved")
vm := testDiskVM(t, "race-vm", vmDir, filepath.Join(vmDir, "disk.qcow2"))
moved := testDiskVM(t, "race-vm", otherDir, filepath.Join(otherDir, "disk.qcow2"))
writeTestRegistrations(t, c, vm)
unlock, err := filelock.Acquire(context.Background(), filepath.Join(regDir, ".reims-go-delete.lock"), 0)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
done <- c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return errors.New("removeVM must not run after concurrent directory change")
})
}()
time.Sleep(40 * time.Millisecond)
writeTestRegistrations(t, c, moved)
unlock()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "changed while waiting to delete it") {
t.Fatalf("err = %v, want concurrent change error", err)
}
case <-time.After(3 * time.Second):
t.Fatal("deleteWithCoW timed out waiting for registry lock")
}
})
t.Run("preserves_overlay_when_still_registered_after_nil_remove", func(t *testing.T) {
root := t.TempDir()
c := &Client{imagesDir: filepath.Join(root, "images"), registryDir: filepath.Join(root, "registry")}
base := filepath.Join(root, "base", "disk.qcow2")
overlay := c.CoWImagePath("still-there")
writeTestCoWFile(t, base, nil)
writeTestCoWFile(t, overlay, testBackingHeader(base))
vmDir := filepath.Join(root, "vms", "still-there")
vm := testDiskVM(t, "still-there", vmDir, overlay)
writeTestRegistrations(t, c, vm)
if err := c.deleteWithCoW(context.Background(), vm.Name, false, nil, func() error {
return nil
}); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, statErr := os.Stat(vmDir); statErr != nil {
t.Fatalf("still-registered VM directory must not be deleted: %v", statErr)
}
if _, statErr := os.Stat(overlay); statErr != nil {
t.Fatalf("overlay for still-registered VM must not be deleted: %v", statErr)
}
})
}
func TestDeleteRealReimsCtlTransientLockAndKeepFiles(t *testing.T) {
ctlPath := os.Getenv("REIMS_GO_TEST_CTL")
if ctlPath == "" {
t.Skip("set REIMS_GO_TEST_CTL to test Client.Delete against a real reims-ctl binary")
}
rtDir := filepath.Dir(filepath.Dir(ctlPath))
dataRoot := t.TempDir()
cfg := &config.Config{DataRoot: dataRoot, Locale: i18n.EnUS}
if err := cfg.EnsureDirs(); err != nil {
t.Fatal(err)
}
client := NewClient(cfg, rt.Installed{Dir: rtDir})
makeVM := func(name string) string {
t.Helper()
vmDir := filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
writeTestCoWFile(t, filepath.Join(vmDir, "vm.toml"), []byte(fmt.Sprintf(
"name = %q\nprofile = \"q35-x86_64\"\ncpus = 4\nmemory_mib = 4096\ndisk = \"disk.qcow2\"\ndisk_format = \"qcow2\"\n",
name,
)))
writeTestCoWFile(t, filepath.Join(vmDir, "disk.qcow2"), []byte("dummy"))
writeTestCoWFile(t, filepath.Join(vmDir, ".reims-go-arg-ledger.json"), []byte("{}"))
writeTestCoWFile(t, filepath.Join(vmDir, "logs", "qemu.log"), []byte("boot\n"))
writeTestRegistrations(t, client, driver.VMInfo{Name: name, Directory: vmDir})
return vmDir
}
// 1. Real reims-ctl delete hitting a transient Windows sharing violation on the first file.
vmDir := makeVM("macos-tahoe2")
lockedPath := filepath.Join(vmDir, ".reims-go-arg-ledger.json")
held, err := os.Open(lockedPath)
if err != nil {
t.Fatal(err)
}
released := make(chan struct{})
go func() {
time.Sleep(120 * time.Millisecond)
_ = held.Close()
close(released)
}()
t.Cleanup(func() { <-released })
var out, errBuf bytes.Buffer
if err := client.Delete(context.Background(), "macos-tahoe2", false, &out, &errBuf); err != nil {
t.Fatalf("real reims-ctl delete failed to recover transient lock: %v (stdout=%q stderr=%q)", err, out.String(), errBuf.String())
}
if _, err := os.Stat(vmDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected %s to be deleted after retry, stat err=%v", vmDir, err)
}
if issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe2"}, nil, i18n.EnUS); issue != nil {
t.Fatalf("recreating macos-tahoe2 should pass target dir validation after clean delete, got %+v", issue)
}
// 2. Real reims-ctl delete with keepFiles=true leaves the dir, and ValidateCreateTargetDir catches it upfront.
keptDir := makeVM("macos-tahoe-keep")
out.Reset()
errBuf.Reset()
if err := client.Delete(context.Background(), "macos-tahoe-keep", true, &out, &errBuf); err != nil {
t.Fatalf("real reims-ctl delete --keep-files failed: %v (stderr=%q)", err, errBuf.String())
}
if _, err := os.Stat(filepath.Join(keptDir, "vm.toml")); err != nil {
t.Fatalf("keep-files should preserve vm.toml: %v", err)
}
issue := ValidateCreateTargetDir(cfg.XDGDataDir(), CreateOpts{Name: "macos-tahoe-keep"}, nil, i18n.ZhCN)
if issue == nil || issue.Field != "dir" || issue.Code != "dir_not_empty" {
t.Fatalf("expected dir_not_empty after keep-files delete, got %+v", issue)
}
}
+12 -2
View File
@@ -33,6 +33,7 @@ type Client struct {
registryDir string
probeGPUs func() []host.GPUInfo
statFile func(string) (os.FileInfo, error)
checkLaunch func(context.Context, io.Writer) error
}
func NewClient(cfg *config.Config, installed rt.Installed) *Client {
@@ -43,6 +44,10 @@ func NewClient(cfg *config.Config, installed rt.Installed) *Client {
if cfg != nil {
c.Locale = cfg.Locale
if cfg.DataRoot != "" {
selection := *cfg
c.checkLaunch = func(ctx context.Context, warnings io.Writer) error {
return rt.CheckLaunchASLR(ctx, selection, installed.QemuPath(), warnings)
}
c.imagesDir = cfg.ImagesDir()
c.registryDir = filepath.Join(cfg.XDGConfigDir(), "reims-ctl")
for _, entry := range c.Env {
@@ -832,6 +837,11 @@ func (c *Client) Start(ctx context.Context, name string, stdout, stderr io.Write
return err
}
defer release()
if c.checkLaunch != nil {
if err := c.checkLaunch(ctx, stderr); err != nil {
return err
}
}
return c.run(ctx, stdout, stderr, "start", name)
}
@@ -884,10 +894,10 @@ func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout
removeVM := func() error {
return c.run(ctx, stdout, stderr, BuildDeleteArgs(name, keepFiles)...)
}
if c.imagesDir == "" {
if c.imagesDir == "" && c.registryDir == "" {
return removeVM()
}
return c.deleteWithCoW(ctx, name, keepFiles, removeVM)
return c.deleteWithCoW(ctx, name, keepFiles, stdout, removeVM)
}
// IsRunning reports whether the VM runs, either in d or in a fresh list.
+1 -1
View File
@@ -73,7 +73,7 @@ type HostCallbacks struct {
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
return "0.2.12"
return "0.2.13"
}
return v
}
+105
View File
@@ -0,0 +1,105 @@
package runtime
import (
"context"
"errors"
"fmt"
"io"
"runtime"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
// CheckLaunchASLR repairs the selected runtime's rule after a data folder
// move and avoids reactivating a version superseded during launch prep.
func CheckLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, warnings io.Writer) error {
if runtime.GOOS != "windows" {
return ctx.Err()
}
return checkLaunchASLR(ctx, cfg, qemuPath, warnings, host.ApplyQEMUASLR)
}
func checkLaunchASLR(ctx context.Context, cfg config.Config, qemuPath string, warnings io.Writer, apply func(string, string) error) error {
warn := func(err error) error {
if warnings != nil {
fmt.Fprintln(warnings, i18n.T(i18n.EffectiveLocale(cfg.Locale), "runtime.qemu_aslr.warning"), err)
}
return ctx.Err()
}
if err := ctx.Err(); err != nil {
return err
}
if err := RefreshSelection(&cfg); err != nil {
// The client already holds a runtime. Launch it without changing a
// registry rule whose current owner we could not verify.
return warn(err)
}
if !cfg.QEMUASLR {
return ctx.Err()
}
release, lockErr := lockLaunchPolicy(ctx, cfg.RuntimesDir())
if lockErr != nil {
if ctx.Err() != nil {
return ctx.Err()
}
if !errors.Is(lockErr, context.DeadlineExceeded) {
return lockErr
}
// Without the lock, only an explicit selection read from disk can
// establish that the client's runtime has been superseded.
cfg.ActiveRuntime = ""
} else {
defer release()
}
if err := RefreshSelection(&cfg); err != nil {
return warn(err)
}
if !cfg.QEMUASLR {
return ctx.Err()
}
active, err := ResolveActive(&cfg)
if lockErr != nil && (err != nil || !active.Active) {
return warn(lockErr)
}
if err != nil && !errors.Is(err, ErrNoActiveRuntime) {
return err
}
if active == nil || !samePath(active.QemuPath(), qemuPath) {
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
}
if lockErr != nil {
return warn(lockErr)
}
if err := ctx.Err(); err != nil {
return err
}
// Opening the VM must not prompt for elevation. Explicitly applying the
// preference or activating a runtime remains the authorized repair path.
if err := apply(cfg.RuntimesDir(), active.QemuPath()); err != nil {
return warn(QEMUASLRPolicyError(&cfg, err))
}
return ctx.Err()
}
func lockLaunchPolicy(ctx context.Context, root string) (func(), error) {
// Repair is optional. A pending consent dialog can keep the selection
// busy indefinitely, and an install can briefly hold the directory lock.
ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond)
defer cancel()
releaseSelection, err := LockSelection(ctx, root)
if err != nil {
return nil, err
}
releaseDir, err := lockRuntimeDirectoriesContext(ctx, root)
if err != nil {
releaseSelection()
return nil, err
}
return func() {
releaseDir()
releaseSelection()
}, nil
}
+95
View File
@@ -0,0 +1,95 @@
package runtime
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestLaunchPolicyUnreadableSelection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current"}
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
for _, enabled := range []bool{false, true} {
cfg.QEMUASLR = enabled
var warning bytes.Buffer
err := checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error {
t.Fatal("policy applied without a confirmed selection")
return nil
})
if err != nil || warning.Len() == 0 {
t.Fatalf("ASLR enabled=%t: launch error %v, warning %q", enabled, err, &warning)
}
}
}
func TestLaunchPolicyBusy(t *testing.T) {
for _, tc := range []struct {
name string
lock func(context.Context, string) (func(), error)
}{
{"pending selection", LockSelection},
{"runtime directory in use", lockRuntimeDirectoriesContext},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)}
writeFakeRuntime(t, current.Dir, Manifest{Commit: cfg.ActiveRuntime})
release, err := tc.lock(t.Context(), cfg.RuntimesDir())
if err != nil {
t.Fatal(err)
}
defer release()
var warning bytes.Buffer
err = checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error {
t.Fatal("policy applied while its lock was in use")
return nil
})
if err != nil || warning.Len() == 0 {
t.Fatalf("busy policy: launch error %v, warning %q", err, &warning)
}
})
}
}
func TestLaunchPolicyReturnsCallerCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
err := checkLaunchASLR(ctx, config.Config{}, "", nil, nil)
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled launch returned %v", err)
}
}
func TestBusyLaunchPolicyRejectsSupersededRuntime(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
writeFakeRuntime(t, old.Dir, Manifest{Commit: "old"})
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "new"), Manifest{Commit: "new"})
published := cfg
published.ActiveRuntime = "new"
if err := config.Save("", &published); err != nil {
t.Fatal(err)
}
release, err := LockSelection(t.Context(), cfg.RuntimesDir())
if err != nil {
t.Fatal(err)
}
defer release()
err = checkLaunchASLR(t.Context(), cfg, old.QemuPath(), nil, func(_, _ string) error {
t.Fatal("policy applied to a superseded runtime")
return nil
})
var coded *i18n.CodedError
if !errors.As(err, &coded) || coded.Code != "E_RUNTIME_CHANGED" {
t.Fatalf("superseded launch while policy busy: %v", err)
}
}
+55
View File
@@ -72,6 +72,61 @@ func TestRemoveRuntime(t *testing.T) {
}
}
func TestRemoveAfterExternalActivation(t *testing.T) {
for _, selected := range []string{"next", DefaultKind + "/next", "other/next"} {
t.Run(selected, func(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old"}
oldDir := filepath.Join(cfg.RuntimesDir(), "old")
nextDir := filepath.Join(cfg.RuntimesDir(), "next")
writeFakeRuntime(t, oldDir, Manifest{Commit: "old"})
if selected == "other/next" {
nextDir = filepath.Join(cfg.RuntimesDir(), "other", "next")
// Keep the default kind's implicit single-runtime fallback out of this case.
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "spare"), Manifest{Commit: "spare"})
}
writeFakeRuntime(t, nextDir, Manifest{Commit: "next"})
cli := cfg
if err := Activate(t.Context(), &cli, selected, nil); err != nil {
t.Fatal(err)
}
list, err := List(&cli)
if err != nil {
t.Fatal(err)
}
for _, item := range list {
if item.Active != (item.Dir == nextDir) {
t.Fatalf("runtime %s active = %t after selecting %s", item.Dir, item.Active, selected)
}
}
if _, err := Remove(&cfg, selected); !errors.Is(err, ErrRemoveActive) {
t.Fatalf("removing the newly active runtime returned %v", err)
}
if _, err := os.Stat(nextDir); err != nil {
t.Fatal(err)
}
if _, err := Remove(&cfg, "old"); err != nil {
t.Fatalf("removing the formerly selected runtime: %v", err)
}
})
}
}
func TestRemoveWithUnreadableSelection(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old"}
nextDir := filepath.Join(cfg.RuntimesDir(), "next")
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "old"), Manifest{Commit: "old"})
writeFakeRuntime(t, nextDir, Manifest{Commit: "next"})
if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Remove(&cfg, "next"); err == nil {
t.Fatal("removed a runtime without a readable selection")
}
if _, err := os.Stat(nextDir); err != nil {
t.Fatal(err)
}
}
func TestRemoveRuntimeInUseWindows(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows file locking semantics only")
+21 -4
View File
@@ -167,7 +167,7 @@ func List(cfg *config.Config) ([]Installed, error) {
Kind: kind,
Commit: commit,
Dir: dir,
Active: specForKind(kind).Builtin && commit == cfg.ActiveRuntime,
Active: (specForKind(kind).Builtin && commit == cfg.ActiveRuntime) || kind+"/"+commit == cfg.ActiveRuntime,
Manifest: m,
Spec: specForKind(kind),
})
@@ -240,7 +240,13 @@ func Remove(cfg *config.Config, commit string) (*Installed, error) {
return nil, err
}
defer release()
list, err := List(cfg)
// Activation takes the same directory lock. Include any selection published
// while this process waited, and leave both runtimes intact upon read errors.
current := *cfg
if err := RefreshSelection(&current); err != nil {
return nil, err
}
list, err := List(&current)
if err != nil {
return nil, err
}
@@ -260,7 +266,11 @@ func Remove(cfg *config.Config, commit string) (*Installed, error) {
if match.Active {
return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit)
}
if active, err := ResolveActive(cfg); err == nil && active != nil && samePath(active.Dir, match.Dir) {
active, err := ResolveActive(&current)
if err != nil && !errors.Is(err, ErrNoActiveRuntime) {
return nil, err
}
if active != nil && samePath(active.Dir, match.Dir) {
return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit)
}
baseAbs, err := filepath.Abs(cfg.RuntimesDir())
@@ -444,7 +454,14 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err
}
func lockRuntimeDirectories(runtimesDir string) (func(), error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
return lockRuntimeDirectoriesContext(context.Background(), runtimesDir)
}
func lockRuntimeDirectoriesContext(ctx context.Context, runtimesDir string) (func(), error) {
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-runtime.lock"), 0)
}
+207
View File
@@ -0,0 +1,207 @@
package runtime
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/filelock"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
func Activate(ctx context.Context, cfg *config.Config, commit string, warn func(error)) error {
return saveSelection(ctx, cfg, commit, nil, host.SyncQEMUASLR, warn)
}
func SetQEMUASLR(ctx context.Context, cfg *config.Config, enabled bool) error {
return saveSelection(ctx, cfg, "", &enabled, host.SyncQEMUASLR, nil)
}
// LockSelection serializes changes to the published selection and its host
// policy across processes. Downloads and preference saves use the directory
// lock separately, so they can finish while Windows waits for consent.
func LockSelection(ctx context.Context, runtimesDir string) (func(), error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-selection.lock"), 0)
}
// RefreshSelection reads the last atomically published selection, without
// waiting for a concurrent install or a pending Windows consent prompt.
func RefreshSelection(cfg *config.Config) error {
saved, err := loadSelection(cfg)
if err != nil {
return err
}
cfg.ActiveRuntime, cfg.QEMUASLR = saved.ActiveRuntime, saved.QEMUASLR
return nil
}
// SavePreferences keeps an unrelated GUI edit from overwriting a CLI switch.
func SavePreferences(cfg *config.Config) error {
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return err
}
defer release()
if err := RefreshSelection(cfg); err != nil {
return err
}
return config.Save("", cfg)
}
func QEMUASLRPath(cfg *config.Config) (string, error) {
if !cfg.QEMUASLR {
return "", nil
}
active, err := ResolveActive(cfg)
if errors.Is(err, ErrNoActiveRuntime) {
return "", nil // The first runtime install will apply the preference.
}
if err != nil {
return "", err
}
return active.QemuPath(), nil
}
func loadSelection(cfg *config.Config) (config.Config, error) {
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
if errors.Is(err, os.ErrNotExist) {
return *cfg, nil
}
if err != nil {
return config.Config{}, err
}
saved.DataRoot = cfg.DataRoot
return *saved, nil
}
func requestedSelection(next config.Config, commit string, aslr *bool) (config.Config, error) {
if aslr != nil {
next.QEMUASLR = *aslr
} else {
installed, err := List(&next)
if err != nil {
return next, err
}
if !slices.ContainsFunc(installed, func(r Installed) bool {
return r.Commit == commit || r.Kind+"/"+r.Commit == commit
}) {
return next, fmt.Errorf("%w: %s", ErrNotFound, commit)
}
next.ActiveRuntime = commit
}
return next, nil
}
func QEMUASLRPolicyError(cfg *config.Config, err error) error {
loc := i18n.EffectiveLocale(cfg.Locale)
switch {
case errors.Is(err, host.ErrQEMUASLRImagePolicy):
return i18n.NewCodedError(loc, "E_QEMU_ASLR_IMAGE_POLICY", "err.qemu_aslr.image_policy", nil, err)
case errors.Is(err, host.ErrElevationDeclined):
return i18n.NewCodedError(loc, "E_QEMU_ASLR_CANCELLED", "err.qemu_aslr.cancelled", nil, err)
default:
return err
}
}
func saveSelection(ctx context.Context, cfg *config.Config, commit string, aslr *bool, syncPolicy func(context.Context, string, string) error, warn func(error)) error {
root := cfg.RuntimesDir()
unlock, err := LockSelection(ctx, root)
if err != nil {
return err
}
defer unlock()
prev, err := loadSelection(cfg)
if err != nil {
return err
}
next, err := requestedSelection(prev, commit, aslr)
if err != nil {
return err
}
managePolicy := aslr != nil || next.QEMUASLR
var warning error
var target string
if managePolicy {
target, err = QEMUASLRPath(&next)
if err != nil {
return err
}
err = syncPolicy(ctx, root, target)
switch {
case errors.Is(err, host.ErrQEMUASLRImagePolicy) && aslr == nil:
// An existing image-wide policy takes precedence. This conflict is
// detected before writing any rules.
warning = QEMUASLRPolicyError(&next, err)
case errors.Is(err, host.ErrQEMUASLRImagePolicy), errors.Is(err, host.ErrElevationDeclined), errors.Is(err, context.Canceled):
return QEMUASLRPolicyError(&next, err)
case err != nil:
return restoreSelectionPolicy(ctx, &prev, syncPolicy, err)
}
}
// UAC may have been pending while preferences were saved or the candidate
// was deleted. Re-read and validate under the same lock used by both.
err = func() error {
release, err := lockRuntimeDirectoriesContext(ctx, root)
if err != nil {
return err
}
defer release()
current, err := loadSelection(cfg)
if err != nil {
return err
}
if current.ActiveRuntime != prev.ActiveRuntime || current.QEMUASLR != prev.QEMUASLR {
prev = current
return i18n.NewCodedError(i18n.EffectiveLocale(current.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
}
next, err = requestedSelection(current, commit, aslr)
if err != nil {
return err
}
if next.QEMUASLR {
latestPath, err := QEMUASLRPath(&next)
if err != nil {
return err
}
if !samePath(latestPath, target) {
return i18n.NewCodedError(i18n.EffectiveLocale(current.Locale), "E_RUNTIME_CHANGED", "err.runtime_changed", nil, nil)
}
}
return config.Save("", &next)
}()
if err != nil {
if managePolicy && warning == nil {
return restoreSelectionPolicy(ctx, &prev, syncPolicy, err)
}
return err
}
cfg.ActiveRuntime, cfg.QEMUASLR = next.ActiveRuntime, next.QEMUASLR
if warning != nil && warn != nil {
warn(warning)
}
return nil
}
func restoreSelectionPolicy(ctx context.Context, prev *config.Config, syncPolicy func(context.Context, string, string) error, cause error) error {
target, err := QEMUASLRPath(prev)
if err == nil {
err = syncPolicy(context.WithoutCancel(ctx), prev.RuntimesDir(), target)
}
return errors.Join(cause, QEMUASLRPolicyError(prev, err))
}
+192
View File
@@ -0,0 +1,192 @@
package runtime
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"runtime"
"slices"
"testing"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestSelectionFollowsRuntimeAndToggle(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir()}
var targets []string
sync := func(_ context.Context, root, path string) error {
if root != cfg.RuntimesDir() {
t.Fatalf("unexpected runtimes root %q", root)
}
targets = append(targets, path)
return nil
}
selectRuntime := func(client *config.Config, commit string, toggle *bool) {
t.Helper()
if err := saveSelection(context.Background(), client, commit, toggle, sync, nil); err != nil {
t.Fatal(err)
}
}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
backup := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "backup")}
writeFakeRuntime(t, current.Dir, Manifest{Commit: "current"})
writeFakeRuntime(t, backup.Dir, Manifest{Commit: "backup"})
on, off := true, false
selectRuntime(cfg, "current", nil) // An older config has ASLR off.
stale := *cfg
selectRuntime(cfg, "", &on)
selectRuntime(&stale, "backup", nil) // CLI picks up the desktop preference.
selectRuntime(cfg, "current", nil)
selectRuntime(cfg, "", &off)
selectRuntime(&stale, "backup", nil)
want := []string{current.QemuPath(), backup.QemuPath(), current.QemuPath(), ""}
if !slices.Equal(targets, want) {
t.Fatalf("synced paths = %q, want %q", targets, want)
}
saved, err := config.Load(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || saved.QEMUASLR || saved.ActiveRuntime != "backup" {
t.Fatalf("saved selection = %+v, %v", saved, err)
}
}
func TestSelectionFailureKeepsPreviousRuntime(t *testing.T) {
cfg := &config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
for _, commit := range []string{"old", "new"} {
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), commit), Manifest{Commit: commit})
}
if err := config.Save("", cfg); err != nil {
t.Fatal(err)
}
calls := 0
err := saveSelection(context.Background(), cfg, "new", nil, func(context.Context, string, string) error {
calls++
return host.ErrElevationDeclined
}, nil)
if !errors.Is(err, host.ErrElevationDeclined) || calls != 1 {
t.Fatalf("declined activation: calls = %d, error = %v", calls, err)
}
// Block the commit lock so the successful host update must be rolled back.
if err := os.Mkdir(filepath.Join(cfg.RuntimesDir(), ".reims-go-runtime.lock"), 0o755); err != nil {
t.Fatal(err)
}
var applied []string
err = saveSelection(context.Background(), cfg, "new", nil, func(_ context.Context, _, path string) error {
applied = append(applied, path)
return nil
}, nil)
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
next := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "new")}
if err == nil || !slices.Equal(applied, []string{next.QemuPath(), old.QemuPath()}) {
t.Fatalf("rollback paths = %v, error = %v", applied, err)
}
saved, err := config.Load(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || cfg.ActiveRuntime != "old" || saved.ActiveRuntime != "old" || !saved.QEMUASLR {
t.Fatalf("failed selection was committed: %+v, %v", saved, err)
}
}
func TestSelectionRevalidatesAfterConsent(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true}
for _, id := range []string{"old", "new"} {
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), id), Manifest{Commit: id})
}
if err := config.Save("", &cfg); err != nil {
t.Fatal(err)
}
var paths []string
err := saveSelection(t.Context(), &cfg, "new", nil, func(_ context.Context, _, path string) error {
paths = append(paths, path)
if len(paths) == 1 {
prefs := cfg
prefs.SyncHostMemorySMBIOS = true
if err := SavePreferences(&prefs); err != nil {
t.Fatal(err)
}
_, err := Remove(&prefs, "new")
return err
}
return nil
}, nil)
old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")}
if !errors.Is(err, ErrNotFound) || len(paths) != 2 || paths[1] != old.QemuPath() {
t.Fatalf("removed during consent: paths = %q, err = %v", paths, err)
}
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || saved.ActiveRuntime != "old" || !saved.SyncHostMemorySMBIOS {
t.Fatalf("lost settings while awaiting consent: %+v, %v", saved, err)
}
}
func TestActivationWarnsOnImagePolicyConflict(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), QEMUASLR: true}
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "new"), Manifest{Commit: "new"})
conflict := func(context.Context, string, string) error { return host.ErrQEMUASLRImagePolicy }
var warning error
if err := saveSelection(t.Context(), &cfg, "new", nil, conflict, func(err error) { warning = err }); err != nil {
t.Fatal(err)
}
var coded *i18n.CodedError
if !errors.As(warning, &coded) || coded.Code != "E_QEMU_ASLR_IMAGE_POLICY" {
t.Fatalf("activation warning = %v", warning)
}
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || saved.ActiveRuntime != "new" || !saved.QEMUASLR {
t.Fatalf("conflicted activation = %+v, %v", saved, err)
}
on := true
err = saveSelection(t.Context(), &cfg, "", &on, conflict, nil)
if !errors.As(err, &coded) || coded.Code != "E_QEMU_ASLR_IMAGE_POLICY" {
t.Fatalf("explicit repair error = %v", err)
}
}
func TestLaunchPolicyRejectsSupersededRuntime(t *testing.T) {
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "backup", QEMUASLR: true}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
writeFakeRuntime(t, current.Dir, Manifest{Commit: "current"})
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "backup"), Manifest{Commit: "backup"})
if err := config.Save("", &cfg); err != nil {
t.Fatal(err)
}
stale := cfg
stale.ActiveRuntime, stale.QEMUASLR = "current", false
called := false
denied := errors.New("access denied")
apply := func(_, _ string) error { called = true; return denied }
if err := checkLaunchASLR(t.Context(), stale, current.QemuPath(), nil, apply); err == nil || called {
t.Fatal("launch would reapply policy to the superseded runtime")
}
backup := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "backup")}
var warning bytes.Buffer
if err := checkLaunchASLR(t.Context(), stale, backup.QemuPath(), &warning, apply); err != nil || !called || !bytes.Contains(warning.Bytes(), []byte(denied.Error())) {
t.Fatalf("launch should continue with a policy warning: %v, %q", err, warning.String())
}
}
func TestNonWindowsIgnoresSavedQEMUASLR(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("non-Windows host")
}
cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true}
for _, commit := range []string{"current", "backup"} {
writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), commit), Manifest{Commit: commit})
}
if err := config.Save("", &cfg); err != nil {
t.Fatal(err)
}
if err := Activate(t.Context(), &cfg, "backup", nil); err != nil {
t.Fatal(err)
}
current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "current")}
if err := CheckLaunchASLR(t.Context(), cfg, current.QemuPath(), nil); err != nil {
t.Fatalf("Windows policy blocked launch on %s: %v", runtime.GOOS, err)
}
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
if err != nil || !saved.QEMUASLR || saved.ActiveRuntime != "backup" {
t.Fatalf("lost runtime selection or portable preference: %+v, %v", saved, err)
}
}
+2 -2
View File
@@ -16,8 +16,8 @@ import (
// Version is the current Reims-Go release version. Release builds may override
// it at link time with:
//
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.12"
var Version = "v0.2.12"
// -ldflags "-X github.com/Nwflower/reims-go/internal/version.Version=v0.2.13"
var Version = "v0.2.13"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
+1
View File
@@ -149,6 +149,7 @@
"taskRuntime": "Installing runtime {v}",
"toastRuntimeReady": "Runtime {v} installed",
"failRuntime": "Runtime install failed",
"runtimeActivationFailed": "Runtime activation failed",
"toastSaved": "Saved",
"toastSavedNextStart": "Saved — applies on next start",
"toastCopied": "Copied",
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more