From afd8ff9371830413b7a44f4457ab91b3a0ef21c2 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Fri, 30 Oct 2026 22:44:51 +0100 Subject: [PATCH 01/13] =?UTF-8?q?CI=EF=BC=9A=E6=94=B9=E4=B8=BA=20PR=20?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E5=B9=B6=E5=8A=A0=E5=85=A5=E9=9A=90=E7=A7=81?= =?UTF-8?q?=E4=B8=8E=E4=BD=9C=E8=80=85=E6=89=AB=E6=8F=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ci.yml | 56 +++++++++++++ .github/workflows/test.yml | 27 ------- README.md | 2 +- scripts/privacy-allowlist.json | 3 + scripts/privacy.py | 141 +++++++++++++++++++++++++++++++++ scripts/repo_checks.py | 61 ++++++++++++++ scripts/test_repo_checks.py | 44 ++++++++++ 7 files changed, 306 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/test.yml create mode 100644 scripts/privacy-allowlist.json create mode 100644 scripts/privacy.py create mode 100644 scripts/repo_checks.py create mode 100644 scripts/test_repo_checks.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..96c5a872 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: ci + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +env: + GOTOOLCHAIN: local + +jobs: + checks: + runs-on: windows-2025 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: false + - name: gofmt + shell: pwsh + run: | + $bad = gofmt -l . + if ($bad) { $bad; throw 'gofmt required' } + - name: go vet + run: go vet ./... + - name: go test + run: go test ./... + - name: build + shell: pwsh + run: | + pwsh -NoProfile -File build.ps1 + Get-FileHash out\tools\modavd.exe -Algorithm SHA256 + Get-FileHash out\ModAVD.exe -Algorithm SHA256 + - name: privacy scan + run: python -B -I -X utf8 scripts/privacy.py . --allowlist scripts/privacy-allowlist.json + - name: author check + shell: pwsh + env: + REPO_CHECK_BASE: ${{ github.event.pull_request.base.sha }} + REPO_CHECK_HEAD: ${{ github.event.pull_request.head.sha }} + REPO_CHECK_EVENT: ${{ github.event_name }} + run: | + if ($env:REPO_CHECK_EVENT -eq 'workflow_dispatch') { + Remove-Item Env:REPO_CHECK_BASE -ErrorAction SilentlyContinue + Remove-Item Env:REPO_CHECK_HEAD -ErrorAction SilentlyContinue + } + python -B -I -X utf8 scripts/repo_checks.py + - name: script tests + run: python -B -I -X utf8 -m unittest scripts/test_repo_checks.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index db656b99..00000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: test - -on: - push: - pull_request: - -permissions: - contents: read - -jobs: - test: - runs-on: windows-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 - with: - go-version-file: go.mod - # standard library only: nothing to cache - cache: false - - name: go vet - run: go vet ./... - - name: go test - run: go test ./... - - name: build - run: pwsh -NoProfile -File build.ps1 diff --git a/README.md b/README.md index 5bfdcbbc..d0b072e7 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ go test ./... - `internal/avd`、`internal/root`、`internal/jsonord` 有一部分测试用 Python 3 运行 AUTO-MAS 的原始逻辑(如 `internal/avd/testdata/instances_ref.py`),和 Go 的输出逐字节对照,所以要装 Python 3。 - 有几项测试只读本机 `D:\ModAVD` 下的现成文件(`mas-avd.json`、实例配置、组件 APK),没有就跳过;`MODAVD_TEST_METADATA` 可以另指一份 `mas-avd.json`。 -- CI(`.github/workflows/test.yml`)在 `windows-latest` 上跑 `go vet`、`go test` 和 `build.ps1`。 +- CI(`.github/workflows/ci.yml`)在 `windows-2025` 上跑格式检查、`go vet`、`go test`、`build.ps1`、隐私扫描和作者检查;只在 PR 或手动触发时运行。 ## 参与 diff --git a/scripts/privacy-allowlist.json b/scripts/privacy-allowlist.json new file mode 100644 index 00000000..b5aac17f --- /dev/null +++ b/scripts/privacy-allowlist.json @@ -0,0 +1,3 @@ +{ + "exceptions": [] +} diff --git a/scripts/privacy.py b/scripts/privacy.py new file mode 100644 index 00000000..d6441adb --- /dev/null +++ b/scripts/privacy.py @@ -0,0 +1,141 @@ +"""Fail-closed privacy scanner shared by release packaging and public CI. + +Exceptions pin a complete printable string and either the file SHA-256 or the +exact upstream file path. New strings still fail; no surname-wide exemption. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tarfile + +# Only generic rules live in this file, because it is copied into the public +# repository. Rules that name private identifiers (real name, private email, +# hostname, local directories) sit in privacy-private-rules.json next to it, +# which stays in the maintainer repository: public CI runs without them, and +# the release entry point refuses to scan unless they were loaded. +PUBLIC_RULES = { + # name: (pattern, UTF-16 prefilter prefixes) + "user-path": (r"[a-z]:[\\/]+Users[\\/]+[^\\/\s\"'<>|]+", ["Users"]), +} +PRIVATE_RULES_FILE = Path(__file__).with_name("privacy-private-rules.json") + + +def load_rule_specs(private_file=PRIVATE_RULES_FILE): + specs = dict(PUBLIC_RULES) + loaded = private_file.exists() + if loaded: + for name, spec in json.loads(private_file.read_text(encoding="utf-8"))["rules"].items(): + specs[name] = (spec["pattern"], spec["prefixes"]) + return specs, loaded + + +RULE_SPECS, PRIVATE_RULES_LOADED = load_rule_specs() +RULES = {name: re.compile(pattern, re.I) for name, (pattern, _) in RULE_SPECS.items()} +ANY_RULE = re.compile("|".join(rx.pattern for rx in RULES.values()), re.I) +ASCII_CANDIDATE = re.compile(ANY_RULE.pattern.encode("ascii"), re.I) +# UTF-16 prefix prefilter; full matching still uses RULES on decoded printable strings. +PREFIXES = [prefix for _, prefixes in RULE_SPECS.values() for prefix in prefixes] +U16_CANDIDATE = re.compile(b"|".join(re.escape(s.encode("utf-16le")) for s in PREFIXES), re.I) +NEEDLES = [s.lower().encode(e) for s in PREFIXES for e in ["ascii", "utf-16le"]] + + +def strings(data): + # Find candidate strings directly, without allocating every string in large executables. + for rx, encoding, width in [(ASCII_CANDIDATE, "ascii", 1), (U16_CANDIDATE, "utf-16le", 2)]: + seen = set() + for match in rx.finditer(data): + lo, hi = match.span() + if width == 1: + while lo > 0 and 32 <= data[lo-1] <= 126: + lo -= 1 + while hi < len(data) and 32 <= data[hi] <= 126: + hi += 1 + else: + while lo >= 2 and data[lo-1] == 0 and 32 <= data[lo-2] <= 126: + lo -= 2 + while hi+1 < len(data) and data[hi+1] == 0 and 32 <= data[hi] <= 126: + hi += 2 + if (lo, hi) not in seen: + seen.add((lo, hi)) + yield data[lo:hi].decode(encoding) + try: + text = data.decode("utf-8-sig") + except UnicodeDecodeError: + return + for line in text.splitlines(): + if any(ord(c) > 127 for c in line): + yield line + + +def scan_files(files, allowlist): + rules = json.loads(Path(allowlist).read_text(encoding="utf-8")) + allowed_keys = {(e["file_sha256"], e["rule"], e["string_sha256"]) for e in rules["exceptions"] if "file_sha256" in e} + allowed_paths = {(e["path"], e["rule"], e["string_sha256"]) for e in rules["exceptions"] if "path" in e} + report = {"files_scanned": 0, "failures": [], "allowed": []} + def blob(name, data): + report["files_scanned"] += 1 + lower = data.lower() + if not any(needle in lower for needle in NEEDLES): + return + file_sha = None + logical_path = name.split("!", 1)[-1] + if logical_path.startswith("ModAVD-") and "/" in logical_path: + logical_path = logical_path.split("/", 1)[1] + seen = set() + for string in strings(data): + if not ANY_RULE.search(string): + continue + for rule, rx in RULES.items(): + if not rx.search(string): + continue + digest = hashlib.sha256(string.encode("utf-8")).hexdigest() + if (rule, digest) in seen: + continue + seen.add((rule, digest)) + if file_sha is None: + file_sha = hashlib.sha256(data).hexdigest() + entry = {"file": name, "path": logical_path, "rule": rule, "file_sha256": file_sha, "string_sha256": digest} + if (file_sha, rule, digest) in allowed_keys or (logical_path, rule, digest) in allowed_paths: + report["allowed"].append(entry) + else: + matches = list(rx.finditer(string)) + entry["sample"] = " | ".join(string[max(0, m.start()-80):m.end()+120] for m in matches) + report["failures"].append(entry) + for path, name in files: + path = Path(path) + if name.endswith((".tar.xz", ".tar.gz")): + print(f"Scanning source members: {name}", flush=True) + with tarfile.open(path, "r|*") as archive: + for member in archive: + if member.isfile(): + blob(name + "!" + member.name, archive.extractfile(member).read()) + else: + blob(name, path.read_bytes()) + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("--allowlist", type=Path, default=Path(__file__).with_name("privacy-allowlist.json")) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + # CI scans tracked repository files, never .git internals or arbitrary local artifacts. + names = subprocess.check_output(["git", "-C", str(args.root), "ls-files", "-z"]).decode("utf-8").split("\0") + files = [(args.root / name, name) for name in names if name] + report = scan_files(files, args.allowlist) + if args.report: + args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(f"Privacy: {report['files_scanned']} files; {len(report['allowed'])} allowed; {len(report['failures'])} failures") + for item in report["failures"][:20]: + print(f" {item['file']}: {item['rule']}: {item['sample'][:120]}") + return bool(report["failures"]) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/repo_checks.py b/scripts/repo_checks.py new file mode 100644 index 00000000..33e9a7bc --- /dev/null +++ b/scripts/repo_checks.py @@ -0,0 +1,61 @@ +"""Validate commit authors and Co-authored-by trailers for public history.""" +from __future__ import annotations + +import os +import re +import subprocess +import sys + +ALLOWED_AUTHOR = re.compile(r"^qiyinxi $") +ALLOWED_NOREPLY = ( + re.compile(r"^[0-9]+\+[A-Za-z0-9-]+(?:\[bot\])?@users\.noreply\.github\.com$"), + re.compile(r"^[A-Za-z0-9-]+@users\.noreply\.github\.com$"), +) + + +def allowed(name: str, email: str) -> bool: + identity = f"{name} <{email}>" + return bool(ALLOWED_AUTHOR.fullmatch(identity) or any(rx.fullmatch(email) for rx in ALLOWED_NOREPLY)) + + +def commits(base: str, head: str, cwd: str = ".") -> list[str]: + spec = f"{base}..{head}" + out = subprocess.check_output(["git", "rev-list", "--no-merges", spec], cwd=cwd, text=True) + return [x for x in out.splitlines() if x] + + +def check_commit(commit: str, cwd: str = ".") -> list[str]: + fmt = "%an%x00%ae%x00%B" + raw = subprocess.check_output(["git", "show", "-s", f"--format={fmt}", commit], cwd=cwd, text=True) + name, email, message = raw.split("\x00", 2) + errors: list[str] = [] + if not allowed(name.strip(), email.strip()): + errors.append(f"{commit}: author {name.strip()} <{email.strip()}> is not allowed") + for line in message.splitlines(): + if line.lower().startswith("co-authored-by:"): + value = line.split(":", 1)[1].strip() + match = re.fullmatch(r".+ <([^<>]+)>", value) + if not match or not allowed(value.rsplit(" <", 1)[0], match.group(1)): + errors.append(f"{commit}: {line}") + return errors + + +def main() -> int: + base = os.environ.get("REPO_CHECK_BASE") + head = os.environ.get("REPO_CHECK_HEAD") + if not base or not head: + base, head = "origin/main", "HEAD" + try: + ids = commits(base, head) + except subprocess.CalledProcessError as exc: + print(f"cannot inspect {base}..{head}: git exited {exc.returncode}") + return 1 + errors = [error for commit in ids for error in check_commit(commit)] + for error in errors: + print(error) + print(f"Author check: {len(ids)} non-merge commits; {len(errors)} failures") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test_repo_checks.py b/scripts/test_repo_checks.py new file mode 100644 index 00000000..b9419ef3 --- /dev/null +++ b/scripts/test_repo_checks.py @@ -0,0 +1,44 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +import repo_checks + + +class RepoChecksTest(unittest.TestCase): + def test_allowed_identities(self): + self.assertTrue(repo_checks.allowed("qiyinxi", "qiyinxi@foxmail.com")) + self.assertTrue(repo_checks.allowed("bot", "123+bot[bot]@users.noreply.github.com")) + self.assertTrue(repo_checks.allowed("someone", "someone@users.noreply.github.com")) + self.assertFalse(repo_checks.allowed("ai", "noreply@openai.com")) + + def test_commit_and_coauthor(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "config", "user.name", "qiyinxi"], cwd=root, check=True) + subprocess.run(["git", "config", "user.email", "qiyinxi@foxmail.com"], cwd=root, check=True) + (root / "x").write_text("x") + subprocess.run(["git", "add", "x"], cwd=root, check=True) + env = dict(os.environ, GIT_AUTHOR_NAME="qiyinxi", GIT_AUTHOR_EMAIL="qiyinxi@foxmail.com") + subprocess.run(["git", "commit", "-qm", "ok\n\nCo-authored-by: bot <123+bot[bot]@users.noreply.github.com>"], cwd=root, env=env, check=True) + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() + self.assertEqual(repo_checks.check_commit(commit, str(root)), []) + + def test_rejects_ai_trailer(self): + with tempfile.TemporaryDirectory() as td: + root = Path(td) + subprocess.run(["git", "init", "-q"], cwd=root, check=True) + subprocess.run(["git", "config", "user.name", "qiyinxi"], cwd=root, check=True) + subprocess.run(["git", "config", "user.email", "qiyinxi@foxmail.com"], cwd=root, check=True) + (root / "x").write_text("x") + subprocess.run(["git", "add", "x"], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "bad\n\nCo-authored-by: bot "], cwd=root, check=True) + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() + self.assertTrue(repo_checks.check_commit(commit, str(root))) + + +if __name__ == "__main__": + unittest.main() From eda2ad5cc858093f06d746dfb32a055efaeedf66 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Fri, 30 Oct 2026 22:51:31 +0100 Subject: [PATCH 02/13] =?UTF-8?q?=E5=8F=91=E7=89=88=EF=BC=9A=E5=8A=A0?= =?UTF-8?q?=E5=85=A5=200.1.0=20=E7=8B=AC=E7=AB=8B=E5=8C=85=E5=92=8C?= =?UTF-8?q?=E5=8F=AF=E5=A4=8D=E7=8E=B0=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 102 ++++++++++++++++++++++++++++++++ README.md | 11 +++- build.ps1 | 8 +-- internal/tools/mkzip/main.go | 106 ++++++++++++++++++++++++++++++++++ release/0.1.0.SHA256SUMS.txt | 3 + release/0.1.0.md | 10 ++++ 6 files changed, 234 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 internal/tools/mkzip/main.go create mode 100644 release/0.1.0.SHA256SUMS.txt create mode 100644 release/0.1.0.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..1695bc45 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,102 @@ +name: release + +on: + push: + tags: ["v*"] + +permissions: {} + +concurrency: + group: release-${{ github.ref_name }} + cancel-in-progress: false + +jobs: + build: + if: github.repository == 'ModAVD/ModAVDManager' + runs-on: windows-2025 + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + cache: false + - name: verify tag and ancestry + shell: pwsh + env: + TAG: ${{ github.ref_name }} + SHA: ${{ github.sha }} + run: | + if ($env:TAG -notmatch '^v\d+\.\d+\.\d+$') { throw "invalid tag: $env:TAG" } + git merge-base --is-ancestor $env:SHA origin/main + if ($LASTEXITCODE -ne 0) { throw 'tag is not on origin/main' } + - name: build and verify + shell: pwsh + env: + TAG: ${{ github.ref_name }} + run: | + $version = $env:TAG.Substring(1) + $want = (Select-String -LiteralPath 'internal/buildinfo/buildinfo.go' -Pattern 'Version = "([^"]+)"').Matches.Groups[1].Value + if ($want -ne $version) { throw "buildinfo.Version=$want, tag=$version" } + pwsh -NoProfile -File build.ps1 -Out out + $sums = @{} + foreach ($line in Get-Content "release/$version.SHA256SUMS.txt") { if ($line -match '^([0-9a-f]{64}) (.+)$') { $sums[$Matches[2]] = $Matches[1] } } + foreach ($name in @('ModAVD.exe', 'tools/modavd.exe')) { + $got = (Get-FileHash "out/$name" -Algorithm SHA256).Hash.ToLowerInvariant() + if ($got -ne $sums[$name]) { throw "$name hash mismatch" } + } + $zip = "ModAVDManager-$version-win-x64.zip" + $env:GOTOOLCHAIN = 'local' + go run ./internal/tools/mkzip -dir out -version $version -out $zip + $gotZip = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() + if ($gotZip -ne $sums[$zip]) { throw 'zip hash mismatch' } + New-Item -ItemType Directory -Force artifacts | Out-Null + Copy-Item $zip, "release/$version.SHA256SUMS.txt" artifacts + - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 + with: + name: release-assets + path: artifacts + if-no-files-found: error + + draft: + needs: build + runs-on: windows-2025 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 1 + - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: release-assets + path: artifacts + - name: verify artifact + shell: pwsh + env: + TAG: ${{ github.ref_name }} + run: | + $version = $env:TAG.Substring(1) + $sumPath = "artifacts/$version.SHA256SUMS.txt" + $zip = "artifacts/ModAVDManager-$version-win-x64.zip" + $line = Get-Content $sumPath | Where-Object { $_ -match "^([0-9a-f]{64}) ModAVDManager-$version-win-x64\.zip$" } + $expected = $Matches[1] + $actual = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() + if ($actual -ne $expected) { throw 'downloaded zip hash mismatch' } + if (gh release view $env:TAG 2>$null) { throw 'release already exists' } + - name: create draft + shell: pwsh + env: + TAG: ${{ github.ref_name }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + $version = $env:TAG.Substring(1) + $zip = "artifacts/ModAVDManager-$version-win-x64.zip" + $sumPath = "artifacts/$version.SHA256SUMS.txt" + gh release create $env:TAG --draft --verify-tag --notes-file "release/$version.md" $zip $sumPath diff --git a/README.md b/README.md index d0b072e7..73e1e1db 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,9 @@ ## 和 ModAVD 的关系 -- 两个程序随 [ModAVD](https://github.com/ModAVD/ModAVD) 的 Release 包发布:包根目录的 `ModAVD.exe`(管理器)和 `tools\modavd.exe`(命令行、MCP)。只是使用的话,下载 ModAVD 的 Release 就行,不用自己编译。 -- 本仓库只有这两个程序的源码。模拟器本身的补丁、安装说明和发版在 ModAVD 仓库。 +- 本公开仓库是管理器和命令行程序的开发与发版依据,版本号独立维护,并单独提供 GitHub Release。 +- ModAVD 整包仍会带着 `ModAVD.exe` 和 `tools\modavd.exe`,每次 ModAVD 发版会钉住使用的管理器版本与哈希。 +- 单独下载包可在任意目录使用;给 `--root` 或设置 `MODAVD_ROOT` 指向 ModAVD 根目录,并按下面的哈希核对下载内容。不要把它解压到 ModAVD 根目录覆盖整包里的文件。 | 产物 | 源码 | 做什么 | | --- | --- | --- | @@ -158,6 +159,12 @@ go test ./... - 有几项测试只读本机 `D:\ModAVD` 下的现成文件(`mas-avd.json`、实例配置、组件 APK),没有就跳过;`MODAVD_TEST_METADATA` 可以另指一份 `mas-avd.json`。 - CI(`.github/workflows/ci.yml`)在 `windows-2025` 上跑格式检查、`go vet`、`go test`、`build.ps1`、隐私扫描和作者检查;只在 PR 或手动触发时运行。 +## 独立下载与哈希 + +v0.1.0 是第一个独立版本。压缩包名为 `ModAVDManager-0.1.0-win-x64.zip`,内容只有两个程序、许可证和清单;压缩包不带顶层目录。下载后核对 `release/0.1.0.SHA256SUMS.txt` 中的两个 exe 与 zip 的 SHA-256。v0.1.0 没有自更新,单独下载的文件需要手动替换;从 v0.2.0 起才提供自更新。 + +自己编译需要 Go 1.26.5、`GOTOOLCHAIN=local`,运行 `build.ps1`。单独使用时必须指定 `--root` 或 `MODAVD_ROOT`,否则程序会提示找不到 ModAVD 根目录。 + ## 参与 - 只有一个维护者,回复可能要几天。改代码前先开 issue,写清要改什么、为什么;没商量过的大 PR 可能不合。 diff --git a/build.ps1 b/build.ps1 index d4eb7bd0..a8cb7f27 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,15 +1,15 @@ # Build tools\modavd.exe reproducibly: the same source and Go version give the same bytes on any machine and path. # -# pwsh -NoProfile -File tools\modavd\build.ps1 # -> tools\modavd\out\tools\modavd.exe, out\ModAVD.exe -# pwsh -NoProfile -File tools\modavd\build.ps1 -Out -Go \bin\go.exe -# pwsh -NoProfile -File tools\modavd\build.ps1 -Test # go vet + go test first +# pwsh -NoProfile -File build.ps1 # -> out\tools\modavd.exe, out\ModAVD.exe +# pwsh -NoProfile -File build.ps1 -Out -Go \bin\go.exe +# pwsh -NoProfile -File build.ps1 -Test # go vet + go test first # # modavd.exe is the console program (CLI, MCP); ModAVD.exe is the manager, a GUI-subsystem exe (-H=windowsgui, no # console window when double-clicked) built from cmd/modavd-gui. In the package: \tools\modavd.exe and # \ModAVD.exe. # # -trimpath keeps local paths (GOROOT under C:\Users, the source dir) out of the binary, which the release privacy scan -# would flag; -buildvcs=false keeps the private repo's commit and dirty flag out. GOTOOLCHAIN=local plus the check +# would flag; -buildvcs=false keeps repository metadata and dirty flags out. GOTOOLCHAIN=local plus the check # against go.mod's toolchain line makes sure no other Go version builds it silently. No -X version stamp (see # internal/buildinfo). diff --git a/internal/tools/mkzip/main.go b/internal/tools/mkzip/main.go new file mode 100644 index 00000000..64874340 --- /dev/null +++ b/internal/tools/mkzip/main.go @@ -0,0 +1,106 @@ +// Command mkzip creates the deterministic standalone manager archive. +package main + +import ( + "archive/zip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "sort" + "time" +) + +type manifest struct { + Version string `json:"version"` + Files map[string]string `json:"files"` +} + +func digest(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func main() { + dir := flag.String("dir", "out", "build output directory") + version := flag.String("version", "0.1.0", "manager version") + out := flag.String("out", "", "zip path") + flag.Parse() + if *out == "" { + *out = fmt.Sprintf("ModAVDManager-%s-win-x64.zip", *version) + } + goRoot := runtime.GOROOT() + files := map[string]string{ + "ModAVD.exe": filepath.Join(*dir, "ModAVD.exe"), + "tools/modavd.exe": filepath.Join(*dir, "tools", "modavd.exe"), + "LICENSE": "LICENSE", + "NOTICE": "NOTICE", + "LICENSES/Go-LICENSE.txt": filepath.Join(goRoot, "LICENSE"), + } + data := make(map[string][]byte, len(files)+1) + hashes := make(map[string]string, len(files)) + for name, path := range files { + b, err := os.ReadFile(path) + if err != nil { + panic(err) + } + data[name] = b + hashes[name] = digest(b) + } + manifestBytes, err := json.Marshal(manifest{Version: *version, Files: hashes}) + if err != nil { + panic(err) + } + data["modavd-manager.json"] = append(manifestBytes, '\n') + + names := make([]string, 0, len(data)) + for name := range data { + names = append(names, name) + } + sort.Strings(names) + if err := os.MkdirAll(filepath.Dir(filepath.Clean(*out)), 0o755); err != nil && filepath.Dir(filepath.Clean(*out)) != "." { + panic(err) + } + f, err := os.Create(*out) + if err != nil { + panic(err) + } + zw := zip.NewWriter(f) + epoch := time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC) + for _, name := range names { + h := &zip.FileHeader{Name: name, Method: zip.Store, Modified: epoch} + h.SetMode(0o644) + w, err := zw.CreateHeader(h) + if err != nil { + panic(err) + } + if _, err := io.Copy(w, &byteReader{data: data[name]}); err != nil { + panic(err) + } + } + if err := zw.Close(); err != nil { + panic(err) + } + if err := f.Close(); err != nil { + panic(err) + } +} + +type byteReader struct { + data []byte + pos int +} + +func (r *byteReader) Read(p []byte) (int, error) { + if r.pos == len(r.data) { + return 0, io.EOF + } + n := copy(p, r.data[r.pos:]) + r.pos += n + return n, nil +} diff --git a/release/0.1.0.SHA256SUMS.txt b/release/0.1.0.SHA256SUMS.txt new file mode 100644 index 00000000..26d36f29 --- /dev/null +++ b/release/0.1.0.SHA256SUMS.txt @@ -0,0 +1,3 @@ +3331b658a9f3a000091f4bda6ed13298e11eceee9962c1ce22e1bcfbccc4d65b ModAVD.exe +a86fc959f182ef781b53d1d3bf38806f7a5197f141d5c804d4c6b13274d8879b ModAVDManager-0.1.0-win-x64.zip +90cb0d9ad05b366144202600d38e6d1341a5b9e20b152a7fbe20a220d558723d tools/modavd.exe diff --git a/release/0.1.0.md b/release/0.1.0.md new file mode 100644 index 00000000..c1c90ad1 --- /dev/null +++ b/release/0.1.0.md @@ -0,0 +1,10 @@ +# ModAVDManager v0.1.0 + +这是 ModAVDManager 的第一个独立版本。`ModAVD.exe` 与 `tools/modavd.exe` 和 [ModAVD v0.36.0 包](https://github.com/ModAVD/ModAVD/releases/tag/v0.36.0)中的对应文件逐字节相同: + +- `ModAVD.exe`:`3331b658a9f3a000091f4bda6ed13298e11eceee9962c1ce22e1bcfbccc4d65b` +- `tools/modavd.exe`:`90cb0d9ad05b366144202600d38e6d1341a5b9e20b152a7fbe20a220d558723d` + +使用 Go 1.26.5、`GOTOOLCHAIN=local`,运行仓库中的 `build.ps1` 可以编出相同字节。单独下载包还包含 Go 许可原文和文件清单;请用 `0.1.0.SHA256SUMS.txt` 核对两个 exe 与 zip。 + +0.1.0 没有自更新,单独下载的文件需要手动替换。从 0.2.0 起才提供自更新。单独使用时请给 `--root` 或设置 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把单独下载的 zip 解压到 ModAVD 根目录覆盖整包中的文件。 From c5f8d7549e58273af9ddb13f2b7c65c12bb386a1 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Fri, 30 Oct 2026 22:58:43 +0100 Subject: [PATCH 03/13] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=BC=80=E6=9C=BA?= =?UTF-8?q?=E7=AB=9E=E6=80=81=E3=80=81=E6=89=A7=E8=A1=8C=E6=A1=A5=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=92=8C=E5=AE=A2=E4=BD=93=E6=8C=82=E8=BD=BD=E6=97=B6?= =?UTF-8?q?=E6=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++- cmd/modavd-gui/winres/main.go | 2 +- internal/apk/apk.go | 2 +- internal/buildinfo/buildinfo.go | 2 +- internal/emu/afterboot.go | 2 +- internal/emu/bridge.go | 14 ++++++++--- internal/emu/crud.go | 7 ++++++ internal/emu/ime.go | 2 +- internal/emu/manager.go | 3 ++- internal/emu/start.go | 24 ++++++++++++++++++ internal/emu/status.go | 21 ++++++++++++++-- internal/emu/status_test.go | 2 +- internal/emu/types.go | 9 +++++-- internal/guest/guest.go | 28 ++++++++++++++++++--- internal/guest/guest_test.go | 6 ----- internal/guest/scripts/cpuinfo-bind.sh | 2 +- internal/guest/scripts/mas-wifi-fastpath.sh | 2 +- internal/guest/scripts/vulkanfix.sh | 2 +- internal/vkfix/vkfix.go | 4 +-- internal/win/start.go | 2 +- 20 files changed, 112 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 73e1e1db..1dbb4c94 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb N] [--fps 30\|60] [--no-bridge]` | 新建。默认带 arm64 执行桥,第一次开机时装上;`--no-bridge` 记下这台不要桥,以后开机也不装 | | `set [--title T] [--memory M] [--cpu N] [--fps F] [--data-gb N]` | 修改,下次开机生效。`--data-gb` 只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB) | | `delete --yes` | 删除已关机的实例,连同游戏数据 | -| `start [--window] [--timeout 300] [--no-bridge]` | 开机,等开完并做完开机后的设置;实例还没有执行桥时接着装上,`--no-bridge` 这次不装 | +| `start [--window] [--timeout 300] [--no-bridge]` | 开机,等开完并做完开机后的设置;还会等待 `/sdcard` 挂好(最多 60 秒,超时只警告),实例还没有执行桥时接着装上,`--no-bridge` 这次不装 | | `stop [--force]`、`stop --all` | 关机:先让安卓正常关机,不成再 sync + kill;`--force` 是 sync + 强杀 | | `restart [--window] [--timeout 300] [--force] [--no-bridge]` | 关机再开机,选项同 `stop`、`start` | | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | @@ -76,6 +76,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] - modavd(命令行、MCP)和管理器每次开机都会看一眼:实例还没有桥,就在开机后的设置做完后装上,中间关机再冷启动一两次。只在这次是它拉起的模拟器时装;接管已经在运行的实例时不装。装不上只是警告,实例照常运行,下次开机再试。 - 不要桥的实例:新建时带 `--no-bridge`,或者之后跑 `bridge uninstall`。两种都会在 `mas-avd.json` 里记下 `instances..bridge` 为 `false`,以后开机不再自动装;再 `bridge install` 就恢复。`start` / `restart` 的 `--no-bridge` 只管这一次。 - `bridge` 调用 ModAVD 包里的 `tools\modavd-bridge.ps1`。`install`:需要时关机再开机,装上;已经装了的只在载荷有变时更新。`uninstall`:卸掉桥、开机标记和装桥时改成的 GL 传输方式(asg);退回更早的版本之前要先卸。实例原来关着的,做完再关掉。`verify`:只读核对,实例要开着。 +- `info` / `list` 的 `bridge` 为 `off`、`pending`、`installed` 或 `unknown`;关机时不能查询客体属性,因此没有“不装”记录且没有待装标记时显示 `unknown`。装桥期间 `busy` 为 `bridging`,删除也会持有同一把桥锁。 - 不经 modavd 或管理器开机的实例(别的程序直接拉起模拟器)不会自动装,要装就跑一次 `bridge install`。 **机读输出**(`--json`): @@ -83,6 +84,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] - stdout 只有一行:`{"ok":true,"data":…}` 或 `{"ok":false,"error":{"code","message","advice"}}`。`data` 的字段见 `internal/emu/types.go`,snake_case,所有字段一直出现。 - 进度日志写 stderr,一行一个 JSON:`{"time","level","msg"}`。调用方不要把 stderr 并进 stdout。 - `version --json` 的 `protocol` 是契约版本,字段改了含义或删了才加一。 +- 运行中的实例增加 `started_at_ms`(Unix 毫秒),原来的 `started_at` 保留。`stop --all` 即使部分失败也返回 `ok:true` 和结果列表,同时以第一个失败的退出码结束。 **退出码**:0 成功,1 内部错误,2 用法或参数不对,3 实例不存在,4 根目录没就绪 / 检查没通过 / 不支持,5 实例忙 / 已存在 / 端口被占,6 超时,7 启动失败,8 已取消。`shell` 不带 `--json` 时是客体命令的退出码,`adb` 是 adb 的退出码;`bridge` 不带 `--json` 时,`install` 后没装上、`uninstall` 后还在都是 1,`verify` 是脚本的退出码。 @@ -180,3 +182,6 @@ v0.1.0 是第一个独立版本。压缩包名为 `ModAVDManager-0.1.0-win-x64.z - 程序图标(`cmd/modavd-gui/modavd.ico`、`cmd/modavd-gui/rsrc_windows_amd64.syso`、`internal/ui/web/assets/` 下的图片)是《明日方舟》艾雅法拉的同人图,角色版权归上海鹰角网络所有,不在本仓库的许可范围内; - `internal/avd/testdata/instances_ref.py` 复制自 AUTO-MAS(AGPL-3.0-or-later),只供测试、在单独的进程里运行,不编进程序。 - 编出的 exe 含 Go 标准库和运行时(BSD-3-Clause)。 + + + diff --git a/cmd/modavd-gui/winres/main.go b/cmd/modavd-gui/winres/main.go index 69a79635..752ccbbf 100644 --- a/cmd/modavd-gui/winres/main.go +++ b/cmd/modavd-gui/winres/main.go @@ -2,7 +2,7 @@ // the application manifest (RT_MANIFEST), as a COFF object with a single .rsrc section. The Go linker merges a // package's .syso files into the executable, so the icon shows in Explorer and the taskbar with no extra tool. // -// cd tools\modavd\cmd\modavd-gui && go run ./winres (or: go generate ./cmd/modavd-gui) +// go run ./cmd/modavd-gui/winres // // The output is deterministic (no timestamps), so the same icon gives the same bytes and release builds stay // reproducible. Run it again only when modavd.ico or the manifest changes, and commit the .syso. diff --git a/internal/apk/apk.go b/internal/apk/apk.go index 61d396e0..b71e82fe 100644 --- a/internal/apk/apk.go +++ b/internal/apk/apk.go @@ -1,5 +1,5 @@ // Package apk reads the package name and versionCode from an APK's binary AndroidManifest.xml, without aapt -// (neither the release package nor dev SDKs have it). Port of Get-ApkManifestInfo in tools/launcher/avd-p0.ps1: +// (neither the release package nor development SDKs have it). Port of the launcher's Get-ApkManifestInfo helper: // walk the chunks — string pool (0x0001), resource ids (0x0180), the first start tag () — and read its // "package" (string attribute) and "versionCode" (integer attribute; resource id 0x0101021b). // diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index 6fc22004..4280144a 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -4,7 +4,7 @@ package buildinfo // Version of modavd itself, kept in the source rather than set with -ldflags -X: release builds must come out byte // for byte the same for the same source (Mirror 酱 ships per-file deltas, and a version stamped per package would // change the exe in every release). The ModAVD package version comes from the root at run time. -var Version = "0.1.0" +var Version = "0.2.0" // Protocol is the version of the machine-readable contract: the JSON written by `--json`, the exit codes and the // MCP tool schemas. Callers such as AUTO-MAS check it (`modavd version --json`) before relying on a field. diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 90c023b8..c039da1d 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -217,7 +217,7 @@ func tuneHostScheduling(p win.Process) string { } // setupGuestWriteback sets the guest dirty_expire / dirty_writeback to 200 / 100 cs and reads them back (10-04 hard -// kill tests, AGENTS.md: "delete, then rename the temp file over" came back 0 bytes up to 34 s after the write at +// kill tests, deleting then renaming the temp file came back 0 bytes up to 34 s after the write at // the default 3000 / 500; 200 / 100 shrinks that to about 5 s for ~14% more host writes). func (m *Manager) setupGuestWriteback(ctx context.Context, i int) { res := m.su(ctx, i, fmt.Sprintf("echo %d > /proc/sys/vm/dirty_expire_centisecs; "+ diff --git a/internal/emu/bridge.go b/internal/emu/bridge.go index 2424460a..5602107d 100644 --- a/internal/emu/bridge.go +++ b/internal/emu/bridge.go @@ -11,8 +11,8 @@ package emu // It runs without -Reboot: where the script would reboot the guest (the first remount only turns verity off; the new // build.prop line is read at boot) modavd shuts the instance down and boots it cold instead. A guest reboot under // WHPX can leave one vCPU deaf to IPIs, and the guest then spins in smp_call_function forever (10-30 bridge-default -// regression: soft lockup in toggle_allocation_gate right after the install's `adb reboot`, docs/自研模拟器-AOSP提交/TSC.md -// has the same picture); a cold boot does not reset vCPUs in place. +// regression: soft lockup in toggle_allocation_gate right after the install's `adb reboot`; a cold boot does not +// reset vCPUs in place. // // Instances AUTO-MAS creates and boots itself never come through here; `modavd bridge install` does them (and // any older instance). @@ -294,6 +294,14 @@ func (m *Manager) Bridge(ctx context.Context, i int, action string) (*BridgeResu if _, err := m.instance(i); err != nil { return nil, err } + bridgeLock, ok, err := win.TryLock(m.lockPath(i, "bridge")) + if err != nil { + return nil, errs.Wrap(errs.Internal, err, "实例执行桥锁文件打不开") + } + if !ok { + return nil, errs.Newf(errs.Busy, "魔改 AVD 实例 %d 正在装执行桥,无法重复操作", i) + } + defer bridgeLock.Unlock() res := &BridgeResult{Index: i, Action: action, ExitCode: -1, Warnings: []string{}} _, wasRunning := m.findQemu(i) @@ -322,7 +330,7 @@ func (m *Manager) Bridge(ctx context.Context, i int, action string) (*BridgeResu res.Restarted = true } if !wasRunning || res.Restarted { - sr, err := m.Start(ctx, i, StartOptions{}) + sr, err := m.Start(ctx, i, StartOptions{NoBridge: true}) if err != nil { return nil, err } diff --git a/internal/emu/crud.go b/internal/emu/crud.go index a41b55b7..0b1054b0 100644 --- a/internal/emu/crud.go +++ b/internal/emu/crud.go @@ -164,7 +164,14 @@ func (m *Manager) Delete(ctx context.Context, i int) (*DeleteResult, error) { startLock.Unlock() return nil, err } + bridgeLock, err := m.tryInstanceLock(i, "bridge", "正在装执行桥") + if err != nil { + startLock.Unlock() + stopLock.Unlock() + return nil, err + } unlock := func() { + bridgeLock.Unlock() stopLock.Unlock() startLock.Unlock() } diff --git a/internal/emu/ime.go b/internal/emu/ime.go index 74386ab6..6b534eba 100644 --- a/internal/emu/ime.go +++ b/internal/emu/ime.go @@ -21,7 +21,7 @@ import ( // The host input method org.modavd.ime: the guest half of the emulator's modavd_ime channel; what the user types // with a Windows IME in the emulator window reaches the app through it. It has no input view and leaves key events // alone, so `adb shell input`, maatouch and MaaFW input reach the app as before. Same constants as AUTO-MAS HOST_IME* -// and the launcher tools/launcher/avd-p0.ps1. +// and the launcher's embedded setup script. const ( hostImePackage = "org.modavd.ime" hostImeID = "org.modavd.ime/.HostImeService" diff --git a/internal/emu/manager.go b/internal/emu/manager.go index 57d0e5c5..ee8d2c2e 100644 --- a/internal/emu/manager.go +++ b/internal/emu/manager.go @@ -62,6 +62,7 @@ const ( balloonReportingOrder = 9 logcatBufferSize = "16M" guestTmpDir = "/data/local/tmp" + sdcardMountWait = 60 * time.Second emulatorShmNamePrefix = "SHM_videmulator" installLauncherTimeout = 180 * time.Second ) @@ -335,7 +336,7 @@ func (m *Manager) guestLockPath(i int) string { // removeLockFiles deletes the lock files, the setup marker and the boot record of instance i (after Delete); best // effort. func (m *Manager) removeLockFiles(i int) { - for _, kind := range []string{"start", "boot", "stop", "watch"} { + for _, kind := range []string{"start", "boot", "stop", "watch", "bridge"} { os.Remove(m.lockPath(i, kind)) } os.Remove(m.setupMarkerPath(i)) diff --git a/internal/emu/start.go b/internal/emu/start.go index 7865be26..0ad5f9cd 100644 --- a/internal/emu/start.go +++ b/internal/emu/start.go @@ -254,6 +254,9 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption if err != nil { return nil, owed(err) } + if !m.waitSDCard(ctx, i) { + m.Log.Warnf("实例 %d 安卓已开机,但 /sdcard 在 %.0f 秒内还没挂好;继续返回,稍后再试", i, sdcardMountWait.Seconds()) + } if res.Launched { res.BootSeconds = time.Since(launchedAt).Seconds() prog.emit("boot", fmt.Sprintf("实例 %d 安卓已开机(%.1f 秒)", i, res.BootSeconds), progressBooted) @@ -328,6 +331,27 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption return res, nil } +// waitSDCard covers the short interval after sys.boot_completed in which vold has not mounted shared storage yet. +// A timeout is only a warning: the emulator is usable and a later start/status call can observe the mount. +func (m *Manager) waitSDCard(ctx context.Context, i int) bool { + deadline := time.Now().Add(sdcardMountWait) + for { + if err := ctxErr(ctx); err != nil { + return false + } + res := m.shell(ctx, i, "test -d /sdcard && test -r /sdcard && test -w /sdcard", statusAdbTimeout) + if res.Code == 0 { + return true + } + if !time.Now().Before(deadline) { + return false + } + if !sleepOrDone(ctx, 500*time.Millisecond) { + return false + } + } +} + // waitBoot polls sys.boot_completed every second until it is 1 (AUTO-MAS _wait_boot). An instance this call launched // is not re-registered meanwhile (it has not registered with the private server yet, which is normal); an adopted // one may have missed a server restart and is. Fails when the deadline passes, when emulator.exe has exited while diff --git a/internal/emu/status.go b/internal/emu/status.go index 39684910..2c4b7935 100644 --- a/internal/emu/status.go +++ b/internal/emu/status.go @@ -130,6 +130,7 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *win.Pro info.PID = int(p.PID) if t := p.StartedAt(); !t.IsZero() { info.StartedAt = t.Format(time.RFC3339) + info.StartedAtMS = t.UnixMilli() } if booted != nil { info.Booted = *booted @@ -141,7 +142,8 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *win.Pro info.Screencap.ShmReady = win.SharedMemoryExists(info.Screencap.Shm) } info.Status = statusOf(info.Running, info.Booted) - info.Busy = busyOf(m.stopping(i), m.lockHeld(i, "start")) + info.Busy = busyOf(m.stopping(i), m.lockHeld(i, "start"), m.lockHeld(i, "bridge")) + info.Bridge = m.bridgeState(ctx, i, info.Running) cfg := InstanceConfig{MemoryMB: avd.MemoryFor(m.Root, i), FPS: in.FPS()} if n, ok := in.CPU(); ok { @@ -176,8 +178,10 @@ func statusOf(running, booted bool) Status { } // busyOf: a stop that runs wins over a start (a stop does not wait for a start, and ends it). -func busyOf(stopping, starting bool) string { +func busyOf(stopping, starting, bridging bool) string { switch { + case bridging: + return "bridging" case stopping: return "stopping" case starting: @@ -187,6 +191,19 @@ func busyOf(stopping, starting bool) string { } } +func (m *Manager) bridgeState(ctx context.Context, i int, running bool) string { + if !m.bridgeWanted(i) { + return "off" + } + if regularFile(bridgeMarker(m.Root, i)) { + return "pending" + } + if running && m.guestBridge(ctx, i) == bridgeProp { + return "installed" + } + return "unknown" +} + // lockHeld: some process (this one included: the lock is per handle) holds lock kind of instance i right now. func (m *Manager) lockHeld(i int, kind string) bool { l, ok, err := win.TryLock(m.lockPath(i, kind)) diff --git a/internal/emu/status_test.go b/internal/emu/status_test.go index 7f68060e..24647b27 100644 --- a/internal/emu/status_test.go +++ b/internal/emu/status_test.go @@ -18,7 +18,7 @@ func TestStatusOfAndBusyOf(t *testing.T) { if statusOf(true, false) != StatusStarting || statusOf(true, true) != StatusOnline { t.Fatal("qemu: starting until booted") } - if busyOf(false, false) != "" || busyOf(false, true) != "starting" || busyOf(true, false) != "stopping" || busyOf(true, true) != "stopping" { + if busyOf(false, false, false) != "" || busyOf(false, true, false) != "starting" || busyOf(true, false, false) != "stopping" || busyOf(true, true, false) != "stopping" || busyOf(false, false, true) != "bridging" { t.Fatal("busyOf") } } diff --git a/internal/emu/types.go b/internal/emu/types.go index 32ffc57d..1213ccc3 100644 --- a/internal/emu/types.go +++ b/internal/emu/types.go @@ -51,9 +51,14 @@ type InstanceInfo struct { // Busy: "starting" / "stopping" while some modavd process holds that lock of the instance (AUTO-MAS's updater // must not swap sdk\emulator then); "" otherwise. Busy string `json:"busy"` - PID int `json:"pid"` + // Bridge is off (disabled), pending (marker requests install), installed, or unknown (the instance is off or + // the guest did not answer). An offline instance is unknown when its marker is absent because the guest property + // cannot be queried; only an explicit off setting is definitive. + Bridge string `json:"bridge"` + PID int `json:"pid"` // StartedAt is the qemu process start, local time RFC 3339 ("2026-10-28T15:04:05+01:00"). - StartedAt string `json:"started_at"` + StartedAt string `json:"started_at"` + StartedAtMS int64 `json:"started_at_ms"` // Serial is the device on the private adb server (adb -P -s ). Scripts that use their own // adb server connect to AdbAddress instead. Serial string `json:"serial"` diff --git a/internal/guest/guest.go b/internal/guest/guest.go index f597eccd..db630030 100644 --- a/internal/guest/guest.go +++ b/internal/guest/guest.go @@ -1,6 +1,5 @@ // Package guest holds the scripts modavd pushes into the guest after boot. They are copies of AUTO-MAS -// res/avd/guest/*.sh (the product versions; mas-idlepoll.sh differs from aemu-lab tools/launcher/ only in a comment, -// mas-wifi-fastpath.sh equals tools/guest/). Until AUTO-MAS calls modavd for booting, changes go into both places. +// res/avd/guest/*.sh (the product versions). Keep these shared scripts in sync with the companion launcher. package guest import ( @@ -14,6 +13,8 @@ import ( "os" "path/filepath" "sync/atomic" + "syscall" + "time" ) //go:embed scripts/*.sh @@ -58,7 +59,7 @@ func LocalFile(dir, name string) (string, error) { sum := sha256.Sum256(b) sub := filepath.Join(dir, hex.EncodeToString(sum[:])[:12]) path := filepath.Join(sub, name) - switch old, err := os.ReadFile(path); { + switch old, err := readStable(path); { case err == nil && bytes.Equal(old, b): return path, nil case err == nil: @@ -81,7 +82,7 @@ func LocalFile(dir, name string) (string, error) { if err != nil { os.Remove(tmp) // another writer got there first: its file is just as good when it holds these bytes - if old, rerr := os.ReadFile(path); rerr == nil && bytes.Equal(old, b) { + if old, rerr := readStable(path); rerr == nil && bytes.Equal(old, b) { return path, nil } return "", err @@ -89,5 +90,24 @@ func LocalFile(dir, name string) (string, error) { return path, nil } +// readStable tolerates the short window in which another writer has renamed a complete file but still has its +// handle open. Windows reports that as ERROR_SHARING_VIOLATION (or ERROR_LOCK_VIOLATION); retrying here makes the +// content-addressed first write safe across processes without weakening the no-replace invariant. +func readStable(path string) ([]byte, error) { + const attempts = 40 + for n := 0; ; n++ { + b, err := os.ReadFile(path) + if err == nil || n >= attempts || !sharingViolation(err) { + return b, err + } + time.Sleep(50 * time.Millisecond) + } +} + +func sharingViolation(err error) bool { + var errno syscall.Errno + return errors.As(err, &errno) && (errno == syscall.Errno(32) || errno == syscall.Errno(33)) +} + // Remote is the guest path of a script. func Remote(name string) string { return RemoteDir + "/" + name } diff --git a/internal/guest/guest_test.go b/internal/guest/guest_test.go index f868d6c4..4f4ce1f4 100644 --- a/internal/guest/guest_test.go +++ b/internal/guest/guest_test.go @@ -122,12 +122,6 @@ func TestLocalFileDamaged(t *testing.T) { // TestLocalFileConcurrent: many writers at once (goroutines here; processes share the same path logic) all succeed // with the same complete file. func TestLocalFileConcurrent(t *testing.T) { - // Known race (10-30): on GitHub's Windows runners (real-time AV scan, slow disk) some writers read the freshly - // moved file while it is still held and get ERROR_SHARING_VIOLATION; 200 local runs never hit it. LocalFile will - // retry such reads in the next version; until then the test is skipped on CI only. - if os.Getenv("CI") == "true" { - t.Skip("known sharing-violation race on CI runners, fixed in the next version") - } dir := t.TempDir() want, b := contentPath(t, dir, WifiFastpath) var wg sync.WaitGroup diff --git a/internal/guest/scripts/cpuinfo-bind.sh b/internal/guest/scripts/cpuinfo-bind.sh index ac65b20d..4997cee6 100644 --- a/internal/guest/scripts/cpuinfo-bind.sh +++ b/internal/guest/scripts/cpuinfo-bind.sh @@ -1,6 +1,6 @@ #!/system/bin/sh # cpuinfo-bind.sh - one cpuinfo entry per real vCPU for the ARM translation layer. Run as root (su 0 sh ...). -# Same text as the inline script in aemu-lab tools\launcher\avd-p0.ps1; keep the two in sync. +# Keep this text in sync with the launcher’s embedded guest script. # # ARM games run through libndk_translation, which answers their /proc/cpuinfo from # /system/etc/cpuinfo.{arm64,arm}.txt: a single "processor : 1" entry. Unity then reports diff --git a/internal/guest/scripts/mas-wifi-fastpath.sh b/internal/guest/scripts/mas-wifi-fastpath.sh index 63b5d95c..5f3a396d 100644 --- a/internal/guest/scripts/mas-wifi-fastpath.sh +++ b/internal/guest/scripts/mas-wifi-fastpath.sh @@ -2,7 +2,7 @@ # mas-wifi-fastpath.sh - guest sees Wi-Fi, bulk data goes over eth0. Run as root # (adb root + adb shell, or adb shell su 0 sh ...). Same text is embedded in # external/qemu android/android-emu/android/network/wifi.cpp (-wifi-fastpath); -# keep the two in sync. Explanation: C:\emu-src\patches\wifi\README.md +# keep the two in sync. The simulator's embedded wifi implementation must be updated alongside this script. # # on apply once (idempotent) # daemon start "watch" in the background unless already running diff --git a/internal/guest/scripts/vulkanfix.sh b/internal/guest/scripts/vulkanfix.sh index d28faab3..38847979 100644 --- a/internal/guest/scripts/vulkanfix.sh +++ b/internal/guest/scripts/vulkanfix.sh @@ -1,7 +1,7 @@ #!/system/bin/sh # vulkanfix.sh - bind-mount the patched guest Vulkan encoder (bindlock2, includes # khrfix) over the image's own and restart zygote (it preloads the driver). Run as root (su 0 sh ...). Same steps as -# -VulkanFix in aemu-lab tools\launcher\avd-p0.ps1; the patch itself is made on the host from the image's own library +# The launcher carries the same Vulkan fix text; the patch itself is made on the host from the image's own library # (app/utils/common/emulator2/avd/vulkanfix.py), the patched file is never shipped. # # The patched copy stays in /data/local/tmp as a cache: the next boot mounts it again without a new upload. It is diff --git a/internal/vkfix/vkfix.go b/internal/vkfix/vkfix.go index 682b3fa1..2dba70f2 100644 --- a/internal/vkfix/vkfix.go +++ b/internal/vkfix/vkfix.go @@ -1,8 +1,8 @@ // Package vkfix builds the patched guest Vulkan encoder (bindlock2, includes khrfix) from the image's own // /vendor/lib64/libvulkan_enc.so on the user's machine; the patched file is never distributed. // -// Byte-for-byte port of AUTO-MAS app/utils/common/emulator2/avd/vulkanfix.py (itself a copy of aemu-lab -// tools/guest/bindlock.py): khrfix jumps for vkUpdateDescriptorSetWithTemplateKHR, and lock wrappers around +// Byte-for-byte port of the companion Vulkan fix implementation: khrfix jumps for +// vkUpdateDescriptorSetWithTemplateKHR, and lock wrappers around // ResourceTracker::on_vkBindImageMemory(2) placed in the freed dynCheck function body. // // 1. khrfix (09-30, Star Rail normal mode): the two vkUpdateDescriptorSetWithTemplateKHR entries call the raw diff --git a/internal/win/start.go b/internal/win/start.go index 0e52993f..802361cc 100644 --- a/internal/win/start.go +++ b/internal/win/start.go @@ -224,7 +224,7 @@ type spawnReply struct { // StartDetached), which starts exe with StartDetached semantics, reports the child to us and exits at once. The // child's parent PID then names a dead process, so tools that end "the process tree" of modavd (Claude Code ends an // MCP server's whole tree on disconnect; AUTO-MAS Runtime's job object) cannot reach the emulator: ending qemu -// without a guest shutdown is a power cut (AGENTS.md). Output must be given as opt.OutputPath (opened by the helper, +// without a guest shutdown is a power cut. Output must be given as opt.OutputPath (opened by the helper, // appended to); opt.Output is not allowed here. The helper gets opt.Env and passes it on. Returns the grandchild. // // Protocol: one JSON argument (spawnRequest) after "__spawn"; the helper's stdout is a pipe to us carrying one JSON From 44dfb744a5028ffa77ff75a26d905267399f1897 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:10:27 +0100 Subject: [PATCH 04/13] =?UTF-8?q?=E5=8F=91=E7=89=88=E9=99=84=E4=BB=B6?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=9B=BA=E5=AE=9A=E7=9A=84=20SHA256SUMS=20?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1695bc45..64087a90 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -56,7 +56,8 @@ jobs: $gotZip = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() if ($gotZip -ne $sums[$zip]) { throw 'zip hash mismatch' } New-Item -ItemType Directory -Force artifacts | Out-Null - Copy-Item $zip, "release/$version.SHA256SUMS.txt" artifacts + Copy-Item $zip artifacts + Copy-Item "release/$version.SHA256SUMS.txt" "artifacts/SHA256SUMS.txt" - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 with: name: release-assets @@ -83,7 +84,7 @@ jobs: TAG: ${{ github.ref_name }} run: | $version = $env:TAG.Substring(1) - $sumPath = "artifacts/$version.SHA256SUMS.txt" + $sumPath = "artifacts/SHA256SUMS.txt" $zip = "artifacts/ModAVDManager-$version-win-x64.zip" $line = Get-Content $sumPath | Where-Object { $_ -match "^([0-9a-f]{64}) ModAVDManager-$version-win-x64\.zip$" } $expected = $Matches[1] @@ -98,5 +99,5 @@ jobs: run: | $version = $env:TAG.Substring(1) $zip = "artifacts/ModAVDManager-$version-win-x64.zip" - $sumPath = "artifacts/$version.SHA256SUMS.txt" + $sumPath = "artifacts/SHA256SUMS.txt" gh release create $env:TAG --draft --verify-tag --notes-file "release/$version.md" $zip $sumPath From 9ab66d342fd1dabb42a4522a50075822ea428677 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:11:26 +0100 Subject: [PATCH 05/13] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=85=AC=E5=BC=80?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=B8=AD=E7=9A=84=E6=9C=AC=E6=9C=BA=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E5=92=8C=E7=A7=81=E6=9C=89=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/adb/identity.go | 2 +- internal/adb/real_adb_test.go | 2 +- internal/apk/apk_test.go | 2 +- internal/cli/format_test.go | 4 ++-- internal/root/root.go | 2 +- internal/root/root_test.go | 4 ++-- internal/vkfix/vkfix_test.go | 4 ++-- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/adb/identity.go b/internal/adb/identity.go index 8bc4d4e2..0ae644d9 100644 --- a/internal/adb/identity.go +++ b/internal/adb/identity.go @@ -262,7 +262,7 @@ func hasDirPrefix(path, dir string) bool { // resolvedPath is path with its links resolved, cleaned; the cleaned path itself when it cannot be resolved (it does // not exist, access denied). filepath.EvalSymlinks alone is not enough: since Go 1.23 it leaves mount points unresolved -// on Windows, and a directory junction (C:\emu-src) is one. +// on Windows, and a directory junction (C:\sdk-src) is one. func resolvedPath(path string) string { if s, ok := finalPath(path); ok { return filepath.Clean(s) diff --git a/internal/adb/real_adb_test.go b/internal/adb/real_adb_test.go index 75276576..30eb0157 100644 --- a/internal/adb/real_adb_test.go +++ b/internal/adb/real_adb_test.go @@ -33,7 +33,7 @@ const ( // testSDK is an SDK whose adb.exe the test may run (only run, never modified). func testSDK() string { - for _, sdk := range []string{`C:\emu-src\sdk-mas35`, `D:\ModAVD\sdk`} { + for _, sdk := range []string{`C:\sdk-src\sdk-mas35`, `D:\ModAVD\sdk`} { if st, err := os.Stat(filepath.Join(sdk, "platform-tools", "adb.exe")); err == nil && !st.IsDir() { return sdk } diff --git a/internal/apk/apk_test.go b/internal/apk/apk_test.go index c353f260..8a43cd32 100644 --- a/internal/apk/apk_test.go +++ b/internal/apk/apk_test.go @@ -441,7 +441,7 @@ func TestReadManifestRejects(t *testing.T) { // ---- real APKs --------------------------------------------------------------------------------------------------- -// Expected values come from Get-ApkManifestInfo in tools/launcher/avd-p0.ps1, run with pwsh on the same files. +// Expected values come from Get-ApkManifestInfo in the launcher embedded helper, run with pwsh on the same files. // The IME's APKs are looked for in $MODAVD_TEST_IME_APK_DIR (the IME build's output directory); without it those // cases are skipped. func TestReadManifestRealAPKs(t *testing.T) { diff --git a/internal/cli/format_test.go b/internal/cli/format_test.go index 2478ace9..5047c433 100644 --- a/internal/cli/format_test.go +++ b/internal/cli/format_test.go @@ -84,9 +84,9 @@ func TestFormatListTable(t *testing.T) { } buf.Reset() - formatList(&buf, &emu.ListResult{RootInfo: emu.RootInfo{Root: `D:\r`, LocalSDK: true, SDK: `C:\emu-src\sdk-mas35`}}) + formatList(&buf, &emu.ListResult{RootInfo: emu.RootInfo{Root: `D:\r`, LocalSDK: true, SDK: `C:\sdk-src\sdk-mas35`}}) out := buf.String() - if !strings.Contains(out, "ModAVD 版本未知") || !strings.Contains(out, `SDK:C:\emu-src\sdk-mas35(mas-avd.json 的 sdkRoot)`) || + if !strings.Contains(out, "ModAVD 版本未知") || !strings.Contains(out, `SDK:C:\sdk-src\sdk-mas35(mas-avd.json 的 sdkRoot)`) || !strings.Contains(out, "还没有实例") { t.Errorf("empty list = %q", out) } diff --git a/internal/root/root.go b/internal/root/root.go index 396f7b1f..0d4fc15d 100644 --- a/internal/root/root.go +++ b/internal/root/root.go @@ -182,7 +182,7 @@ func New(dir string) (*Root, error) { return openDir(cleanArg(dir), "") } func (r *Root) SDK() string { return filepath.Join(r.Dir, SDKDir) } // \sdk -// LocalSDKRoot is mas-avd.json's sdkRoot (a dev SDK such as C:\emu-src\sdk-mas35), "" when not set. A relative +// LocalSDKRoot is mas-avd.json's sdkRoot (a dev SDK such as C:\sdk-src\sdk-mas35), "" when not set. A relative // value is taken relative to the root (AUTO-MAS would resolve it against its own working directory, which is // never what was meant). func (r *Root) LocalSDKRoot() string { diff --git a/internal/root/root_test.go b/internal/root/root_test.go index d3f2571e..b9e068ba 100644 --- a/internal/root/root_test.go +++ b/internal/root/root_test.go @@ -192,7 +192,7 @@ func TestPaths(t *testing.T) { } } for meta, want := range map[string]string{ - `{"sdkRoot": " C:/emu-src/sdk-mas35/ "}`: `C:\emu-src\sdk-mas35`, + `{"sdkRoot": " C:/emu-src/sdk-mas35/ "}`: `C:\sdk-src\sdk-mas35`, `{"sdkRoot": "dev-sdk"}`: d + `\dev-sdk`, `{"sdkRoot": " "}`: "", `{"sdkRoot": 5}`: "", @@ -205,7 +205,7 @@ func TestPaths(t *testing.T) { } } writeFile(t, r.MetadataPath(), []byte(`{"sdkRoot": "C:\\emu-src\\sdk-mas35"}`)) - if r.AdbExe() != `C:\emu-src\sdk-mas35\platform-tools\adb.exe` || r.SDK() != d+`\sdk` { + if r.AdbExe() != `C:\sdk-src\sdk-mas35\platform-tools\adb.exe` || r.SDK() != d+`\sdk` { t.Errorf("runtime sdk: %s", r.AdbExe()) } } diff --git a/internal/vkfix/vkfix_test.go b/internal/vkfix/vkfix_test.go index 07a55630..3a4ca867 100644 --- a/internal/vkfix/vkfix_test.go +++ b/internal/vkfix/vkfix_test.go @@ -12,8 +12,8 @@ import ( // The real libraries (read-only); the tests that need them are skipped when they are absent. const ( - origLib = `C:\emu-src\work\gfx\guestlibs\libvulkan_enc.so` - fixLib = `C:\emu-src\work\gfx\guestlibs\libvulkan_enc.khrfix-bindlock2.so` + origLib = `C:\sdk-src\work\gfx\guestlibs\libvulkan_enc.so` + fixLib = `C:\sdk-src\work\gfx\guestlibs\libvulkan_enc.khrfix-bindlock2.so` ) // Golden bytes printed by AUTO-MAS vulkanfix.py (_wrapper_bind / _wrapper_bind2 at their caves, _jmp, _EXIT_MAGIC). From ac540126d7eeb03fbc567eba8ec2f6ae158953e3 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:11:56 +0100 Subject: [PATCH 06/13] =?UTF-8?q?=E6=B8=85=E7=90=86=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E5=A4=B9=E5=85=B7=E9=87=8C=E7=9A=84=E6=9C=AC=E6=9C=BA=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/adb/real_adb_test.go | 2 +- internal/jsonord/testdata/gen_pycases.py | 2 +- internal/jsonord/testdata/pycases.json | 2 +- internal/root/root_test.go | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/internal/adb/real_adb_test.go b/internal/adb/real_adb_test.go index 30eb0157..e4427d76 100644 --- a/internal/adb/real_adb_test.go +++ b/internal/adb/real_adb_test.go @@ -47,7 +47,7 @@ func realRoot(t *testing.T) (*root.Root, string) { t.Helper() sdk := testSDK() if sdk == "" { - t.Skip("没有可用的 adb.exe(C:\\emu-src\\sdk-mas35 / D:\\ModAVD\\sdk)") + t.Skip("没有可用的 adb.exe(C:\\sdk-src\\sdk-mas35 / D:\\ModAVD\\sdk)") } dir := tempDir(t) meta, _ := json.Marshal(map[string]any{ diff --git a/internal/jsonord/testdata/gen_pycases.py b/internal/jsonord/testdata/gen_pycases.py index 3e0a6d6e..884ed229 100644 --- a/internal/jsonord/testdata/gen_pycases.py +++ b/internal/jsonord/testdata/gen_pycases.py @@ -18,7 +18,7 @@ '{"名称": "魔改 AVD ✓ 😀", "x": "\\u00e9\\ud83d\\ude00", "": "empty key"}', '"\\u0000\\u0001\\u001f\\u007f\\b\\f\\n\\r\\t \\u0080 \\u00a0 \\u2028 \\u2029 \\ufffd \\ufeff"', '"a\\"b\\\\c\\/d"', - '{"q": "say \\"hi\\"", "p": "C:\\\\emu-src\\\\sdk-mas35\\\\", "u": "\\u4e2d\\u6587"}', + '{"q": "say \\"hi\\"", "p": "C:\\\\sdk-src\\\\sdk-mas35\\\\", "u": "\\u4e2d\\u6587"}', "[6144, -1, 1.5, 1e3, 0.1, 123456789012345678901234567890, -0, -0.0, 0.0, 1E400, -1e400, 1e-400]", "[1.0, 100.0, 1e16, 1e15, 1e-5, 0.0001, 0.001, 2.5e-7, 1.7976931348623157e308, 5e-324, 2.2250738585072014e-308]", "[123.456e2, 0.30000000000000004, 1.23456789012345678, -12.5E+3, 9007199254740993, 9007199254740993.0]", diff --git a/internal/jsonord/testdata/pycases.json b/internal/jsonord/testdata/pycases.json index c85b4e4a..4721fe67 100644 --- a/internal/jsonord/testdata/pycases.json +++ b/internal/jsonord/testdata/pycases.json @@ -30,7 +30,7 @@ }, { "in": "eyJxIjogInNheSBcImhpXCIiLCAicCI6ICJDOlxcZW11LXNyY1xcc2RrLW1hczM1XFwiLCAidSI6ICJcdTRlMmRcdTY1ODcifQ==", -"out": "{\n \"q\": \"say \\\"hi\\\"\",\n \"p\": \"C:\\\\emu-src\\\\sdk-mas35\\\\\",\n \"u\": \"\u4e2d\u6587\"\n}" +"out": "{\n \"q\": \"say \\\"hi\\\"\",\n \"p\": \"C:\\\\sdk-src\\\\sdk-mas35\\\\\",\n \"u\": \"\u4e2d\u6587\"\n}" }, { "in": "WzYxNDQsIC0xLCAxLjUsIDFlMywgMC4xLCAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAsIC0wLCAtMC4wLCAwLjAsIDFFNDAwLCAtMWU0MDAsIDFlLTQwMF0=", diff --git a/internal/root/root_test.go b/internal/root/root_test.go index b9e068ba..c20de622 100644 --- a/internal/root/root_test.go +++ b/internal/root/root_test.go @@ -192,7 +192,7 @@ func TestPaths(t *testing.T) { } } for meta, want := range map[string]string{ - `{"sdkRoot": " C:/emu-src/sdk-mas35/ "}`: `C:\sdk-src\sdk-mas35`, + `{"sdkRoot": " C:/sdk-src/sdk-mas35/ "}`: `C:\sdk-src\sdk-mas35`, `{"sdkRoot": "dev-sdk"}`: d + `\dev-sdk`, `{"sdkRoot": " "}`: "", `{"sdkRoot": 5}`: "", @@ -204,7 +204,7 @@ func TestPaths(t *testing.T) { t.Errorf("%s: LocalSDKRoot %q want %q", meta, got, want) } } - writeFile(t, r.MetadataPath(), []byte(`{"sdkRoot": "C:\\emu-src\\sdk-mas35"}`)) + writeFile(t, r.MetadataPath(), []byte(`{"sdkRoot": "C:\\sdk-src\\sdk-mas35"}`)) if r.AdbExe() != `C:\sdk-src\sdk-mas35\platform-tools\adb.exe` || r.SDK() != d+`\sdk` { t.Errorf("runtime sdk: %s", r.AdbExe()) } From 0fe4117369e1e077621334a639881645e41de30f Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:29:51 +0100 Subject: [PATCH 07/13] =?UTF-8?q?CI=EF=BC=9A=E8=84=9A=E6=9C=AC=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E5=9C=A8=E9=9A=94=E7=A6=BB=E6=A8=A1=E5=BC=8F=E4=B8=8B?= =?UTF-8?q?=E4=B9=9F=E8=83=BD=E5=AF=BC=E5=85=A5=E8=A2=AB=E6=B5=8B=E6=A8=A1?= =?UTF-8?q?=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python -I 不把脚本所在目录放进 sys.path,原来的 -m unittest 写法在 CI 上必然失败。 测试自己把 scripts 目录加进 sys.path,CI 直接运行测试文件。 尾注检查忽略行首空白,git 输出按 UTF-8 读。 --- .github/workflows/ci.yml | 2 +- scripts/repo_checks.py | 7 ++++--- scripts/test_repo_checks.py | 9 +++++++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96c5a872..c7090a4a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,4 +53,4 @@ jobs: } python -B -I -X utf8 scripts/repo_checks.py - name: script tests - run: python -B -I -X utf8 -m unittest scripts/test_repo_checks.py + run: python -B -I -X utf8 scripts/test_repo_checks.py diff --git a/scripts/repo_checks.py b/scripts/repo_checks.py index 33e9a7bc..8a1d933c 100644 --- a/scripts/repo_checks.py +++ b/scripts/repo_checks.py @@ -20,19 +20,20 @@ def allowed(name: str, email: str) -> bool: def commits(base: str, head: str, cwd: str = ".") -> list[str]: spec = f"{base}..{head}" - out = subprocess.check_output(["git", "rev-list", "--no-merges", spec], cwd=cwd, text=True) + out = subprocess.check_output(["git", "rev-list", "--no-merges", spec], cwd=cwd, text=True, encoding="utf-8") return [x for x in out.splitlines() if x] def check_commit(commit: str, cwd: str = ".") -> list[str]: fmt = "%an%x00%ae%x00%B" - raw = subprocess.check_output(["git", "show", "-s", f"--format={fmt}", commit], cwd=cwd, text=True) + raw = subprocess.check_output(["git", "show", "-s", f"--format={fmt}", commit], cwd=cwd, text=True, + encoding="utf-8") name, email, message = raw.split("\x00", 2) errors: list[str] = [] if not allowed(name.strip(), email.strip()): errors.append(f"{commit}: author {name.strip()} <{email.strip()}> is not allowed") for line in message.splitlines(): - if line.lower().startswith("co-authored-by:"): + if line.strip().lower().startswith("co-authored-by:"): value = line.split(":", 1)[1].strip() match = re.fullmatch(r".+ <([^<>]+)>", value) if not match or not allowed(value.rsplit(" <", 1)[0], match.group(1)): diff --git a/scripts/test_repo_checks.py b/scripts/test_repo_checks.py index b9419ef3..4ea0dde7 100644 --- a/scripts/test_repo_checks.py +++ b/scripts/test_repo_checks.py @@ -1,10 +1,13 @@ import os import subprocess +import sys import tempfile import unittest from pathlib import Path -import repo_checks +# CI runs this with python -I, which leaves the script's own directory off sys.path. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import repo_checks # noqa: E402 class RepoChecksTest(unittest.TestCase): @@ -13,6 +16,8 @@ def test_allowed_identities(self): self.assertTrue(repo_checks.allowed("bot", "123+bot[bot]@users.noreply.github.com")) self.assertTrue(repo_checks.allowed("someone", "someone@users.noreply.github.com")) self.assertFalse(repo_checks.allowed("ai", "noreply@openai.com")) + self.assertFalse(repo_checks.allowed("Claude", "noreply@" + "anthropic.com")) + self.assertFalse(repo_checks.allowed("qiyinxi", "someone@example.com")) def test_commit_and_coauthor(self): with tempfile.TemporaryDirectory() as td: @@ -35,7 +40,7 @@ def test_rejects_ai_trailer(self): subprocess.run(["git", "config", "user.email", "qiyinxi@foxmail.com"], cwd=root, check=True) (root / "x").write_text("x") subprocess.run(["git", "add", "x"], cwd=root, check=True) - subprocess.run(["git", "commit", "-qm", "bad\n\nCo-authored-by: bot "], cwd=root, check=True) + subprocess.run(["git", "commit", "-qm", "bad\n\n co-authored-by: bot "], cwd=root, check=True) commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip() self.assertTrue(repo_checks.check_commit(commit, str(root))) From 7dc89488ee093f406fb77aae995b2f1f1a928352 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:32:30 +0100 Subject: [PATCH 08/13] =?UTF-8?q?=E5=8F=91=E7=89=88=EF=BC=9A=E8=8D=89?= =?UTF-8?q?=E7=A8=BF=E5=89=8D=E7=9A=84=E9=87=8D=E5=A4=8D=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=E6=94=BE=E5=88=B0=E5=B8=A6=E4=BB=A4=E7=89=8C=E7=9A=84=E9=82=A3?= =?UTF-8?q?=E4=B8=80=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来 gh release view 在没有 GH_TOKEN 的步骤里跑,出错被吞掉,"已有 Release" 的检查永远不成立;而同一个 tag 可以挂多个草稿。现在在建草稿那一步列出全部 Release(含草稿),tag 已有就失败,列不出来也失败。 - 草稿 job 用 tag 里的 release/<版本>.SHA256SUMS.txt 再核一次产物,并只许有 zip 和 SHA256SUMS.txt 两个文件;加超时。 - upload-artifact、download-artifact 换成当前的官方版本(node24),仍钉 SHA。 - 每个命令都检查退出码;GOTOOLCHAIN=local 放到顶层。 - mkzip:LICENSE、NOTICE 取 git 里的字节,Go 许可取 go env GOROOT,出错时 报错退出而不是 panic。打出的 0.1.0 zip 字节不变。 - 发版说明里的校验文件名改成实际的附件名 SHA256SUMS.txt,README 写明核对和 自己打包的命令。 --- .github/workflows/release.yml | 38 +++++++---- README.md | 13 ++-- internal/tools/mkzip/main.go | 119 +++++++++++++++++++++------------- release/0.1.0.md | 2 +- 4 files changed, 107 insertions(+), 65 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 64087a90..f4a04779 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,9 @@ concurrency: group: release-${{ github.ref_name }} cancel-in-progress: false +env: + GOTOOLCHAIN: local + jobs: build: if: github.repository == 'ModAVD/ModAVDManager' @@ -44,6 +47,7 @@ jobs: $want = (Select-String -LiteralPath 'internal/buildinfo/buildinfo.go' -Pattern 'Version = "([^"]+)"').Matches.Groups[1].Value if ($want -ne $version) { throw "buildinfo.Version=$want, tag=$version" } pwsh -NoProfile -File build.ps1 -Out out + if ($LASTEXITCODE -ne 0) { throw 'build.ps1 failed' } $sums = @{} foreach ($line in Get-Content "release/$version.SHA256SUMS.txt") { if ($line -match '^([0-9a-f]{64}) (.+)$') { $sums[$Matches[2]] = $Matches[1] } } foreach ($name in @('ModAVD.exe', 'tools/modavd.exe')) { @@ -51,14 +55,14 @@ jobs: if ($got -ne $sums[$name]) { throw "$name hash mismatch" } } $zip = "ModAVDManager-$version-win-x64.zip" - $env:GOTOOLCHAIN = 'local' go run ./internal/tools/mkzip -dir out -version $version -out $zip + if ($LASTEXITCODE -ne 0) { throw 'mkzip failed' } $gotZip = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() if ($gotZip -ne $sums[$zip]) { throw 'zip hash mismatch' } New-Item -ItemType Directory -Force artifacts | Out-Null Copy-Item $zip artifacts Copy-Item "release/$version.SHA256SUMS.txt" "artifacts/SHA256SUMS.txt" - - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-assets path: artifacts @@ -67,6 +71,7 @@ jobs: draft: needs: build runs-on: windows-2025 + timeout-minutes: 10 permissions: contents: write steps: @@ -74,7 +79,7 @@ jobs: with: persist-credentials: false fetch-depth: 1 - - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-assets path: artifacts @@ -83,21 +88,28 @@ jobs: env: TAG: ${{ github.ref_name }} run: | + # Checked against the tag's own list, not only the copy that travelled with the artifact. $version = $env:TAG.Substring(1) - $sumPath = "artifacts/SHA256SUMS.txt" - $zip = "artifacts/ModAVDManager-$version-win-x64.zip" - $line = Get-Content $sumPath | Where-Object { $_ -match "^([0-9a-f]{64}) ModAVDManager-$version-win-x64\.zip$" } - $expected = $Matches[1] - $actual = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLowerInvariant() - if ($actual -ne $expected) { throw 'downloaded zip hash mismatch' } - if (gh release view $env:TAG 2>$null) { throw 'release already exists' } + $zip = "ModAVDManager-$version-win-x64.zip" + $sums = Get-Content -Raw "release/$version.SHA256SUMS.txt" + if ((Get-Content -Raw artifacts/SHA256SUMS.txt) -cne $sums) { throw 'artifact SHA256SUMS.txt differs from the tag' } + $have = (Get-ChildItem artifacts -File | ForEach-Object Name | Sort-Object) -join ',' + $expect = (@($zip, 'SHA256SUMS.txt') | Sort-Object) -join ',' + if ($have -cne $expect) { throw "unexpected artifact files: $have" } + $want = [regex]::Match($sums, "(?m)^([0-9a-f]{64}) $([regex]::Escape($zip))$").Groups[1].Value + $got = (Get-FileHash "artifacts/$zip" -Algorithm SHA256).Hash.ToLowerInvariant() + if (-not $want -or $got -ne $want) { throw 'downloaded zip hash mismatch' } - name: create draft shell: pwsh env: TAG: ${{ github.ref_name }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} run: | $version = $env:TAG.Substring(1) - $zip = "artifacts/ModAVDManager-$version-win-x64.zip" - $sumPath = "artifacts/SHA256SUMS.txt" - gh release create $env:TAG --draft --verify-tag --notes-file "release/$version.md" $zip $sumPath + # Drafts are not bound to their tag, so one tag can collect several: list every release, drafts included. + $tags = gh api "repos/$env:GH_REPO/releases?per_page=100" --paginate --jq '.[].tag_name' + if ($LASTEXITCODE -ne 0) { throw 'cannot list releases' } + if ($tags -contains $env:TAG) { throw "a release for $env:TAG already exists (draft or published)" } + gh release create $env:TAG --draft --verify-tag --notes-file "release/$version.md" "artifacts/ModAVDManager-$version-win-x64.zip" artifacts/SHA256SUMS.txt + if ($LASTEXITCODE -ne 0) { throw 'gh release create failed' } diff --git a/README.md b/README.md index 73e1e1db..d3535704 100644 --- a/README.md +++ b/README.md @@ -159,11 +159,14 @@ go test ./... - 有几项测试只读本机 `D:\ModAVD` 下的现成文件(`mas-avd.json`、实例配置、组件 APK),没有就跳过;`MODAVD_TEST_METADATA` 可以另指一份 `mas-avd.json`。 - CI(`.github/workflows/ci.yml`)在 `windows-2025` 上跑格式检查、`go vet`、`go test`、`build.ps1`、隐私扫描和作者检查;只在 PR 或手动触发时运行。 -## 独立下载与哈希 - -v0.1.0 是第一个独立版本。压缩包名为 `ModAVDManager-0.1.0-win-x64.zip`,内容只有两个程序、许可证和清单;压缩包不带顶层目录。下载后核对 `release/0.1.0.SHA256SUMS.txt` 中的两个 exe 与 zip 的 SHA-256。v0.1.0 没有自更新,单独下载的文件需要手动替换;从 v0.2.0 起才提供自更新。 - -自己编译需要 Go 1.26.5、`GOTOOLCHAIN=local`,运行 `build.ps1`。单独使用时必须指定 `--root` 或 `MODAVD_ROOT`,否则程序会提示找不到 ModAVD 根目录。 +## 单独下载与哈希 + +- 每个版本的 GitHub Release 附 `ModAVDManager-<版本>-win-x64.zip` 和 `SHA256SUMS.txt`,后者和仓库里的 `release/<版本>.SHA256SUMS.txt` 是同一份。v0.1.0 是第一个独立版本,两个 exe 和 ModAVD 0.36.0 包里的逐字节相同。 +- zip 没有顶层目录,里面是 `ModAVD.exe`、`tools\modavd.exe`、`LICENSE`、`NOTICE`、`LICENSES\Go-LICENSE.txt`,以及单独下载包的标记 `modavd-manager.json`(版本号和其余各文件的 SHA-256)。 +- 核对:`Get-FileHash .\ModAVDManager-0.1.0-win-x64.zip -Algorithm SHA256`,和 `SHA256SUMS.txt` 里那一行比;解压出的两个 exe 也一样比。 +- 自己编出同样的字节:Go 1.26.5、`GOTOOLCHAIN=local`,`pwsh -NoProfile -File build.ps1 -Out out`,再 `go run ./internal/tools/mkzip -dir out -version <版本>` 打 zip。 +- 单独使用时给 `--root` 或设 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把 zip 解压到 ModAVD 根目录里覆盖包里的那份。 +- v0.1.0 没有自更新,单独下载的要手动换;0.2.0 起才有。 ## 参与 diff --git a/internal/tools/mkzip/main.go b/internal/tools/mkzip/main.go index 64874340..1861c2b6 100644 --- a/internal/tools/mkzip/main.go +++ b/internal/tools/mkzip/main.go @@ -1,19 +1,30 @@ -// Command mkzip creates the deterministic standalone manager archive. +// Command mkzip packs the standalone download ModAVDManager--win-x64.zip from build.ps1's output. Neither +// exe imports it. The archive is reproducible: entries sorted by name, stored (no compression, so no zlib version +// can change the bytes), no directory entries, fixed time and mode. +// +// go run ./internal/tools/mkzip -dir out -version 0.1.0 -out ModAVDManager-0.1.0-win-x64.zip +// +// LICENSE and NOTICE are the committed bytes (git cat-file at -rev), LICENSES/Go-LICENSE.txt is $(go env GOROOT)\LICENSE +// (the Go standard library is BSD-3-Clause, whose text must go with the binaries), and modavd-manager.json marks the +// standalone download for the updater: version and SHA-256 of every other entry. package main import ( "archive/zip" + "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "flag" "fmt" - "io" "os" + "os/exec" "path/filepath" - "runtime" "sort" + "strings" "time" + + "modavd/internal/buildinfo" ) type manifest struct { @@ -27,80 +38,96 @@ func digest(data []byte) string { } func main() { - dir := flag.String("dir", "out", "build output directory") - version := flag.String("version", "0.1.0", "manager version") - out := flag.String("out", "", "zip path") + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "mkzip:", err) + os.Exit(1) + } +} + +func run() error { + dir := flag.String("dir", "out", "build.ps1 output directory") + version := flag.String("version", buildinfo.Version, "manager version") + out := flag.String("out", "", "zip path (default ModAVDManager--win-x64.zip)") + rev := flag.String("rev", "HEAD", "commit that LICENSE and NOTICE are taken from") flag.Parse() if *out == "" { *out = fmt.Sprintf("ModAVDManager-%s-win-x64.zip", *version) } - goRoot := runtime.GOROOT() - files := map[string]string{ - "ModAVD.exe": filepath.Join(*dir, "ModAVD.exe"), - "tools/modavd.exe": filepath.Join(*dir, "tools", "modavd.exe"), - "LICENSE": "LICENSE", - "NOTICE": "NOTICE", - "LICENSES/Go-LICENSE.txt": filepath.Join(goRoot, "LICENSE"), - } - data := make(map[string][]byte, len(files)+1) - hashes := make(map[string]string, len(files)) - for name, path := range files { + + data := map[string][]byte{} + for name, path := range map[string]string{ + "ModAVD.exe": filepath.Join(*dir, "ModAVD.exe"), + "tools/modavd.exe": filepath.Join(*dir, "tools", "modavd.exe"), + } { b, err := os.ReadFile(path) if err != nil { - panic(err) + return err } data[name] = b + } + for _, name := range []string{"LICENSE", "NOTICE"} { + b, err := output("git", "cat-file", "blob", *rev+":"+name) + if err != nil { + return fmt.Errorf("%s at %s: %w", name, *rev, err) + } + data[name] = b + } + goroot, err := output("go", "env", "GOROOT") + if err != nil { + return fmt.Errorf("go env GOROOT: %w", err) + } + if data["LICENSES/Go-LICENSE.txt"], err = os.ReadFile(filepath.Join(strings.TrimSpace(string(goroot)), "LICENSE")); err != nil { + return err + } + + hashes := make(map[string]string, len(data)) + for name, b := range data { hashes[name] = digest(b) } - manifestBytes, err := json.Marshal(manifest{Version: *version, Files: hashes}) + mb, err := json.Marshal(manifest{Version: *version, Files: hashes}) if err != nil { - panic(err) + return err } - data["modavd-manager.json"] = append(manifestBytes, '\n') + data["modavd-manager.json"] = append(mb, '\n') names := make([]string, 0, len(data)) for name := range data { names = append(names, name) } sort.Strings(names) - if err := os.MkdirAll(filepath.Dir(filepath.Clean(*out)), 0o755); err != nil && filepath.Dir(filepath.Clean(*out)) != "." { - panic(err) - } - f, err := os.Create(*out) - if err != nil { - panic(err) - } - zw := zip.NewWriter(f) + var buf bytes.Buffer + zw := zip.NewWriter(&buf) epoch := time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC) for _, name := range names { h := &zip.FileHeader{Name: name, Method: zip.Store, Modified: epoch} h.SetMode(0o644) w, err := zw.CreateHeader(h) if err != nil { - panic(err) + return err } - if _, err := io.Copy(w, &byteReader{data: data[name]}); err != nil { - panic(err) + if _, err := w.Write(data[name]); err != nil { + return err } } if err := zw.Close(); err != nil { - panic(err) + return err } - if err := f.Close(); err != nil { - panic(err) + if d := filepath.Dir(*out); d != "." { + if err := os.MkdirAll(d, 0o755); err != nil { + return err + } } + return os.WriteFile(*out, buf.Bytes(), 0o644) } -type byteReader struct { - data []byte - pos int -} - -func (r *byteReader) Read(p []byte) (int, error) { - if r.pos == len(r.data) { - return 0, io.EOF +// output runs a command and returns its stdout; stderr goes into the error. +func output(name string, args ...string) ([]byte, error) { + var stderr bytes.Buffer + cmd := exec.Command(name, args...) + cmd.Stderr = &stderr + b, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("%v: %s", err, strings.TrimSpace(stderr.String())) } - n := copy(p, r.data[r.pos:]) - r.pos += n - return n, nil + return b, nil } diff --git a/release/0.1.0.md b/release/0.1.0.md index c1c90ad1..3b4690f4 100644 --- a/release/0.1.0.md +++ b/release/0.1.0.md @@ -5,6 +5,6 @@ - `ModAVD.exe`:`3331b658a9f3a000091f4bda6ed13298e11eceee9962c1ce22e1bcfbccc4d65b` - `tools/modavd.exe`:`90cb0d9ad05b366144202600d38e6d1341a5b9e20b152a7fbe20a220d558723d` -使用 Go 1.26.5、`GOTOOLCHAIN=local`,运行仓库中的 `build.ps1` 可以编出相同字节。单独下载包还包含 Go 许可原文和文件清单;请用 `0.1.0.SHA256SUMS.txt` 核对两个 exe 与 zip。 +使用 Go 1.26.5、`GOTOOLCHAIN=local`,运行仓库中的 `build.ps1` 可以编出相同字节。单独下载包还包含 Go 许可原文和文件清单;请用附件 `SHA256SUMS.txt` 核对 zip 和解压出的两个 exe,例如在 PowerShell 里运行 `Get-FileHash .\ModAVDManager-0.1.0-win-x64.zip -Algorithm SHA256`。 0.1.0 没有自更新,单独下载的文件需要手动替换。从 0.2.0 起才提供自更新。单独使用时请给 `--root` 或设置 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把单独下载的 zip 解压到 ModAVD 根目录覆盖整包中的文件。 From 80c7903c8a796f1794cbec59d480a3e14b109149 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:38:16 +0100 Subject: [PATCH 09/13] =?UTF-8?q?=E4=BF=AE=E5=A5=BD=20bridge=20install=20?= =?UTF-8?q?=E7=9A=84=E5=9B=9E=E5=BD=92=EF=BC=8C=E6=89=A7=E8=A1=8C=E6=A1=A5?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E5=8F=AA=E9=97=AE=E5=BC=80=E5=AE=8C=E6=9C=BA?= =?UTF-8?q?=E7=9A=84=E5=AE=A2=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bridge install 又能装上桥:持有桥锁的 Bridge() 把"锁已在手"交给这次开机, 开机里直接装(installBridge),不再去抢同一把锁。之前改成 NoBridge 开机, 对没桥的实例只会开机关机,报"开机后没装上执行桥"。 - info / list / status 的 bridge:开机标记在桥装好后一直留着,"有标记就是 pending"不对。现在只问已开完机的客体(getprop 限 5 秒,原来是 30 秒); 关着或还在开机时,没有标记、或首次开机还没做的是 pending,其余是 unknown。 - jsonord 对照数据用 gen_pycases.py 重新生成:之前只改了 out,in 还是旧路径, TestAgainstPython 失败。 - 客体脚本头注释:vulkanfix.sh 改断的句子接好,cpuinfo-bind.sh 不用弯引号, mas-wifi-fastpath.sh 去掉多余的话。guest.go 头注释写回"两边一起改"。 - 依赖本机文件的两个测试改用 MODAVD_TEST_SDK、MODAVD_TEST_VKLIBS 指路径,不再 写死一个不存在的目录而悄悄跳过。 - 补单元测试:桥锁期间 status 报 bridging、bridge 和 delete 报忙、删除后不留 桥锁文件;关机实例的 bridge 取值;started_at_ms;/sdcard 等待的轮询; LocalFile 读到被占用的文件时重试。 - README 写明 bridge 各取值和 bridging,去掉末尾空行。 --- README.md | 8 ++- internal/adb/real_adb_test.go | 9 ++-- internal/emu/bridge.go | 14 +++++- internal/emu/bridge_test.go | 55 +++++++++++++++++++++ internal/emu/start.go | 23 ++++++--- internal/emu/start_test.go | 24 +++++++++ internal/emu/status.go | 38 ++++++++++---- internal/emu/status_test.go | 53 +++++++++++++++++++- internal/emu/types.go | 20 +++++--- internal/guest/guest.go | 2 +- internal/guest/readstable_windows_test.go | 54 ++++++++++++++++++++ internal/guest/scripts/cpuinfo-bind.sh | 2 +- internal/guest/scripts/mas-wifi-fastpath.sh | 2 +- internal/guest/scripts/vulkanfix.sh | 4 +- internal/jsonord/testdata/pycases.json | 2 +- internal/vkfix/vkfix_test.go | 10 ++-- 16 files changed, 275 insertions(+), 45 deletions(-) create mode 100644 internal/emu/bridge_test.go create mode 100644 internal/guest/readstable_windows_test.go diff --git a/README.md b/README.md index a8c1afcb..d94ecb18 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,8 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] - modavd(命令行、MCP)和管理器每次开机都会看一眼:实例还没有桥,就在开机后的设置做完后装上,中间关机再冷启动一两次。只在这次是它拉起的模拟器时装;接管已经在运行的实例时不装。装不上只是警告,实例照常运行,下次开机再试。 - 不要桥的实例:新建时带 `--no-bridge`,或者之后跑 `bridge uninstall`。两种都会在 `mas-avd.json` 里记下 `instances..bridge` 为 `false`,以后开机不再自动装;再 `bridge install` 就恢复。`start` / `restart` 的 `--no-bridge` 只管这一次。 - `bridge` 调用 ModAVD 包里的 `tools\modavd-bridge.ps1`。`install`:需要时关机再开机,装上;已经装了的只在载荷有变时更新。`uninstall`:卸掉桥、开机标记和装桥时改成的 GL 传输方式(asg);退回更早的版本之前要先卸。实例原来关着的,做完再关掉。`verify`:只读核对,实例要开着。 -- `info` / `list` 的 `bridge` 为 `off`、`pending`、`installed` 或 `unknown`;关机时不能查询客体属性,因此没有“不装”记录且没有待装标记时显示 `unknown`。装桥期间 `busy` 为 `bridging`,删除也会持有同一把桥锁。 +- `info` / `list` / `status` 的 `bridge`:`off`(记了不要桥)、`pending`(下次由 modavd 拉起的开机会装)、`installed`(开着的客体里桥在)、`unknown`。只问已经开完机的客体;关着或还在开机的实例,开机标记在桥装好后一直留着,装失败时也在,所以首次开机做过、标记也在时是 `unknown`,要知道确切结果就开机后再查。 +- 装桥期间(含其中的关机、冷启动)`busy` 为 `bridging`;这时 `delete`、再次 `bridge` 返回实例忙(退出码 5)。调用方不认识的 `busy` 取值一律当忙处理。 - 不经 modavd 或管理器开机的实例(别的程序直接拉起模拟器)不会自动装,要装就跑一次 `bridge install`。 **机读输出**(`--json`): @@ -158,7 +159,7 @@ go test ./... | `MODAVD_TEST_LIVE` | 设成 `1` 才跑碰真实环境的测试:看本机正在运行的模拟器、起真的 adb server。会碰到本机正在用的实例,平时不要设。 | - `internal/avd`、`internal/root`、`internal/jsonord` 有一部分测试用 Python 3 运行 AUTO-MAS 的原始逻辑(如 `internal/avd/testdata/instances_ref.py`),和 Go 的输出逐字节对照,所以要装 Python 3。 -- 有几项测试只读本机 `D:\ModAVD` 下的现成文件(`mas-avd.json`、实例配置、组件 APK),没有就跳过;`MODAVD_TEST_METADATA` 可以另指一份 `mas-avd.json`。 +- 有几项测试只读本机 `D:\ModAVD` 下的现成文件(`mas-avd.json`、实例配置、组件 APK),没有就跳过;`MODAVD_TEST_METADATA` 可以另指一份 `mas-avd.json`,`MODAVD_TEST_SDK` 另指一个带 `platform-tools\adb.exe` 的 SDK,`MODAVD_TEST_VKLIBS` 指向放着原版和打过补丁的 `libvulkan_enc.so` 的目录(Vulkan 修复的逐字节对照)。 - CI(`.github/workflows/ci.yml`)在 `windows-2025` 上跑格式检查、`go vet`、`go test`、`build.ps1`、隐私扫描和作者检查;只在 PR 或手动触发时运行。 ## 单独下载与哈希 @@ -185,6 +186,3 @@ go test ./... - 程序图标(`cmd/modavd-gui/modavd.ico`、`cmd/modavd-gui/rsrc_windows_amd64.syso`、`internal/ui/web/assets/` 下的图片)是《明日方舟》艾雅法拉的同人图,角色版权归上海鹰角网络所有,不在本仓库的许可范围内; - `internal/avd/testdata/instances_ref.py` 复制自 AUTO-MAS(AGPL-3.0-or-later),只供测试、在单独的进程里运行,不编进程序。 - 编出的 exe 含 Go 标准库和运行时(BSD-3-Clause)。 - - - diff --git a/internal/adb/real_adb_test.go b/internal/adb/real_adb_test.go index e4427d76..75a1797e 100644 --- a/internal/adb/real_adb_test.go +++ b/internal/adb/real_adb_test.go @@ -31,9 +31,12 @@ const ( testScriptPort = 20076 ) -// testSDK is an SDK whose adb.exe the test may run (only run, never modified). +// testSDK is an SDK whose adb.exe the test may run (only run, never modified): $MODAVD_TEST_SDK, else the package's. func testSDK() string { - for _, sdk := range []string{`C:\sdk-src\sdk-mas35`, `D:\ModAVD\sdk`} { + for _, sdk := range []string{os.Getenv("MODAVD_TEST_SDK"), `D:\ModAVD\sdk`} { + if sdk == "" { + continue + } if st, err := os.Stat(filepath.Join(sdk, "platform-tools", "adb.exe")); err == nil && !st.IsDir() { return sdk } @@ -47,7 +50,7 @@ func realRoot(t *testing.T) (*root.Root, string) { t.Helper() sdk := testSDK() if sdk == "" { - t.Skip("没有可用的 adb.exe(C:\\sdk-src\\sdk-mas35 / D:\\ModAVD\\sdk)") + t.Skip("没有可用的 adb.exe(MODAVD_TEST_SDK / D:\\ModAVD\\sdk)") } dir := tempDir(t) meta, _ := json.Marshal(map[string]any{ diff --git a/internal/emu/bridge.go b/internal/emu/bridge.go index 5602107d..ae813998 100644 --- a/internal/emu/bridge.go +++ b/internal/emu/bridge.go @@ -104,7 +104,12 @@ func writeBridgeMarker(r *root.Root, i int) error { // guestBridge is the booted guest's ro.dalvik.vm.native.bridge ("" when adb did not answer). func (m *Manager) guestBridge(ctx context.Context, i int) string { - res := m.shell(ctx, i, "getprop ro.dalvik.vm.native.bridge", 0) + return m.guestBridgeWithin(ctx, i, 0) +} + +// guestBridgeWithin is guestBridge with an adb timeout (0: m.shell's default). +func (m *Manager) guestBridgeWithin(ctx context.Context, i int, timeout time.Duration) string { + res := m.shell(ctx, i, "getprop ro.dalvik.vm.native.bridge", timeout) if res.Code != 0 { return "" } @@ -198,7 +203,11 @@ func (m *Manager) finishBridge(ctx context.Context, i int, opt StartOptions, res return res, nil } defer lock.Unlock() + return m.installBridge(ctx, i, opt, res) +} +// installBridge is finishBridge with the bridge lock already held by the caller. +func (m *Manager) installBridge(ctx context.Context, i int, opt StartOptions, res *StartResult) (*StartResult, error) { // The script's notes go to this log; the warnings of the cold boots come with their results (m, not mm, starts them). col := &logx.Collector{} mm := m.withLog(col.Sink()) @@ -330,7 +339,8 @@ func (m *Manager) Bridge(ctx context.Context, i int, action string) (*BridgeResu res.Restarted = true } if !wasRunning || res.Restarted { - sr, err := m.Start(ctx, i, StartOptions{NoBridge: true}) + // this start installs (installBridge, under the lock held above) + sr, err := m.Start(ctx, i, StartOptions{bridgeLocked: true}) if err != nil { return nil, err } diff --git a/internal/emu/bridge_test.go b/internal/emu/bridge_test.go new file mode 100644 index 00000000..04bda277 --- /dev/null +++ b/internal/emu/bridge_test.go @@ -0,0 +1,55 @@ +//go:build windows + +package emu + +import ( + "context" + "strings" + "testing" + + "modavd/internal/errs" + "modavd/internal/win" +) + +// TestBridgeLockExcludes: while some process holds an instance's bridge lock (an install, with its stops and cold +// boots), status says busy "bridging", a second bridge action and a delete are refused as busy, and the delete that +// runs afterwards removes the lock file with the others. +func TestBridgeLockExcludes(t *testing.T) { + m, _ := opsTestManager(t) + ctx := context.Background() + i := 6 + _, err := m.Create(ctx, CreateRequest{Index: &i}) + opsSkipIfNotImplemented(t, err) + if err != nil { + t.Fatal(err) + } + l, ok, err := win.TryLock(m.lockPath(i, "bridge")) + if err != nil || !ok { + t.Fatalf("TryLock: %v %v", ok, err) + } + info, err := m.Info(ctx, i) + if err != nil || info.Busy != "bridging" { + l.Unlock() + t.Fatalf("busy = %q, %v", info.Busy, err) + } + for _, action := range []string{"install", "uninstall", "verify"} { + if _, err := m.Bridge(ctx, i, action); errs.CodeOf(err) != errs.Busy { + l.Unlock() + t.Fatalf("bridge %s while bridging: %v", action, err) + } + } + if _, err := m.Delete(ctx, i); errs.CodeOf(err) != errs.Busy || !strings.Contains(err.Error(), "正在装执行桥") { + l.Unlock() + t.Fatalf("delete while bridging: %v", err) + } + l.Unlock() + + if _, err := m.Delete(ctx, i); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"start", "stop", "bridge"} { + if fileOrDirExists(m.lockPath(i, kind)) { + t.Errorf("%s lock file left after delete", kind) + } + } +} diff --git a/internal/emu/start.go b/internal/emu/start.go index 0ad5f9cd..32ca7688 100644 --- a/internal/emu/start.go +++ b/internal/emu/start.go @@ -105,6 +105,9 @@ func (m *Manager) Start(ctx context.Context, i int, opt StartOptions) (*StartRes // whole setup, because installing takes a cold boot or two; and only on a boot this start launched, never on a // running instance it adopted (someone may be playing on it: the install restarts adbd and boots it cold). if bridge && res.Launched && m.bridgePending(ctx, i) { + if opt.bridgeLocked { + return m.installBridge(ctx, i, opt, res) + } return m.finishBridge(ctx, i, opt, res) } return res, nil @@ -334,19 +337,23 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption // waitSDCard covers the short interval after sys.boot_completed in which vold has not mounted shared storage yet. // A timeout is only a warning: the emulator is usable and a later start/status call can observe the mount. func (m *Manager) waitSDCard(ctx context.Context, i int) bool { - deadline := time.Now().Add(sdcardMountWait) + return pollUntil(ctx, sdcardMountWait, 500*time.Millisecond, func() bool { + return m.shell(ctx, i, "test -d /sdcard && test -r /sdcard && test -w /sdcard", statusAdbTimeout).Code == 0 + }) +} + +// pollUntil calls ok (at least once) every interval until it returns true (true), limit has passed or ctx ends +// (false). +func pollUntil(ctx context.Context, limit, every time.Duration, ok func() bool) bool { + deadline := time.Now().Add(limit) for { - if err := ctxErr(ctx); err != nil { + if ctx.Err() != nil { return false } - res := m.shell(ctx, i, "test -d /sdcard && test -r /sdcard && test -w /sdcard", statusAdbTimeout) - if res.Code == 0 { + if ok() { return true } - if !time.Now().Before(deadline) { - return false - } - if !sleepOrDone(ctx, 500*time.Millisecond) { + if !time.Now().Before(deadline) || !sleepOrDone(ctx, every) { return false } } diff --git a/internal/emu/start_test.go b/internal/emu/start_test.go index 241a4322..3939e77d 100644 --- a/internal/emu/start_test.go +++ b/internal/emu/start_test.go @@ -425,3 +425,27 @@ func TestSleepOrDone(t *testing.T) { t.Errorf("ctxErr = %v", err) } } + +// TestPollUntil: the /sdcard wait's loop. Stops at the first true; gives up after its limit (a timeout is only a +// warning for start); a canceled start does not probe at all. +func TestPollUntil(t *testing.T) { + ctx := context.Background() + n := 0 + if !pollUntil(ctx, time.Second, time.Millisecond, func() bool { n++; return n == 3 }) || n != 3 { + t.Fatalf("true on the third probe: n = %d", n) + } + n = 0 + t0 := time.Now() + if pollUntil(ctx, 30*time.Millisecond, 5*time.Millisecond, func() bool { n++; return false }) { + t.Fatal("never true, yet reported true") + } + if d := time.Since(t0); d < 30*time.Millisecond || d > 2*time.Second || n < 2 { + t.Fatalf("gave up after %v and %d probes", d, n) + } + cctx, cancel := context.WithCancel(ctx) + cancel() + n = 0 + if pollUntil(cctx, time.Second, time.Millisecond, func() bool { n++; return true }) || n != 0 { + t.Fatalf("canceled: probed %d times", n) + } +} diff --git a/internal/emu/status.go b/internal/emu/status.go index 2c4b7935..6243c0ea 100644 --- a/internal/emu/status.go +++ b/internal/emu/status.go @@ -143,7 +143,6 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *win.Pro } info.Status = statusOf(info.Running, info.Booted) info.Busy = busyOf(m.stopping(i), m.lockHeld(i, "start"), m.lockHeld(i, "bridge")) - info.Bridge = m.bridgeState(ctx, i, info.Running) cfg := InstanceConfig{MemoryMB: avd.MemoryFor(m.Root, i), FPS: in.FPS()} if n, ok := in.CPU(); ok { @@ -161,6 +160,7 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *win.Pro info.Renderer = metaText(meta.Get("renderer")) info.SoftwareRenderer = metaTruthy(meta.Get("softwareRenderer")) } + info.Bridge = m.bridgeState(ctx, i, info.Booted, info.Initialized) return info } @@ -177,7 +177,8 @@ func statusOf(running, booted bool) Status { } } -// busyOf: a stop that runs wins over a start (a stop does not wait for a start, and ends it). +// busyOf: a stop that runs wins over a start (a stop does not wait for a start, and ends it). The bridge install +// wins over both: it stops and starts the instance itself, a cold boot or two, while holding the bridge lock. func busyOf(stopping, starting, bridging bool) string { switch { case bridging: @@ -191,17 +192,36 @@ func busyOf(stopping, starting, bridging bool) string { } } -func (m *Manager) bridgeState(ctx context.Context, i int, running bool) string { +// Bridge states (InstanceInfo.Bridge). +const ( + bridgeStateOff = "off" // instances..bridge is false: no start installs it + bridgeStatePending = "pending" // wanted and not there yet: the next start modavd launches installs it + bridgeStateInstalled = "installed" // the booted guest runs it + bridgeStateUnknown = "unknown" // off or still booting with the marker: installed, or not yet (see bridgeState) +) + +// bridgeState is InstanceInfo.Bridge. Only a booted guest tells installed from not (one getprop, statusAdbTimeout). +// The boot marker stays for as long as the bridge is installed (it keeps the system writable), so on an instance that +// is off or still booting the marker alone means "installed, or the last install failed": unknown. Pending there is +// what a start would install for sure: no marker yet (it places one first), or the marker of an instance whose first +// boot (which comes before the install) has not run. +func (m *Manager) bridgeState(ctx context.Context, i int, booted, initialized bool) string { if !m.bridgeWanted(i) { - return "off" + return bridgeStateOff } - if regularFile(bridgeMarker(m.Root, i)) { - return "pending" + if booted { + switch b := m.guestBridgeWithin(ctx, i, statusAdbTimeout); { + case b == bridgeProp: + return bridgeStateInstalled + case b != "": + return bridgeStatePending + } + return bridgeStateUnknown } - if running && m.guestBridge(ctx, i) == bridgeProp { - return "installed" + if !regularFile(bridgeMarker(m.Root, i)) || !initialized { + return bridgeStatePending } - return "unknown" + return bridgeStateUnknown } // lockHeld: some process (this one included: the lock is per handle) holds lock kind of instance i right now. diff --git a/internal/emu/status_test.go b/internal/emu/status_test.go index 24647b27..fb1d617a 100644 --- a/internal/emu/status_test.go +++ b/internal/emu/status_test.go @@ -3,12 +3,15 @@ package emu import ( + "context" "os" "path/filepath" "testing" + "time" "modavd/internal/errs" "modavd/internal/jsonord" + "modavd/internal/win" ) func TestStatusOfAndBusyOf(t *testing.T) { @@ -18,11 +21,59 @@ func TestStatusOfAndBusyOf(t *testing.T) { if statusOf(true, false) != StatusStarting || statusOf(true, true) != StatusOnline { t.Fatal("qemu: starting until booted") } - if busyOf(false, false, false) != "" || busyOf(false, true, false) != "starting" || busyOf(true, false, false) != "stopping" || busyOf(true, true, false) != "stopping" || busyOf(false, false, true) != "bridging" { + if busyOf(false, false, false) != "" || busyOf(false, true, false) != "starting" || busyOf(true, false, false) != "stopping" || + busyOf(true, true, false) != "stopping" || busyOf(false, false, true) != "bridging" || busyOf(true, true, true) != "bridging" { t.Fatal("busyOf") } } +// TestBridgeStateWithoutGuest: what info / list say about the bridge of an instance that is off or still booting +// (no guest to ask). Only a turned-off bridge is certain; the marker, which stays while the bridge is installed, +// means unknown once the first boot has run. +func TestBridgeStateWithoutGuest(t *testing.T) { + r := managerTestRoot(t, 1) + m := New(r, nil) + ctx := context.Background() + check := func(label string, initialized bool, want string) { + t.Helper() + if got := m.bridgeState(ctx, 1, false, initialized); got != want { + t.Errorf("%s: bridge = %q, want %q", label, got, want) + } + } + check("no marker", false, "pending") + check("no marker, first boot done elsewhere", true, "pending") + if err := writeBridgeMarker(r, 1); err != nil { + t.Fatal(err) + } + check("marker, first boot not run", false, "pending") + check("marker after the first boot", true, "unknown") + if err := m.setBridgeWanted(1, false); err != nil { + t.Fatal(err) + } + check("turned off", true, "off") + check("turned off before the first boot", false, "off") +} + +// TestInstanceInfoStartedAtMS: started_at_ms is started_at's moment in Unix milliseconds; both empty when off. +func TestInstanceInfoStartedAtMS(t *testing.T) { + m := New(managerTestRoot(t, 1), nil) + in, err := m.instance(1) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + at := time.Date(2026, 10, 28, 15, 4, 5, 123_000_000, time.Local) + booted := false + info := m.instanceInfo(ctx, in, &win.Process{PID: 4242, Created: filetimeOf(at)}, &booted) + if info.StartedAtMS != at.UnixMilli() || info.StartedAt != at.Format(time.RFC3339) || info.PID != 4242 { + t.Fatalf("running: started_at %q, started_at_ms %d (want %d)", info.StartedAt, info.StartedAtMS, at.UnixMilli()) + } + off := m.instanceInfo(ctx, in, nil, nil) + if off.StartedAtMS != 0 || off.StartedAt != "" || off.Bridge != "pending" { + t.Fatalf("off: %+v", off) + } +} + func TestMetaTruthy(t *testing.T) { v, err := jsonord.Parse([]byte(`{"t":true,"f":false,"one":1,"zero":0,"fz":0.0,"fx":0.5,"s":"x","e":"","a":[1],"ea":[],"o":{"k":1},"eo":{},"n":null}`)) if errs.CodeOf(err) == errs.NotImplemented { diff --git a/internal/emu/types.go b/internal/emu/types.go index 1213ccc3..76c5f9cc 100644 --- a/internal/emu/types.go +++ b/internal/emu/types.go @@ -48,17 +48,20 @@ type InstanceInfo struct { Status Status `json:"status"` Running bool `json:"running"` // qemu process exists (MuMuManager is_process_started) Booted bool `json:"booted"` // Android finished booting (MuMuManager is_android_started) - // Busy: "starting" / "stopping" while some modavd process holds that lock of the instance (AUTO-MAS's updater - // must not swap sdk\emulator then); "" otherwise. + // Busy: "starting" / "stopping" / "bridging" while some modavd process holds that lock of the instance (AUTO-MAS's + // updater must not swap sdk\emulator then); "" otherwise. "bridging" covers the whole bridge install, including the + // stops and cold boots in it; callers that do not know a value treat it as busy. Busy string `json:"busy"` - // Bridge is off (disabled), pending (marker requests install), installed, or unknown (the instance is off or - // the guest did not answer). An offline instance is unknown when its marker is absent because the guest property - // cannot be queried; only an explicit off setting is definitive. + // Bridge (the arm64 execution bridge): "off" (instances..bridge is false), "pending" (the next start modavd + // launches installs it), "installed" (the booted guest runs it) or "unknown". Only a booted guest is asked; an + // instance that is off or still booting and has the bridge's boot marker after its first boot reads unknown, since + // the marker stays while the bridge is installed and also after a failed install. Bridge string `json:"bridge"` PID int `json:"pid"` // StartedAt is the qemu process start, local time RFC 3339 ("2026-10-28T15:04:05+01:00"). - StartedAt string `json:"started_at"` - StartedAtMS int64 `json:"started_at_ms"` + StartedAt string `json:"started_at"` + // StartedAtMS is the same moment in Unix milliseconds; 0 when not running. + StartedAtMS int64 `json:"started_at_ms"` // Serial is the device on the private adb server (adb -P -s ). Scripts that use their own // adb server connect to AdbAddress instead. Serial string `json:"serial"` @@ -139,6 +142,9 @@ type StartOptions struct { // NoBridge: do not install the execution bridge on this boot even when its marker is there and the bridge is not // (bridge.go), the way AUTO-MAS boots. Bridge starts with it to uninstall. NoBridge bool + // bridgeLocked: the caller (Bridge) holds the instance's bridge lock, so the install step runs under it instead of + // taking it (the lock is per handle: a second TryLock in the same process fails). + bridgeLocked bool } type Progress struct { diff --git a/internal/guest/guest.go b/internal/guest/guest.go index db630030..d0d67dbe 100644 --- a/internal/guest/guest.go +++ b/internal/guest/guest.go @@ -1,5 +1,5 @@ // Package guest holds the scripts modavd pushes into the guest after boot. They are copies of AUTO-MAS -// res/avd/guest/*.sh (the product versions). Keep these shared scripts in sync with the companion launcher. +// res/avd/guest/*.sh (the product versions). Until AUTO-MAS calls modavd for booting, changes go into both places. package guest import ( diff --git a/internal/guest/readstable_windows_test.go b/internal/guest/readstable_windows_test.go new file mode 100644 index 00000000..e48302cd --- /dev/null +++ b/internal/guest/readstable_windows_test.go @@ -0,0 +1,54 @@ +package guest + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +// TestReadStableWaitsForSharingViolation: a file another handle holds without read sharing (a writer that has just +// moved it into place) is read once that handle is closed, not reported as ERROR_SHARING_VIOLATION. +func TestReadStableWaitsForSharingViolation(t *testing.T) { + path := filepath.Join(t.TempDir(), "held.sh") + if err := os.WriteFile(path, []byte("payload"), 0o644); err != nil { + t.Fatal(err) + } + p, err := syscall.UTF16PtrFromString(path) + if err != nil { + t.Fatal(err) + } + h, err := syscall.CreateFile(p, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, + syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + t.Fatal(err) + } + if _, err := os.ReadFile(path); !sharingViolation(err) { + syscall.CloseHandle(h) + t.Fatalf("held file: want a sharing violation, got %v", err) + } + go func() { + time.Sleep(200 * time.Millisecond) + syscall.CloseHandle(h) + }() + t0 := time.Now() + b, err := readStable(path) + if err != nil || string(b) != "payload" { + t.Fatalf("readStable = %q, %v", b, err) + } + if d := time.Since(t0); d < 150*time.Millisecond { + t.Errorf("returned after %v, before the handle was closed", d) + } + + // Other errors are not retried. + t0 = time.Now() + if _, err := readStable(filepath.Join(t.TempDir(), "missing.sh")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("missing: %v", err) + } + if d := time.Since(t0); d > 40*time.Millisecond { + t.Errorf("missing file retried for %v", d) + } +} diff --git a/internal/guest/scripts/cpuinfo-bind.sh b/internal/guest/scripts/cpuinfo-bind.sh index 4997cee6..6b35a21f 100644 --- a/internal/guest/scripts/cpuinfo-bind.sh +++ b/internal/guest/scripts/cpuinfo-bind.sh @@ -1,6 +1,6 @@ #!/system/bin/sh # cpuinfo-bind.sh - one cpuinfo entry per real vCPU for the ARM translation layer. Run as root (su 0 sh ...). -# Keep this text in sync with the launcher’s embedded guest script. +# Same text as the inline script in the launcher; keep the two in sync. # # ARM games run through libndk_translation, which answers their /proc/cpuinfo from # /system/etc/cpuinfo.{arm64,arm}.txt: a single "processor : 1" entry. Unity then reports diff --git a/internal/guest/scripts/mas-wifi-fastpath.sh b/internal/guest/scripts/mas-wifi-fastpath.sh index 5f3a396d..6e61591b 100644 --- a/internal/guest/scripts/mas-wifi-fastpath.sh +++ b/internal/guest/scripts/mas-wifi-fastpath.sh @@ -2,7 +2,7 @@ # mas-wifi-fastpath.sh - guest sees Wi-Fi, bulk data goes over eth0. Run as root # (adb root + adb shell, or adb shell su 0 sh ...). Same text is embedded in # external/qemu android/android-emu/android/network/wifi.cpp (-wifi-fastpath); -# keep the two in sync. The simulator's embedded wifi implementation must be updated alongside this script. +# keep the two in sync. # # on apply once (idempotent) # daemon start "watch" in the background unless already running diff --git a/internal/guest/scripts/vulkanfix.sh b/internal/guest/scripts/vulkanfix.sh index 38847979..1e1b2594 100644 --- a/internal/guest/scripts/vulkanfix.sh +++ b/internal/guest/scripts/vulkanfix.sh @@ -1,7 +1,7 @@ #!/system/bin/sh # vulkanfix.sh - bind-mount the patched guest Vulkan encoder (bindlock2, includes -# khrfix) over the image's own and restart zygote (it preloads the driver). Run as root (su 0 sh ...). Same steps as -# The launcher carries the same Vulkan fix text; the patch itself is made on the host from the image's own library +# khrfix) over the image's own and restart zygote (it preloads the driver). Run as root (su 0 sh ...). The launcher's +# Vulkan fix runs the same steps; the patch itself is made on the host from the image's own library # (app/utils/common/emulator2/avd/vulkanfix.py), the patched file is never shipped. # # The patched copy stays in /data/local/tmp as a cache: the next boot mounts it again without a new upload. It is diff --git a/internal/jsonord/testdata/pycases.json b/internal/jsonord/testdata/pycases.json index 4721fe67..4d3f4b9b 100644 --- a/internal/jsonord/testdata/pycases.json +++ b/internal/jsonord/testdata/pycases.json @@ -29,7 +29,7 @@ "out": "\"a\\\"b\\\\c/d\"" }, { -"in": "eyJxIjogInNheSBcImhpXCIiLCAicCI6ICJDOlxcZW11LXNyY1xcc2RrLW1hczM1XFwiLCAidSI6ICJcdTRlMmRcdTY1ODcifQ==", +"in": "eyJxIjogInNheSBcImhpXCIiLCAicCI6ICJDOlxcc2RrLXNyY1xcc2RrLW1hczM1XFwiLCAidSI6ICJcdTRlMmRcdTY1ODcifQ==", "out": "{\n \"q\": \"say \\\"hi\\\"\",\n \"p\": \"C:\\\\sdk-src\\\\sdk-mas35\\\\\",\n \"u\": \"\u4e2d\u6587\"\n}" }, { diff --git a/internal/vkfix/vkfix_test.go b/internal/vkfix/vkfix_test.go index 3a4ca867..ff4f450b 100644 --- a/internal/vkfix/vkfix_test.go +++ b/internal/vkfix/vkfix_test.go @@ -4,16 +4,18 @@ import ( "bytes" "encoding/hex" "os" + "path/filepath" "strings" "testing" "modavd/internal/errs" ) -// The real libraries (read-only); the tests that need them are skipped when they are absent. -const ( - origLib = `C:\sdk-src\work\gfx\guestlibs\libvulkan_enc.so` - fixLib = `C:\sdk-src\work\gfx\guestlibs\libvulkan_enc.khrfix-bindlock2.so` +// The real libraries (read-only) in $MODAVD_TEST_VKLIBS: the image's libvulkan_enc.so and the patched copy AUTO-MAS +// vulkanfix.py made of it, libvulkan_enc.khrfix-bindlock2.so. The tests that need them are skipped when they are absent. +var ( + origLib = filepath.Join(os.Getenv("MODAVD_TEST_VKLIBS"), "libvulkan_enc.so") + fixLib = filepath.Join(os.Getenv("MODAVD_TEST_VKLIBS"), "libvulkan_enc.khrfix-bindlock2.so") ) // Golden bytes printed by AUTO-MAS vulkanfix.py (_wrapper_bind / _wrapper_bind2 at their caves, _jmp, _EXIT_MAGIC). From e26c3f1dc13bbaf3a175dceb4e7916b1523f521e Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 01:51:44 +0100 Subject: [PATCH 10/13] =?UTF-8?q?start=20=E8=BF=94=E5=9B=9E=E5=89=8D?= =?UTF-8?q?=E7=A1=AE=E8=AE=A4=20/sdcard=20=E8=83=BD=E5=86=99=E8=BF=9B?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 10-31 在 6 号实例上实测(每 250 ms 查一次,首次开机、装桥的冷启动和普通开机 共五次): - sys.boot_completed 为 1 时 /sdcard 还没挂上,这时写文件直接报错(No such file or directory 或 Operation not permitted),不是悄悄丢; - 挂上以后 test -w 马上为真,但真要建文件还要再等 1–3 秒; - 开机设置里 Vulkan 修复重启 zygote,/sdcard 又有约 7 秒写不进去。 原来的等待放在开机设置之前、只看 test -w,三段都挡不住;start 能用是因为 设置做完时早已恢复。现在在设置做完、返回之前,用真建一个文件再删掉来确认, 平时不多花时间,最多等 60 秒,到点只警告。help 和 README 同步改。 另外:装桥完成后 start 结果里的实例还带着 busy=bridging(结果是在桥锁里 读的),释放锁后改正;bridge 忙时的提示改成"装或卸"。 --- README.md | 2 +- internal/cli/commands.go | 1 + internal/emu/bridge.go | 11 ++++++++--- internal/emu/bridge_test.go | 2 +- internal/emu/crud.go | 2 +- internal/emu/start.go | 19 +++++++++++++------ 6 files changed, 25 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d94ecb18..3b83506c 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb N] [--fps 30\|60] [--no-bridge]` | 新建。默认带 arm64 执行桥,第一次开机时装上;`--no-bridge` 记下这台不要桥,以后开机也不装 | | `set [--title T] [--memory M] [--cpu N] [--fps F] [--data-gb N]` | 修改,下次开机生效。`--data-gb` 只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB) | | `delete --yes` | 删除已关机的实例,连同游戏数据 | -| `start [--window] [--timeout 300] [--no-bridge]` | 开机,等开完并做完开机后的设置;还会等待 `/sdcard` 挂好(最多 60 秒,超时只警告),实例还没有执行桥时接着装上,`--no-bridge` 这次不装 | +| `start [--window] [--timeout 300] [--no-bridge]` | 开机,等开完并做完开机后的设置,返回前确认 `/sdcard` 能写进文件(一般这时早已就绪;最多再等 60 秒,到点只警告);实例还没有执行桥时接着装上,`--no-bridge` 这次不装 | | `stop [--force]`、`stop --all` | 关机:先让安卓正常关机,不成再 sync + kill;`--force` 是 sync + 强杀 | | `restart [--window] [--timeout 300] [--force] [--no-bridge]` | 关机再开机,选项同 `stop`、`start` | | `bridge install\|uninstall\|verify` | 装、卸、检查 arm64 执行桥;开机时会自动装,一般不用手动跑(见下) | diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 264096f7..e01ba094 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -130,6 +130,7 @@ func init() { "按 Ctrl+C 或 --timeout 到点都只是不再等:模拟器不会被结束,会接着开机。" + "之后再运行一次 start 会接管它,把这次开机还没做完的设置补完(包括首次初始化和客体 Vulkan 修复)。" + "实例已经在运行、设置也都做完时,只重做每次开机都做的设置。" + + "返回前确认 /sdcard 能写进文件(一般这时早已就绪,不多花时间;最多再等 60 秒,到点只警告)。" + "实例还没有 arm64 执行桥时,设置做完后自动装上(中间关机再开机一两次);--no-bridge 这次不装," + "用 bridge uninstall 卸过或新建时带 --no-bridge 的实例不装,接管已经在运行的实例时也不装。", flags: []flagSpec{optWindow, optTimeout, optBootNoBridge}, diff --git a/internal/emu/bridge.go b/internal/emu/bridge.go index ae813998..9bc5c9b1 100644 --- a/internal/emu/bridge.go +++ b/internal/emu/bridge.go @@ -202,8 +202,13 @@ func (m *Manager) finishBridge(ctx context.Context, i int, opt StartOptions, res res.Warnings = append(res.Warnings, fmt.Sprintf("实例 %d 的执行桥正由另一次 modavd 在装,这次不装", i)) return res, nil } - defer lock.Unlock() - return m.installBridge(ctx, i, opt, res) + r, err := m.installBridge(ctx, i, opt, res) + lock.Unlock() + // the instance in the result was read under this lock: the install is over now + if r != nil && r.Instance.Busy == "bridging" { + r.Instance.Busy = busyOf(m.stopping(i), false, false) + } + return r, err } // installBridge is finishBridge with the bridge lock already held by the caller. @@ -308,7 +313,7 @@ func (m *Manager) Bridge(ctx context.Context, i int, action string) (*BridgeResu return nil, errs.Wrap(errs.Internal, err, "实例执行桥锁文件打不开") } if !ok { - return nil, errs.Newf(errs.Busy, "魔改 AVD 实例 %d 正在装执行桥,无法重复操作", i) + return nil, errs.Newf(errs.Busy, "魔改 AVD 实例 %d 正在装或卸执行桥,稍后再试", i) } defer bridgeLock.Unlock() res := &BridgeResult{Index: i, Action: action, ExitCode: -1, Warnings: []string{}} diff --git a/internal/emu/bridge_test.go b/internal/emu/bridge_test.go index 04bda277..5df1b2d7 100644 --- a/internal/emu/bridge_test.go +++ b/internal/emu/bridge_test.go @@ -38,7 +38,7 @@ func TestBridgeLockExcludes(t *testing.T) { t.Fatalf("bridge %s while bridging: %v", action, err) } } - if _, err := m.Delete(ctx, i); errs.CodeOf(err) != errs.Busy || !strings.Contains(err.Error(), "正在装执行桥") { + if _, err := m.Delete(ctx, i); errs.CodeOf(err) != errs.Busy || !strings.Contains(err.Error(), "正在装卸执行桥") { l.Unlock() t.Fatalf("delete while bridging: %v", err) } diff --git a/internal/emu/crud.go b/internal/emu/crud.go index 0b1054b0..ca4174a5 100644 --- a/internal/emu/crud.go +++ b/internal/emu/crud.go @@ -164,7 +164,7 @@ func (m *Manager) Delete(ctx context.Context, i int) (*DeleteResult, error) { startLock.Unlock() return nil, err } - bridgeLock, err := m.tryInstanceLock(i, "bridge", "正在装执行桥") + bridgeLock, err := m.tryInstanceLock(i, "bridge", "正在装卸执行桥") if err != nil { startLock.Unlock() stopLock.Unlock() diff --git a/internal/emu/start.go b/internal/emu/start.go index 32ca7688..3135c2a9 100644 --- a/internal/emu/start.go +++ b/internal/emu/start.go @@ -257,9 +257,6 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption if err != nil { return nil, owed(err) } - if !m.waitSDCard(ctx, i) { - m.Log.Warnf("实例 %d 安卓已开机,但 /sdcard 在 %.0f 秒内还没挂好;继续返回,稍后再试", i, sdcardMountWait.Seconds()) - } if res.Launched { res.BootSeconds = time.Since(launchedAt).Seconds() prog.emit("boot", fmt.Sprintf("实例 %d 安卓已开机(%.1f 秒)", i, res.BootSeconds), progressBooted) @@ -309,6 +306,12 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption return nil, errs.Newf(errs.LaunchFailed, "魔改 AVD 实例 %d 在开机后设置期间退出了(模拟器 pid %d):%s", i, qemu.PID, orText(logTail(res.LogFile, 8), "日志见 "+m.Root.LogsDir())) } + // Callers write to /sdcard right after start (10-31 measurements): it is not there yet at sys.boot_completed, + // takes another 1–3 s to accept a new file after it is mounted, and the zygote restart of the Vulkan fix takes it + // away again for about 7 s. Usually ready long before the setup is done, so this costs nothing then. + if !m.waitSDCard(ctx, i) && ctx.Err() == nil { + m.Log.Warnf("实例 %d 开机后 /sdcard 在 %.0f 秒内一直写不进文件;先返回,稍后再写", i, sdcardMountWait.Seconds()) + } res.SetupPending = ab.SetupPending // The boot read before the setup, so a guest that rebooted during it is set up again by the watch. Unknown (adb // failed): the old record stays, which at worst makes the watch set this boot up once more. @@ -334,14 +337,18 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption return res, nil } -// waitSDCard covers the short interval after sys.boot_completed in which vold has not mounted shared storage yet. -// A timeout is only a warning: the emulator is usable and a later start/status call can observe the mount. +// waitSDCard waits up to sdcardMountWait until a new file can be created in /sdcard (and removed again). Being +// mounted, or test -w, is not enough: right after the mount both say yes while creating a file still fails with +// EPERM. A timeout is only a warning: the emulator is usable, the caller's write fails visibly if it is still too early. func (m *Manager) waitSDCard(ctx context.Context, i int) bool { return pollUntil(ctx, sdcardMountWait, 500*time.Millisecond, func() bool { - return m.shell(ctx, i, "test -d /sdcard && test -r /sdcard && test -w /sdcard", statusAdbTimeout).Code == 0 + return m.shell(ctx, i, sdcardProbe, statusAdbTimeout).Code == 0 }) } +// sdcardProbe creates and removes a file in /sdcard as the shell user (whom apps and AUTO-MAS's adb push write as). +const sdcardProbe = "f=/sdcard/.modavd-sdcard-check; touch $f && rm -f $f" + // pollUntil calls ok (at least once) every interval until it returns true (true), limit has passed or ctx ends // (false). func pollUntil(ctx context.Context, limit, every time.Duration, ok func() bool) bool { From 88248bf1684fc88d051fda9720f386b04d0f6e84 Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 10:27:48 +0100 Subject: [PATCH 11/13] =?UTF-8?q?=E5=8F=91=E7=89=88=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E9=A2=84=E5=91=8A=200.2.0=20=E7=9A=84?= =?UTF-8?q?=E8=87=AA=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 管理器不做自更新:单独下载的要手动替换,ModAVD 包里的那份随 ModAVD 整包 一起更新。v0.1.0 的发版说明和 README 原来写「0.2.0 起才有自更新」,改掉。 --- README.md | 2 +- release/0.1.0.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3535704..aba9b15d 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ go test ./... - 核对:`Get-FileHash .\ModAVDManager-0.1.0-win-x64.zip -Algorithm SHA256`,和 `SHA256SUMS.txt` 里那一行比;解压出的两个 exe 也一样比。 - 自己编出同样的字节:Go 1.26.5、`GOTOOLCHAIN=local`,`pwsh -NoProfile -File build.ps1 -Out out`,再 `go run ./internal/tools/mkzip -dir out -version <版本>` 打 zip。 - 单独使用时给 `--root` 或设 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把 zip 解压到 ModAVD 根目录里覆盖包里的那份。 -- v0.1.0 没有自更新,单独下载的要手动换;0.2.0 起才有。 +- 单独下载的管理器不会自己更新,新版本要手动下载替换;ModAVD 包里的那份随 ModAVD 整包一起更新。 ## 参与 diff --git a/release/0.1.0.md b/release/0.1.0.md index 3b4690f4..ca0a2184 100644 --- a/release/0.1.0.md +++ b/release/0.1.0.md @@ -7,4 +7,4 @@ 使用 Go 1.26.5、`GOTOOLCHAIN=local`,运行仓库中的 `build.ps1` 可以编出相同字节。单独下载包还包含 Go 许可原文和文件清单;请用附件 `SHA256SUMS.txt` 核对 zip 和解压出的两个 exe,例如在 PowerShell 里运行 `Get-FileHash .\ModAVDManager-0.1.0-win-x64.zip -Algorithm SHA256`。 -0.1.0 没有自更新,单独下载的文件需要手动替换。从 0.2.0 起才提供自更新。单独使用时请给 `--root` 或设置 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把单独下载的 zip 解压到 ModAVD 根目录覆盖整包中的文件。 +管理器不会自己更新:单独下载的文件需要手动替换,ModAVD 包里的那份随 ModAVD 整包一起更新。单独使用时请给 `--root` 或设置 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把单独下载的 zip 解压到 ModAVD 根目录覆盖整包中的文件。 From 4ceca4be7a1858b6654274ed7b185e09d774a17e Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 10:39:33 +0100 Subject: [PATCH 12/13] =?UTF-8?q?CI=EF=BC=9Asetup-go=20=E8=A3=85=20go.mod?= =?UTF-8?q?=20=E9=87=8C=20toolchain=20=E8=A1=8C=E7=9A=84=E7=A1=AE=E5=88=87?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit go.mod 的 go 行是 go 1.26,setup-go 按它装了最新的 1.26.10;build.ps1 要求 和 toolchain 行(go1.26.5)一致,构建失败,后面的检查都没跑。改为先读出 toolchain 行的版本,再交给 setup-go。 --- .github/workflows/ci.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c7090a4a..548e8838 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,9 +19,18 @@ jobs: with: persist-credentials: false fetch-depth: 0 + # go.mod's go line is "go 1.26", which setup-go resolves to the newest 1.26.x; build.ps1 wants the exact + # toolchain line. + - name: go version + id: go + shell: pwsh + run: | + $v = (Select-String -LiteralPath go.mod -Pattern '^toolchain\s+go(\S+)' | Select-Object -First 1).Matches.Groups[1].Value + if (-not $v) { throw 'go.mod has no toolchain line' } + "version=$v" >> $env:GITHUB_OUTPUT - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod + go-version: ${{ steps.go.outputs.version }} cache: false - name: gofmt shell: pwsh From ea495f71b79e9788a8d038f97d1c02d041d17a9f Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Sat, 31 Oct 2026 10:39:47 +0100 Subject: [PATCH 13/13] =?UTF-8?q?=E5=8F=91=E7=89=88=EF=BC=9Asetup-go=20?= =?UTF-8?q?=E8=A3=85=20go.mod=20=E9=87=8C=20toolchain=20=E8=A1=8C=E7=9A=84?= =?UTF-8?q?=E7=A1=AE=E5=88=87=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 和 CI 同一个问题:按 go 1.26 会装上最新的 1.26.x,build.ps1 拒绝构建,打 tag 后发版必然失败。 --- .github/workflows/release.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f4a04779..85f82332 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,9 +25,17 @@ jobs: with: persist-credentials: false fetch-depth: 0 + # the exact toolchain line, as in ci.yml (setup-go would resolve "go 1.26" to the newest 1.26.x) + - name: go version + id: go + shell: pwsh + run: | + $v = (Select-String -LiteralPath go.mod -Pattern '^toolchain\s+go(\S+)' | Select-Object -First 1).Matches.Groups[1].Value + if (-not $v) { throw 'go.mod has no toolchain line' } + "version=$v" >> $env:GITHUB_OUTPUT - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version-file: go.mod + go-version: ${{ steps.go.outputs.version }} cache: false - name: verify tag and ancestry shell: pwsh