diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..548e8838 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +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 + # 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: ${{ steps.go.outputs.version }} + 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 scripts/test_repo_checks.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..85f82332 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,123 @@ +name: release + +on: + push: + tags: ["v*"] + +permissions: {} + +concurrency: + group: release-${{ github.ref_name }} + cancel-in-progress: false + +env: + GOTOOLCHAIN: local + +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 + # 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: ${{ steps.go.outputs.version }} + 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 + 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')) { + $got = (Get-FileHash "out/$name" -Algorithm SHA256).Hash.ToLowerInvariant() + if ($got -ne $sums[$name]) { throw "$name hash mismatch" } + } + $zip = "ModAVDManager-$version-win-x64.zip" + 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@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-assets + path: artifacts + if-no-files-found: error + + draft: + needs: build + runs-on: windows-2025 + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-assets + path: artifacts + - name: verify artifact + shell: pwsh + 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) + $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) + # 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/.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..1883c827 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 根目录覆盖整包里的文件。 | 产物 | 源码 | 做什么 | | --- | --- | --- | @@ -58,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 执行桥;开机时会自动装,一般不用手动跑(见下) | @@ -75,6 +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` / `status` 的 `bridge`:`off`(记了不要桥)、`pending`(下次由 modavd 拉起的开机会装)、`installed`(开着的客体里桥在)、`unknown`。只问已经开完机的客体;关着或还在开机的实例,开机标记在桥装好后一直留着,装失败时也在,所以首次开机做过、标记也在时是 `unknown`,要知道确切结果就开机后再查。 +- 装桥期间(含其中的关机、冷启动)`busy` 为 `bridging`;这时 `delete`、再次 `bridge` 返回实例忙(退出码 5)。调用方不认识的 `busy` 取值一律当忙处理。 - 不经 modavd 或管理器开机的实例(别的程序直接拉起模拟器)不会自动装,要装就跑一次 `bridge install`。 **机读输出**(`--json`): @@ -82,6 +85,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` 是脚本的退出码。 @@ -155,8 +159,17 @@ 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`。 -- CI(`.github/workflows/test.yml`)在 `windows-latest` 上跑 `go vet`、`go test` 和 `build.ps1`。 +- 有几项测试只读本机 `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 或手动触发时运行。 + +## 单独下载与哈希 + +- 每个版本的 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 根目录里覆盖包里的那份。 +- 单独下载的管理器不会自己更新,新版本要手动下载替换;ModAVD 包里的那份随 ModAVD 整包一起更新。 ## 参与 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/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/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..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:\emu-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:\\emu-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/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/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/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/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/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/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..9bc5c9b1 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). @@ -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 "" } @@ -197,8 +202,17 @@ 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() + 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. +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()) @@ -294,6 +308,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 +344,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{}) + // 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..5df1b2d7 --- /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/crud.go b/internal/emu/crud.go index a41b55b7..ca4174a5 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..3135c2a9 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 @@ -303,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. @@ -328,6 +337,35 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption return res, nil } +// 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, 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 { + deadline := time.Now().Add(limit) + for { + if ctx.Err() != nil { + return false + } + if ok() { + return true + } + if !time.Now().Before(deadline) || !sleepOrDone(ctx, every) { + 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/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 39684910..6243c0ea 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,7 @@ 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")) cfg := InstanceConfig{MemoryMB: avd.MemoryFor(m.Root, i), FPS: in.FPS()} if n, ok := in.CPU(); ok { @@ -159,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 } @@ -175,9 +177,12 @@ 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 { +// 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: + return "bridging" case stopping: return "stopping" case starting: @@ -187,6 +192,38 @@ func busyOf(stopping, starting 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 bridgeStateOff + } + if booted { + switch b := m.guestBridgeWithin(ctx, i, statusAdbTimeout); { + case b == bridgeProp: + return bridgeStateInstalled + case b != "": + return bridgeStatePending + } + return bridgeStateUnknown + } + if !regularFile(bridgeMarker(m.Root, i)) || !initialized { + return bridgeStatePending + } + return bridgeStateUnknown +} + // 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..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) != "" || 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" || 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 32ffc57d..76c5f9cc 100644 --- a/internal/emu/types.go +++ b/internal/emu/types.go @@ -48,12 +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"` - PID int `json:"pid"` + // 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 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"` @@ -134,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 f597eccd..d0d67dbe 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). Until AUTO-MAS calls modavd for booting, changes go into both places. 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/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 ac65b20d..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 ...). -# Same text as the inline script in aemu-lab tools\launcher\avd-p0.ps1; keep the two in sync. +# 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 63b5d95c..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. Explanation: C:\emu-src\patches\wifi\README.md +# 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 d28faab3..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 -# -VulkanFix in aemu-lab tools\launcher\avd-p0.ps1; 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/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..4d3f4b9b 100644 --- a/internal/jsonord/testdata/pycases.json +++ b/internal/jsonord/testdata/pycases.json @@ -29,8 +29,8 @@ "out": "\"a\\\"b\\\\c/d\"" }, { -"in": "eyJxIjogInNheSBcImhpXCIiLCAicCI6ICJDOlxcZW11LXNyY1xcc2RrLW1hczM1XFwiLCAidSI6ICJcdTRlMmRcdTY1ODcifQ==", -"out": "{\n \"q\": \"say \\\"hi\\\"\",\n \"p\": \"C:\\\\emu-src\\\\sdk-mas35\\\\\",\n \"u\": \"\u4e2d\u6587\"\n}" +"in": "eyJxIjogInNheSBcImhpXCIiLCAicCI6ICJDOlxcc2RrLXNyY1xcc2RrLW1hczM1XFwiLCAidSI6ICJcdTRlMmRcdTY1ODcifQ==", +"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.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..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:\emu-src\sdk-mas35`, + `{"sdkRoot": " C:/sdk-src/sdk-mas35/ "}`: `C:\sdk-src\sdk-mas35`, `{"sdkRoot": "dev-sdk"}`: d + `\dev-sdk`, `{"sdkRoot": " "}`: "", `{"sdkRoot": 5}`: "", @@ -204,8 +204,8 @@ 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"}`)) - if r.AdbExe() != `C:\emu-src\sdk-mas35\platform-tools\adb.exe` || r.SDK() != d+`\sdk` { + 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()) } } diff --git a/internal/tools/mkzip/main.go b/internal/tools/mkzip/main.go new file mode 100644 index 00000000..1861c2b6 --- /dev/null +++ b/internal/tools/mkzip/main.go @@ -0,0 +1,133 @@ +// 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" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "time" + + "modavd/internal/buildinfo" +) + +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() { + 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) + } + + 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 { + 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) + } + mb, err := json.Marshal(manifest{Version: *version, Files: hashes}) + if err != nil { + return err + } + data["modavd-manager.json"] = append(mb, '\n') + + names := make([]string, 0, len(data)) + for name := range data { + names = append(names, name) + } + sort.Strings(names) + 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 { + return err + } + if _, err := w.Write(data[name]); err != nil { + return err + } + } + if err := zw.Close(); err != nil { + return err + } + if d := filepath.Dir(*out); d != "." { + if err := os.MkdirAll(d, 0o755); err != nil { + return err + } + } + return os.WriteFile(*out, buf.Bytes(), 0o644) +} + +// 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())) + } + return b, nil +} 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/vkfix/vkfix_test.go b/internal/vkfix/vkfix_test.go index 07a55630..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:\emu-src\work\gfx\guestlibs\libvulkan_enc.so` - fixLib = `C:\emu-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). 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 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..ca0a2184 --- /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 许可原文和文件清单;请用附件 `SHA256SUMS.txt` 核对 zip 和解压出的两个 exe,例如在 PowerShell 里运行 `Get-FileHash .\ModAVDManager-0.1.0-win-x64.zip -Algorithm SHA256`。 + +管理器不会自己更新:单独下载的文件需要手动替换,ModAVD 包里的那份随 ModAVD 整包一起更新。单独使用时请给 `--root` 或设置 `MODAVD_ROOT`,否则会提示找不到 ModAVD 根目录。不要把单独下载的 zip 解压到 ModAVD 根目录覆盖整包中的文件。 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..8a1d933c --- /dev/null +++ b/scripts/repo_checks.py @@ -0,0 +1,62 @@ +"""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, 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, + 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.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)): + 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..4ea0dde7 --- /dev/null +++ b/scripts/test_repo_checks.py @@ -0,0 +1,49 @@ +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +# 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): + 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")) + 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: + 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\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))) + + +if __name__ == "__main__": + unittest.main()