From 0714e3cfb878daac807cc8575818ef6cce6e8af4 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:13:41 +0000 Subject: [PATCH 1/9] =?UTF-8?q?=E5=BC=80=E6=9C=BA=E5=90=8E=E8=AF=BB?= =?UTF-8?q?=E5=AE=A2=E4=BD=93=E6=97=B6=E9=92=9F=E6=BA=90=E6=94=B9=E7=94=A8?= =?UTF-8?q?=20root=EF=BC=9Ashell=20=E7=94=A8=E6=88=B7=E5=9C=A8=20Android?= =?UTF-8?q?=2014=20=E9=95=9C=E5=83=8F=E4=B8=8A=E8=AF=BB=E4=B8=8D=E5=88=B0?= =?UTF-8?q?=20(#173)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0.41.0 候选的发版回归里,每次开机都只记到「读不到客体时钟源(…Permission denied…)」:SELinux 不让 adb shell 用户读 /sys/devices/system/clocksource/clocksource0/。改成和读内核日志一样用 su 0;读失败时记录里的 available 不再留报错文字。 Refs ModAVD/ModAVD#110 --- internal/emu/clocksource.go | 8 +++++--- internal/emu/clocksource_test.go | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/internal/emu/clocksource.go b/internal/emu/clocksource.go index 83a23c4..653a4b7 100644 --- a/internal/emu/clocksource.go +++ b/internal/emu/clocksource.go @@ -29,9 +29,10 @@ import ( const ( // clocksourceScript prints the current clock source, the available ones and the guest's machine, separated by - // "---" lines: one fixed command line without variables, readable without root. - clocksourceScript = "cat /sys/devices/system/clocksource/clocksource0/current_clocksource; echo ---; " + - "cat /sys/devices/system/clocksource/clocksource0/available_clocksource; echo ---; uname -m" + // "---" lines: one fixed command line without variables. As root: on the Android 14 images SELinux does not let + // the adb shell user read this sysfs directory (every boot logged "Permission denied"). + clocksourceScript = "su 0 sh -c 'cat /sys/devices/system/clocksource/clocksource0/current_clocksource; echo ---; " + + "cat /sys/devices/system/clocksource/clocksource0/available_clocksource; echo ---; uname -m'" clocksourceTimeout = 10 * time.Second // clocksourceKernelCommand is the guest kernel log as root (logcat -b kernel needs it on these images; dmesg may // have been overwritten by then). Filtered here, on the host, so no pipe runs in the guest. @@ -134,6 +135,7 @@ func (m *Manager) checkClocksource(i int, cfg *avd.Ini, run func(command string, rec.Available, rec.Arch, rec.X86 = available, arch, x86Guest(arch, cfg) switch { case !ok: + rec.Available = "" // whatever stood there is part of an error text rec.Error = orText(tail(strings.Join(strings.Fields(res.Out), " "), 200), fmt.Sprintf("退出码 %d", res.Code)) m.Log.Warnf("实例 %d 读不到客体时钟源(%s),这次开机不判断", i, rec.Error) case !rec.X86 || current == "tsc": diff --git a/internal/emu/clocksource_test.go b/internal/emu/clocksource_test.go index 79b4b59..bc178a4 100644 --- a/internal/emu/clocksource_test.go +++ b/internal/emu/clocksource_test.go @@ -275,3 +275,20 @@ func TestCheckClocksourceRecordUnwritable(t *testing.T) { t.Errorf("log = %s", fmt.Sprint(*lines)) } } + +// The clock source is read as root: the adb shell user is denied this sysfs directory on the Android 14 images +// (ModAVD/ModAVD#110; every boot of the 0.41.0 candidate logged "Permission denied"). +func TestClocksourceScriptRunsAsRoot(t *testing.T) { + if !strings.HasPrefix(clocksourceScript, "su 0 sh -c '") || !strings.HasSuffix(clocksourceScript, "'") || + strings.Count(clocksourceScript, "'") != 2 { + t.Fatalf("clocksourceScript must be one su 0 sh -c '…' command: %q", clocksourceScript) + } +} + +func TestParseClocksourceDenied(t *testing.T) { + out := "cat: /sys/devices/system/clocksource/clocksource0/current_clocksource: Permission denied\n---\n" + + "cat: /sys/devices/system/clocksource/clocksource0/available_clocksource: Permission denied\n---\nx86_64\n" + if current, _, arch, ok := parseClocksource(out); ok || current != "" || arch != "x86_64" { + t.Fatalf("denied read parsed as current=%q arch=%q ok=%v", current, arch, ok) + } +} From 71246e6560ef93c1936db6a23d77f1a1b5277967 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:15:50 +0000 Subject: [PATCH 2/9] =?UTF-8?q?=E9=97=AE=E9=A2=98=E5=8C=85=E5=8A=A0?= =?UTF-8?q?=E4=B8=8A=E5=AE=9E=E4=BE=8B=E7=9A=84=E5=AE=9E=E9=99=85=E5=B8=A7?= =?UTF-8?q?=E7=8E=87=20(#176)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 收集最后对每台连得上的实例读屏幕刷新率,用 SurfaceFlinger timestats 同时采样 10 秒,原始输出放 fps\,summary 每台一行写刷新率和主要图层的平均帧率、帧间隔中位和 95%。用户说卡时,能分清是屏幕刷新率没变还是游戏本身帧数低。 Refs ModAVD/ModAVD#180 --- internal/report/collect.go | 3 + internal/report/framerate.go | 198 +++++++++++++++++++++++++ internal/report/framerate_test.go | 89 +++++++++++ internal/report/parity_windows_test.go | 5 +- 4 files changed, 293 insertions(+), 2 deletions(-) create mode 100644 internal/report/framerate.go create mode 100644 internal/report/framerate_test.go diff --git a/internal/report/collect.go b/internal/report/collect.go index 1cd54f8..65f4502 100644 --- a/internal/report/collect.go +++ b/internal/report/collect.go @@ -130,6 +130,7 @@ type collector struct { adbPort int plan root.PortPlan // mas-avd.json's portBase (ModAVD/ModAVD#75); the script's PORT_BASE otherwise running []liveTarget + liveSerials []liveSerial // the instances live() reached, for the frame rate sample (extra.go) cmdlineUnreadable bool masFound bool diagnostics map[int]diagnostics.State @@ -278,6 +279,7 @@ func collect(ctx context.Context, rootDir string, h Host, opt CollectOptions) (r c.step("AUTO-MAS 日志", c.autoMAS) c.step("系统事件日志", c.events) c.step("现场截图与状态", c.live) + c.extra(sectionFrameRate, c.frameRate) if err := ctx.Err(); err != nil { return nil, err } @@ -1892,6 +1894,7 @@ func (c *collector) live() error { } else { c.L(fmt.Sprintf("%s(pid %d,%s):", t.name, t.pid, serial)) } + c.liveSerials = append(c.liveSerials, liveSerial{name: t.name, serial: serial}) if err := c.screenshot(filepath.Join(liveDir, "screen-"+t.name+".png"), serial); err != nil { c.L(" 截图出错:" + errText(err)) } diff --git a/internal/report/framerate.go b/internal/report/framerate.go new file mode 100644 index 0000000..a765c5c --- /dev/null +++ b/internal/report/framerate.go @@ -0,0 +1,198 @@ +package report + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// The frame rate each running instance actually shows: SurfaceFlinger's refresh rate and a short timestats sample of +// what it presented, per layer. A user who says "it stutters" cannot tell whether the game draws 15 frames or the +// screen runs at 30 Hz; this says which (ModAVD/ModAVD#180 lets users pick any rate, so the two often differ). +// collect-info.ps1 never had it: a Go-only section and fps\ entries (goOnlySections, goOnlyEntry). + +const sectionFrameRate = "实际帧率(SurfaceFlinger 采样)" + +// frameRateSample is how long timestats records; the instances are sampled at the same time. +var frameRateSample = 10 * time.Second + +type liveSerial struct{ name, serial string } + +// frameRateCommand: the display's refresh rate and vsync period, then a timestats sample of frameRateSample seconds +// (cleared first, disabled and cleared afterwards so nothing keeps recording). One argument: adbLive joins a shell +// command's arguments as they are. grep reads to the end, so dumpsys gets no broken pipe. +func frameRateCommand(sample time.Duration) []string { + ts := "dumpsys SurfaceFlinger --timestats " + return []string{"dumpsys SurfaceFlinger 2>/dev/null | grep -E 'refresh-rate|VSYNC period'; " + + ts + "-disable -clear >/dev/null 2>&1; " + + ts + "-enable >/dev/null 2>&1 && sleep " + strconv.Itoa(int(sample.Seconds())) + " && " + + ts + "-dump -maxlayers 5; " + + ts + "-disable -clear >/dev/null 2>&1"} +} + +func (c *collector) frameRate() error { + c.section(sectionFrameRate) + if len(c.liveSerials) == 0 { + c.L("没有能连上的实例,跳过") + return nil + } + dir := filepath.Join(c.stage, "fps") + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + c.progress(fmt.Sprintf("正在采样实际帧率(%d 秒)", int(frameRateSample.Seconds()))) + results := make([]adbResult, len(c.liveSerials)) + var wg sync.WaitGroup + for i, t := range c.liveSerials { + wg.Add(1) + go func(i int, serial string) { + defer wg.Done() + results[i] = adbLive(c.ctx, c.adbPort, serial, frameRateSample+nativeTimeout, nil, "shell", + frameRateCommand(frameRateSample)...) + }(i, t.serial) + } + wg.Wait() + for i, t := range c.liveSerials { + res := results[i] + if res.TimedOut { + c.L(t.name + ":超时,已放弃") + continue + } + text := adbTextMode(decodeText(res.Stdout)) + if netTrim(res.Stderr) != "" { + text += "\r\n# stderr:\r\n" + adbTextMode(res.Stderr) + } + if err := os.WriteFile(filepath.Join(dir, t.name+".txt"), []byte(text), 0o644); err != nil { + return err + } + c.L(t.name + ":" + summarizeFrameRate(decodeText(res.Stdout), frameRateSample, res.ExitCode)) + } + return nil +} + +var ( + refreshRateLine = regexp.MustCompile(`refresh-rate\s*:\s*([0-9.]+)\s*Hz`) + tsField = regexp.MustCompile(`^\s*(\w+) = (.*)$`) + histBucket = regexp.MustCompile(`([0-9]+)ms=([0-9]+)`) +) + +type tsLayer struct { + name string + totalFrames int + averageFPS float64 + p2p map[int]int // present-to-present interval, ms bucket → frames +} + +// summarizeFrameRate turns the command's output into one line: the refresh rate, then the busiest layers with their +// average frame rate and how even the intervals were (median and 95th percentile of present-to-present). +func summarizeFrameRate(out string, sample time.Duration, exit int) string { + var parts []string + if m := refreshRateLine.FindStringSubmatch(out); m != nil { + parts = append(parts, "屏幕刷新率 "+trimFloat(m[1])+" Hz") + } else { + parts = append(parts, "读不到屏幕刷新率") + } + layers := parseTimestats(out) + sort.SliceStable(layers, func(i, j int) bool { return layers[i].totalFrames > layers[j].totalFrames }) + shown := 0 + for _, l := range layers { + if l.totalFrames == 0 || shown == 2 { + continue + } + shown++ + s := fmt.Sprintf("%s %d 秒 %d 帧,平均 %.1f 帧/秒", l.name, int(sample.Seconds()), l.totalFrames, l.averageFPS) + if med, p95, ok := histPercentiles(l.p2p); ok { + s += fmt.Sprintf(",帧间隔中位 %d ms、95%% %d ms", med, p95) + } + parts = append(parts, s) + } + if shown == 0 { + if len(layers) == 0 && exit != 0 { + parts = append(parts, fmt.Sprintf("采样失败,退出码 %d", exit)) + } else { + parts = append(parts, "采样期间画面没有更新") + } + } + return strings.Join(parts, ";") +} + +// parseTimestats reads the per-layer blocks of `dumpsys SurfaceFlinger --timestats -dump`: each starts with +// "layerName = …"; the global block before the first one is skipped. +func parseTimestats(out string) []tsLayer { + var layers []tsLayer + var cur *tsLayer + nextHist := false + for _, line := range strings.Split(strings.ReplaceAll(out, "\r", ""), "\n") { + if nextHist { + nextHist = false + if cur != nil { + for _, m := range histBucket.FindAllStringSubmatch(line, -1) { + ms, _ := strconv.Atoi(m[1]) + n, _ := strconv.Atoi(m[2]) + if n > 0 { + cur.p2p[ms] += n + } + } + } + continue + } + if strings.HasPrefix(strings.TrimSpace(line), "present2present histogram") { + nextHist = true + continue + } + m := tsField.FindStringSubmatch(line) + if m == nil { + continue + } + key, val := m[1], strings.TrimSpace(m[2]) + switch { + case key == "layerName": + layers = append(layers, tsLayer{name: val, p2p: map[int]int{}}) + cur = &layers[len(layers)-1] + case cur == nil: + case key == "totalFrames": + cur.totalFrames, _ = strconv.Atoi(val) + case key == "averageFPS": + cur.averageFPS, _ = strconv.ParseFloat(val, 64) + } + } + return layers +} + +// histPercentiles: the buckets holding the median and the 95th percentile frame. +func histPercentiles(h map[int]int) (med, p95 int, ok bool) { + total := 0 + keys := make([]int, 0, len(h)) + for k, n := range h { + total += n + keys = append(keys, k) + } + if total == 0 { + return 0, 0, false + } + sort.Ints(keys) + at := func(q float64) int { + need := int(q*float64(total) + 0.999999) + seen := 0 + for _, k := range keys { + if seen += h[k]; seen >= need { + return k + } + } + return keys[len(keys)-1] + } + return at(0.5), at(0.95), true +} + +func trimFloat(s string) string { + if strings.Contains(s, ".") { + s = strings.TrimRight(strings.TrimRight(s, "0"), ".") + } + return s +} diff --git a/internal/report/framerate_test.go b/internal/report/framerate_test.go new file mode 100644 index 0000000..ba4367c --- /dev/null +++ b/internal/report/framerate_test.go @@ -0,0 +1,89 @@ +package report + +import ( + "strings" + "testing" + "time" +) + +// A trimmed real dump (Android 14 guest at hw.lcd.vsync=48, scrolling Settings): the global block, then the layers. +const timestatsSample = ` present offset: 0 ns VSYNC period: 20833333 ns + refresh-rate : 48.00 Hz +SurfaceFlinger TimeStats: +statsStart = 1794743320 +totalFrames = 647 +missedFrames = 0 +present2present histogram is as below: +20ms=600 +layerName = com.android.settings/com.android.settings.homepage.SettingsHomepageActivity#201 +packageName = +totalFrames = 646 +averageFPS = 44.168 +present2present histogram is as below: +0ms=0 18ms=1 19ms=2 20ms=507 21ms=123 23ms=1 86ms=9 350ms=3 +post2present histogram is as below: +19ms=18 20ms=544 +layerName = StatusBar#88 +packageName = +totalFrames = 3 +averageFPS = 0.3 +present2present histogram is as below: +1000ms=3 +layerName = none +packageName = +totalFrames = 0 +` + +func TestSummarizeFrameRate(t *testing.T) { + got := summarizeFrameRate(timestatsSample, 10*time.Second, 0) + want := "屏幕刷新率 48 Hz;" + + "com.android.settings/com.android.settings.homepage.SettingsHomepageActivity#201 10 秒 646 帧,平均 44.2 帧/秒,帧间隔中位 20 ms、95% 21 ms;" + + "StatusBar#88 10 秒 3 帧,平均 0.3 帧/秒,帧间隔中位 1000 ms、95% 1000 ms" + if got != want { + t.Errorf("got %q\nwant %q", got, want) + } +} + +func TestSummarizeFrameRateEmpty(t *testing.T) { + for _, c := range []struct { + out string + exit int + want string + }{ + {"", 1, "读不到屏幕刷新率;采样失败,退出码 1"}, + {" refresh-rate : 60.00 Hz\nlayerName = none\ntotalFrames = 0\n", 0, "屏幕刷新率 60 Hz;采样期间画面没有更新"}, + {" refresh-rate : 59.94 Hz\n", 0, "屏幕刷新率 59.94 Hz;采样期间画面没有更新"}, + } { + if got := summarizeFrameRate(c.out, 10*time.Second, c.exit); got != c.want { + t.Errorf("%q: got %q, want %q", c.out, got, c.want) + } + } +} + +func TestFrameRateCommandStopsRecording(t *testing.T) { + cmd := frameRateCommand(10 * time.Second) + if len(cmd) != 1 { + t.Fatalf("want one shell argument, got %d", len(cmd)) + } + s := cmd[0] + if !strings.Contains(s, "sleep 10 &&") || !strings.HasSuffix(s, "--timestats -disable -clear >/dev/null 2>&1") { + t.Errorf("command does not sample 10 s and stop recording at the end: %s", s) + } + if strings.Contains(s, "grep -m") { + t.Error("grep -m quits early and gives dumpsys a broken pipe") + } +} + +func TestHistPercentiles(t *testing.T) { + if _, _, ok := histPercentiles(map[int]int{}); ok { + t.Error("empty histogram gave percentiles") + } + med, p95, _ := histPercentiles(map[int]int{16: 90, 33: 5, 50: 5}) + if med != 16 || p95 != 33 { + t.Errorf("med %d p95 %d, want 16 33", med, p95) + } + med, p95, _ = histPercentiles(map[int]int{16: 90, 33: 4, 50: 6}) + if med != 16 || p95 != 50 { + t.Errorf("med %d p95 %d, want 16 50", med, p95) + } +} diff --git a/internal/report/parity_windows_test.go b/internal/report/parity_windows_test.go index 9647360..455264f 100644 --- a/internal/report/parity_windows_test.go +++ b/internal/report/parity_windows_test.go @@ -428,7 +428,8 @@ func TestCollectMatchesScript(t *testing.T) { } // goOnlySections are the summary sections collect-info.ps1 does not have (extra.go). -var goOnlySections = map[string]bool{sectionManagerLogs: true, sectionAdbProcesses: true, sectionPortExcluded: true} +var goOnlySections = map[string]bool{sectionManagerLogs: true, sectionAdbProcesses: true, sectionPortExcluded: true, + sectionFrameRate: true} // withoutGoOnly drops goOnlySections from summary lines: each with the empty line before its header and its lines. func withoutGoOnly(ls []string) []string { @@ -452,7 +453,7 @@ func goOnlyEntry(name string) bool { return true } } - return strings.HasPrefix(name, "adb/") + return strings.HasPrefix(name, "adb/") || strings.HasPrefix(name, "fps/") } func TestReportConfigMatchesScript(t *testing.T) { From bddfb0e059967425a6e5e61d597a2aa5dce5bb99 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:56:27 +0000 Subject: [PATCH 3/9] =?UTF-8?q?=E5=BC=80=E6=9C=BA=E6=94=BE=E5=BC=80?= =?UTF-8?q?=E3=80=8C=E5=AE=89=E8=A3=85=E6=9C=AA=E7=9F=A5=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E3=80=8D=E5=90=8E=E7=AB=8B=E5=88=BB=E8=90=BD=E7=9B=98=20(#177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7c 只改了 system_server 内存里的 app ops(约 30 分钟后才写盘),同一次开机的客体库补丁会重启 system_server,新建的实例从没存下来;第一次装 APK 时安装器把 default 改成 deny。有改动时跑 appops write-settings。 Refs ModAVD/ModAVD#218 --- internal/emu/afterboot.go | 16 +++++++++++----- internal/emu/ime_test.go | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index b4f579d..48be628 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -25,24 +25,30 @@ import ( // (toggled by the user, or allowed at an earlier boot) are left alone; an app whose mode cannot be read // (`appops get` non-zero) is not written and counts as failed. Enumeration failure exits 2; a failed app prints // "failed: ", the rest go on, the exit code is then 1. dumpsys also exits 0 when the service is missing, -// so finding no package section counts as an enumeration failure. Same text as AUTO-MAS -// _ALLOW_INSTALL_SOURCES_SCRIPT and the launcher. +// so finding no package section counts as an enumeration failure. +// +// After a change the modes are written to /data/system/appops.xml at once (`appops write-settings`, a failure prints +// "write-settings failed" and exits 1): system_server only writes them about 30 minutes later, and the guest Vulkan +// fix (step 11) restarts system_server seconds after this step, so a new instance never kept them and the system +// installer, finding the mode back at default, set it to deny on the first APK install (11-15). const allowInstallSourcesScript = `set -o pipefail; ` + `list=$(dumpsys package packages 2>/dev/null` + ` | awk '/^ Package \[/ { n++; p = substr($2, 2, length($2) - 2) }` + ` /android.permission.REQUEST_INSTALL_PACKAGES/ { if (p != "" && p != "android") print p }` + ` END { if (n == 0) exit 3 }'` + ` | sort -u) || { echo "dumpsys package failed"; exit 2; }; ` + - `fail=0; ` + + `fail=0; changed=0; ` + `for p in $list; do` + ` m=$(appops get "$p" REQUEST_INSTALL_PACKAGES 2>&1)` + ` || { echo "failed: $p"; fail=1; continue; };` + ` case "$m" in` + ` *"REQUEST_INSTALL_PACKAGES: default"*) ;;` + ` *"REQUEST_INSTALL_PACKAGES: "*) continue ;; esac;` + - ` if appops set "$p" REQUEST_INSTALL_PACKAGES allow; then echo "$p";` + + ` if appops set "$p" REQUEST_INSTALL_PACKAGES allow; then echo "$p"; changed=1;` + ` else echo "failed: $p"; fail=1; fi;` + - ` done; exit $fail` + ` done; ` + + `if [ $changed = 1 ] && ! appops write-settings >/dev/null 2>&1; then echo "write-settings failed"; fail=1; fi; ` + + `exit $fail` type afterBootResult struct { FirstBoot bool diff --git a/internal/emu/ime_test.go b/internal/emu/ime_test.go index 772fad3..9e51492 100644 --- a/internal/emu/ime_test.go +++ b/internal/emu/ime_test.go @@ -36,7 +36,7 @@ func TestHostImeScripts(t *testing.T) { "wait": {hostImeWaitScript, `i=0; while [ $i -lt 20 ]; do ime list -a -s | grep -qx org.modavd.ime/.HostImeService && { echo ok; exit 0; }; sleep 0.25; i=$((i+1)); done; echo timeout`}, "marker": {hostImeMarker, "/data/local/tmp/modavd-ime.autoselected"}, "id": {hostImeID, "org.modavd.ime/.HostImeService"}, - "allow": {allowInstallSourcesScript, `set -o pipefail; list=$(dumpsys package packages 2>/dev/null | awk '/^ Package \[/ { n++; p = substr($2, 2, length($2) - 2) } /android.permission.REQUEST_INSTALL_PACKAGES/ { if (p != "" && p != "android") print p } END { if (n == 0) exit 3 }' | sort -u) || { echo "dumpsys package failed"; exit 2; }; fail=0; for p in $list; do m=$(appops get "$p" REQUEST_INSTALL_PACKAGES 2>&1) || { echo "failed: $p"; fail=1; continue; }; case "$m" in *"REQUEST_INSTALL_PACKAGES: default"*) ;; *"REQUEST_INSTALL_PACKAGES: "*) continue ;; esac; if appops set "$p" REQUEST_INSTALL_PACKAGES allow; then echo "$p"; else echo "failed: $p"; fail=1; fi; done; exit $fail`}, + "allow": {allowInstallSourcesScript, `set -o pipefail; list=$(dumpsys package packages 2>/dev/null | awk '/^ Package \[/ { n++; p = substr($2, 2, length($2) - 2) } /android.permission.REQUEST_INSTALL_PACKAGES/ { if (p != "" && p != "android") print p } END { if (n == 0) exit 3 }' | sort -u) || { echo "dumpsys package failed"; exit 2; }; fail=0; changed=0; for p in $list; do m=$(appops get "$p" REQUEST_INSTALL_PACKAGES 2>&1) || { echo "failed: $p"; fail=1; continue; }; case "$m" in *"REQUEST_INSTALL_PACKAGES: default"*) ;; *"REQUEST_INSTALL_PACKAGES: "*) continue ;; esac; if appops set "$p" REQUEST_INSTALL_PACKAGES allow; then echo "$p"; changed=1; else echo "failed: $p"; fail=1; fi; done; if [ $changed = 1 ] && ! appops write-settings >/dev/null 2>&1; then echo "write-settings failed"; fail=1; fi; exit $fail`}, } for name, c := range checks { if c[0] != c[1] { From 6682ca89af88b35b1cefed013ee4556adf1613ab Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:40:46 +0000 Subject: [PATCH 4/9] =?UTF-8?q?=E5=BC=80=E6=9C=BA=E8=BF=87=E7=A8=8B?= =?UTF-8?q?=E4=B8=AD=E6=8C=82=E5=AE=A2=E4=BD=93=E5=BA=93=E8=A1=A5=E4=B8=81?= =?UTF-8?q?=EF=BC=8C=E5=BC=80=E6=9C=BA=E5=90=8E=E4=B8=8D=E5=86=8D=E9=BB=91?= =?UTF-8?q?=E5=B1=8F=E9=87=8D=E6=9D=A5=EF=BC=9BPixel=20=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E7=9A=84=E5=8D=B8=E8=BD=BD=E7=AD=89=E5=86=99=E7=9B=98=E3=80=81?= =?UTF-8?q?=E5=BC=80=E6=9C=BA=E8=A1=A5=E5=8D=B8=20(#178)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 带窗口开机时,补丁的 zygote 重启原来排在开机完成之后,桌面露出来又没了、十几秒后再回来。初始化过的实例现在在开机等待里 adb 一能用就挂(earlyGuestFixes),屏幕上还是开机动画;开机后的那一步只看到已挂上。新实例的第一次开机仍在开机后挂,但挪到开机后设置的第一步,之后的设置不用再补做(去掉 recheckHostIme 和重启后的方向设置)。 - 首次初始化卸载原生 Pixel 桌面后,系统要约 10 秒才写盘,原来 2 秒多以后就重启了 zygote,卸载丢了,1080p 上 Pixel 桌面画出任务栏。卸载后等写盘(pixelLauncherRemoveScript);之后每次开机发现它又在就再卸一次(ensurePixelLauncherRemoved)。 - 新建进度的计划跟着改:补丁排在每次开机后的第一步,冷启动只剩检查。 实机(flow-a,1080p):带窗口开机,zygote 在开机动画期间重启,start 合计 21–26 秒(原来约 40 秒);已中招的实例开一次机就卸掉 Pixel 桌面并写盘,下次不再出现;新建一台(带执行桥)首次初始化后 Pixel 桌面不在、没有任务栏。 Refs ModAVD/ModAVD#220 Refs ModAVD/ModAVD#221 --- internal/emu/afterboot.go | 50 ++++++------- internal/emu/bootadb_windows_test.go | 6 +- internal/emu/createinit.go | 17 +++-- internal/emu/createinit_test.go | 37 ++++++---- internal/emu/early_test.go | 104 +++++++++++++++++++++++++++ internal/emu/early_windows_test.go | 51 +++++++++++++ internal/emu/firstboot.go | 18 +++-- internal/emu/guestfix.go | 77 ++++++++++++++++++++ internal/emu/guestfix_test.go | 11 ++- internal/emu/ime.go | 23 ------ internal/emu/ime_test.go | 40 ----------- internal/emu/pixellauncher.go | 85 ++++++++++++++++++++++ internal/emu/qemu_errors_test.go | 2 +- internal/emu/start.go | 36 ++++++++-- internal/emu/start_test.go | 12 ++-- 15 files changed, 436 insertions(+), 133 deletions(-) create mode 100644 internal/emu/early_test.go create mode 100644 internal/emu/early_windows_test.go create mode 100644 internal/emu/pixellauncher.go diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index 48be628..e54e939 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -92,7 +92,6 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe i := inst.Index ports := m.Root.Ports() port := ports.Console(i) - var imeDefault bool cores, ok := inst.CPU() if !ok || cores <= 0 { cores = avd.DefaultCPU @@ -107,6 +106,18 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe } steps := []func(){ + func() { + // 0a) the guest library fixes (Vulkan driver, ARM translation layer). A launched boot of an initialized + // instance has mounted them during the boot animation already (earlyGuestFixes): this only finds them + // mounted. Otherwise mounting them restarts zygote, system_server and every app, so it comes first: + // everything below then runs on the framework that stays, and a change the package manager writes + // with a delay (the stock launcher removed by the first-boot setup) is not lost with the restart. + // The progress step keeps its name vulkan_fix (API, GUI, create) + prog.emit("vulkan_fix", fmt.Sprintf("实例 %d 客体库补丁(Vulkan 驱动、ARM 转译层)", i), progressVulkanFix) + restarted, pending := m.ensureGuestFixes(ctx, inst, mode, until) + r.SetupPending = pending + r.ZygoteRestarted = restarted + }, func() { if err := m.applyRegional(ctx, i, mode); err != nil { m.Log.Warnf("实例 %d 语言设置未完成,下次继续: %v", i, err) @@ -175,7 +186,7 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe func() { // 7b) NetworkWatchlistService hashes every APK in full once a day has passed since the last boot (about // 4 GB into the page cache, the whole guest RAM then stays resident on the host). Read when - // system_server starts: effective from the next boot, also after the zygote restart of step 11 + // system_server starts: effective from the next boot res := m.shell(ctx, i, "settings put global network_watchlist_enabled 0", 0) if res.Code != 0 { m.Log.Warnf("实例 %d 关闭 NetworkWatchlistService 失败(下次开机仍会把安装包整个读一遍): %s", @@ -195,7 +206,7 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe }, // 7d) host input method: install, enable, make it the default by the rules (every boot) // (logPath is this boot's emulator log unless the instance was simply adopted) - func() { imeDefault = m.setupHostIme(ctx, i, mode != setupAdopted, logPath, prog) }, + func() { r.HostIME = m.setupHostIme(ctx, i, mode != setupAdopted, logPath, prog) }, // 8) network: Wi-Fi always on (games then skip "not on Wi-Fi" prompts); fastpath sends bulk traffic over // eth0 (the virtual Wi-Fi alone does about 6 MB/s). The Wi-Fi switch persists in /data: set every boot func() { m.setupNetwork(ctx, i) }, @@ -213,35 +224,19 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe prog.emit("first_boot", fmt.Sprintf("实例 %d 首次开机初始化", i), progressFirstBoot) m.firstBootInit(ctx, i) r.FirstBoot = true + return + } + // 9b) the stock launcher stays removed (pixellauncher.go): an older start lost its removal to a restart + if mode != setupAdopted { + m.ensurePixelLauncherRemoved(ctx, i) } }, // 10) orientation: the display stays landscape (persistent; set every boot so old instances get it) func() { m.setupOrientation(ctx, i) }, - // 10b) hand the clusters the guest freed back to the host, at most once a day (best effort, see autotrim.go); - // before the guest library fixes, whose zygote restart is deliberately the last step + // 10b) hand the clusters the guest freed back to the host, at most once a day (best effort, see autotrim.go) func() { m.autoTrim(ctx, i, mode) }, - func() { - // 11) the guest library fixes (Vulkan driver, ARM translation layer). Must be last: mounting them restarts - // zygote, system_server and every app. The progress step keeps its name vulkan_fix (API, GUI, create) - prog.emit("vulkan_fix", fmt.Sprintf("实例 %d 客体库补丁(Vulkan 驱动、ARM 转译层)", i), progressVulkanFix) - restarted, pending := m.ensureGuestFixes(ctx, inst, mode, until) - r.SetupPending = pending - if !restarted { - return - } - r.ZygoteRestarted = true - if ctx.Err() != nil { - return - } - // the letterbox education switch lives in system_server's memory and went with the restart - m.setupOrientation(ctx, i) - // the default input method lives in settings and should survive; it was ours after 7d, so check it - if imeDefault { - m.recheckHostIme(i, m.guestIO(ctx, i)) - } - }, - // 12) download disks (dldisk.go). After 11: the framework restart there remounts the shared storage, and a - // disk mounted on it before would be gone with it + // 12) download disks (dldisk.go). After the guest library fixes (0a): the framework restart there remounts the + // shared storage, and a disk mounted on it before would be gone with it func() { m.setupDownloadDisk(ctx, i) }, // 13) the guest's clock source into the log, its kernel log's clock lines saved when an x86_64 guest is not on // tsc (clocksource.go, ModAVD#110). Last: the later the one read, the more of a fallback during boot it sees @@ -253,7 +248,6 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe } step() } - r.HostIME = imeDefault return r, ctxErr(ctx) } diff --git a/internal/emu/bootadb_windows_test.go b/internal/emu/bootadb_windows_test.go index 5662120..5987b12 100644 --- a/internal/emu/bootadb_windows_test.go +++ b/internal/emu/bootadb_windows_test.go @@ -41,7 +41,7 @@ func TestWaitBootAdbUnusableAfterBoot(t *testing.T) { tries := bootAdbFakes(t, q, true) adbAfterBootWait, bootRegisterEvery = 1500*time.Millisecond, 500*time.Millisecond t0 := time.Now() - _, err := m.waitBoot(context.Background(), 3, time.Hour, &q, nil, "", &progressor{}, nil, nil) + _, err := m.waitBoot(context.Background(), 3, time.Hour, &q, nil, "", &progressor{}, nil, nil, nil) if errs.CodeOf(err) != errs.Timeout || !strings.Contains(err.Error(), "ModAVD 实例 3 的安卓已经开好了(模拟器报告开机完成),但之后") || !strings.Contains(err.Error(), "私有 adb(端口 20391)一直用不了") { t.Fatalf("err %v", err) @@ -61,7 +61,7 @@ func TestWaitBootAdbUnusableAfterBoot(t *testing.T) { t.Fatal(err) } adbAfterBootWait = time.Hour - _, err = m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &q, nil, "", &progressor{}, nil, nil) + _, err = m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &q, nil, "", &progressor{}, nil, nil, nil) if errs.CodeOf(err) != errs.Timeout || !strings.Contains(err.Error(), "安卓已经开好了") || !strings.Contains(err.Error(), ";adb 自己的日志最后一行:fatal: boom。日志见 ") { t.Fatalf("at the timeout: %v", err) @@ -73,7 +73,7 @@ func TestWaitBootNoBootReport(t *testing.T) { m, _ := opsTestManager(t) q, _ := startSleeper(t) tries := bootAdbFakes(t, q, false) - _, err := m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &q, nil, "", &progressor{}, nil, nil) + _, err := m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &q, nil, "", &progressor{}, nil, nil, nil) if errs.CodeOf(err) != errs.Timeout || !strings.Contains(err.Error(), "启动超时(2 秒内安卓没有启动完成)") { t.Fatalf("err %v", err) } diff --git a/internal/emu/createinit.go b/internal/emu/createinit.go index 8a0aeba..b59f6f4 100644 --- a/internal/emu/createinit.go +++ b/internal/emu/createinit.go @@ -139,7 +139,9 @@ type createStage struct { // the tuning 1–2 s, the host IME and the steps after it 2–3 s, the first-boot setup 3 s, the guest Vulkan fix 13–14 s // (most of it waiting for the framework after the zygote restart), the shutdown 5–8 s. The bridge on a new instance // takes two rounds with a cold boot each, then a check: the first remount turns verity off (27 s with its -// shutdown), the install (12 s with its shutdown), the check that finds it installed (1 s, no boot). +// shutdown), the install (12 s with its shutdown), the check that finds it installed (1 s, no boot). Since 11-15 a cold +// boot mounts the guest library fixes during the boot (earlyGuestFixes, the boot itself still 17 s): only the check +// after it is left (stageFixCheck); the first boot of a new instance mounts them right after the boot as before. const ( stagePrepare = 2.0 // the checks before the launch (and starting the private adb server) stageBoot = 35.0 // from the launch until Android has booted, the first boot of a new instance @@ -148,6 +150,7 @@ const ( stageIme = 2.5 stageFirstBoot = 3.0 stageVulkanFix = 13.5 + stageFixCheck = 0.5 // the guest library fixes after a cold boot: found mounted already stageRemount = 27.0 // the bridge's first round: the first remount and the shutdown stageBridge = 12.0 // its second: the install and the shutdown stageBridgeCheck = 1.0 // its last: the check that finds it installed @@ -167,13 +170,19 @@ func createPlan(boot float64, firstBoot, bridge bool) []createStage { return append(plan, createStage{"create_stop", stageShutdown}) } -// bootStages are the stages of one boot of the setup, by the steps Start reports; boot is the wait for Android. +// bootStages are the stages of one boot of the setup, by the steps Start reports; boot is the wait for Android. The +// guest library fixes come first after the boot (afterBoot); a boot with the first-boot setup is the only one that +// mounts them there, the others did during the boot. func bootStages(boot float64, firstBoot bool) []createStage { - s := []createStage{{"launch", boot}, {"tune", stageTune}, {"ime", stageIme}} + fix := stageFixCheck + if firstBoot { + fix = stageVulkanFix + } + s := []createStage{{"launch", boot}, {"vulkan_fix", fix}, {"tune", stageTune}, {"ime", stageIme}} if firstBoot { s = append(s, createStage{"first_boot", stageFirstBoot}) } - return append(s, createStage{"vulkan_fix", stageVulkanFix}) + return s } // bridgeRound is a round of the bridge install that changes the guest: the script (and the shutdown), then a cold diff --git a/internal/emu/createinit_test.go b/internal/emu/createinit_test.go index 1f10e8c..fd3e04f 100644 --- a/internal/emu/createinit_test.go +++ b/internal/emu/createinit_test.go @@ -541,15 +541,20 @@ func TestCreateCanceledReportsFinalShutdown(t *testing.T) { } // oneBoot is what Start reports for one boot of the setup: the boot wait (polled by the clock), then the steps after -// it. firstBoot adds the first-boot setup. +// it, the guest library fixes first. firstBoot adds the first-boot setup; a later boot mounts the fixes during the +// boot wait already (earlyGuestFixes), and the step after it only finds them mounted. func oneBoot(firstBoot bool) []Progress { - evs := []Progress{{Step: "launch", Done: progressLaunch}, {Step: "boot", Done: 150}, {Step: "boot", Done: 200}, - {Step: "boot", Done: progressBooted}, {Step: "tune", Done: progressTune}, {Step: "ime", Done: progressIme}} + evs := []Progress{{Step: "launch", Done: progressLaunch}, {Step: "boot", Done: 150}} + if !firstBoot { + evs = append(evs, Progress{Step: "vulkan_fix", Done: 151}) + } + evs = append(evs, Progress{Step: "boot", Done: 200}, Progress{Step: "boot", Done: progressBooted}, + Progress{Step: "vulkan_fix", Done: progressVulkanFix}, Progress{Step: "tune", Done: progressTune}, + Progress{Step: "ime", Done: progressIme}) if firstBoot { evs = append(evs, Progress{Step: "first_boot", Done: progressFirstBoot}) } - return append(evs, Progress{Step: "vulkan_fix", Done: progressVulkanFix}, - Progress{Step: "done", Message: "实例 6 已就绪(共 45.7 秒)", Done: progressTotal}) + return append(evs, Progress{Step: "done", Message: "实例 6 已就绪(共 45.7 秒)", Done: progressTotal}) } // runCreateProgress feeds a setup's events into a createProgress with plan and returns what it sent. bridgeRounds @@ -621,8 +626,9 @@ func TestCreateProgress(t *testing.T) { want float64 // seconds done when it starts }{ {"launch", stagePrepare}, - {"tune", stagePrepare + stageBoot}, - {"vulkan_fix", stagePrepare + stageBoot + stageTune + stageIme + stageFirstBoot}, + {"vulkan_fix", stagePrepare + stageBoot}, + {"tune", stagePrepare + stageBoot + stageVulkanFix}, + {"first_boot", stagePrepare + stageBoot + stageVulkanFix + stageTune + stageIme}, {"create_stop", total - stageShutdown}, } { if d, want := doneAt(t, got, c.step), int(float64(progressTotal)*c.want/total); d != want { @@ -652,13 +658,13 @@ func TestCreateProgressBridge(t *testing.T) { var cold, rounds []int for _, e := range planned[slices.IndexFunc(planned, func(e Progress) bool { return e.Step == "bridge" }):] { switch e.Step { - case "launch", "tune", "vulkan_fix": + case "launch", "tune": cold = append(cold, e.Done) case "bridge": rounds = append(rounds, e.Done) } } - increasing := len(cold) == 6 + increasing := len(cold) == 4 for k := 1; k < len(cold); k++ { increasing = increasing && cold[k] > cold[k-1] } @@ -711,9 +717,14 @@ func TestCreatePlanOfSetup(t *testing.T) { } return doneAt(t, sent, "tune") } + // the fixes after the boot: mounted there on a first boot, only checked after a later one want := func(boot, firstBoot float64) int { - total := stagePrepare + boot + stageTune + stageIme + firstBoot + stageVulkanFix + stageShutdown - return int(float64(progressTotal) * (stagePrepare + boot) / total) + fix := stageFixCheck + if firstBoot > 0 { + fix = stageVulkanFix + } + total := stagePrepare + boot + fix + stageTune + stageIme + firstBoot + stageShutdown + return int(float64(progressTotal) * (stagePrepare + boot + fix) / total) } i := 6 if d, w := tuneAt(CreateRequest{Index: &i, NoBridge: true}), want(stageBoot, stageFirstBoot); d != w { @@ -792,8 +803,8 @@ func TestCreateProgressBootLog(t *testing.T) { t.Fatalf("unreadable log: %d, was %d", d, late) } write("x is operational\nAdvertising in: x\nINFO | Initialized handle: videmulator20060\nINFO | Boot completed in 19637 ms\n") - // the log is only read in the boot wait: the tuning starts its own stage - p.boot(Progress{Step: "tune", Done: progressTune}) + // the log is only read in the boot wait: the guest library fixes start their own stage + p.boot(Progress{Step: "vulkan_fix", Done: progressVulkanFix}) p.boot(Progress{Step: "boot", Done: 150}) if d := got[len(got)-1].Done; d != booted { t.Fatalf("after the boot: %d, want %d", d, booted) diff --git a/internal/emu/early_test.go b/internal/emu/early_test.go new file mode 100644 index 0000000..b021cb1 --- /dev/null +++ b/internal/emu/early_test.go @@ -0,0 +1,104 @@ +package emu + +import ( + "strings" + "testing" + "time" + + "modavd/internal/adb" +) + +func TestEarlyBootState(t *testing.T) { + for _, c := range []struct { + name string + res adb.Result + want bootState + ok bool + }{ + {"booting", adb.Result{Out: "zygote=running booted=\r\n"}, bootState{zygote: true}, true}, + {"booted", adb.Result{Out: "zygote=running booted=1\n"}, bootState{zygote: true, booted: true}, true}, + {"zygote not yet", adb.Result{Out: "zygote= booted=\n"}, bootState{}, true}, + {"zygote restarting", adb.Result{Out: "zygote=restarting booted=\n"}, bootState{}, true}, + {"noise before", adb.Result{Out: "WARNING: linker\nzygote=running booted=\n"}, bootState{zygote: true}, true}, + {"adb failed", adb.Result{Code: 1, Out: "error: device offline"}, bootState{}, false}, + {"no line", adb.Result{Out: "something else\n"}, bootState{}, false}, + } { + got, ok := earlyBootState(c.res) + if got != c.want || ok != c.ok { + t.Errorf("%s: %+v %v, want %+v %v", c.name, got, ok, c.want, c.ok) + } + } + if !strings.Contains(earlyBootProbe, "getprop init.svc.zygote") || !strings.Contains(earlyBootProbe, "getprop sys.boot_completed") { + t.Errorf("probe %q", earlyBootProbe) + } +} + +func TestPixelLauncherListed(t *testing.T) { + for out, want := range map[string]bool{ + "package:com.google.android.apps.nexuslauncher\r\n": true, + "package:com.google.android.apps.nexuslauncher.extra\n": false, + "": false, + "package:de.jrpie.android.launcher\npackage:com.google.android.apps.nexuslauncher": true, + } { + if got := pixelLauncherListed(out); got != want { + t.Errorf("%q: %v", out, got) + } + } +} + +func TestPixelLauncherRemoveResult(t *testing.T) { + for _, c := range []struct { + res adb.Result + ok, saved bool + }{ + {adb.Result{Out: "Success\r\nSAVED\r\n"}, true, true}, + {adb.Result{Out: "Success\nUNSAVED\n"}, true, false}, + {adb.Result{Code: 1, Out: "Failure [not installed for 0]\n"}, false, false}, + {adb.Result{Code: -1, Out: "adb shell 超时(45 秒)\nSAVED"}, false, false}, + {adb.Result{Out: "Success\n"}, false, false}, + } { + if ok, saved := pixelLauncherRemoveResult(c.res); ok != c.ok || saved != c.saved { + t.Errorf("%+v: %v %v", c.res, ok, saved) + } + } +} + +func TestPixelLauncherRemoveReport(t *testing.T) { + for _, c := range []struct { + ok, saved bool + out string + warn bool + has string + }{ + {true, true, "Success\nSAVED\n", false, "实例 2 做:已卸载并写盘"}, + {true, false, "Success\nUNSAVED\n", true, "实例 2 做:已卸载,但 20 秒内没见系统写盘,下次开机会再检查"}, + {false, false, "Failure [DELETE_FAILED_INTERNAL_ERROR]\n", true, "实例 2 做失败,下次开机再试: Failure [DELETE_FAILED_INTERNAL_ERROR]"}, + {false, false, "", true, "失败,下次开机再试: 无输出"}, + } { + r := pixelLauncherRemoveReport(2, "做", c.ok, c.saved, c.out) + if r.warn != c.warn || !strings.Contains(r.msg, c.has) { + t.Errorf("%+v: %+v", c, r) + } + } +} + +// The removal runs inside `su 0 sh -c '...'` (no single quote), uninstalls for user 0 only, and waits on the file +// the package manager writes the per-user state to. +func TestPixelLauncherRemoveScript(t *testing.T) { + s := pixelLauncherRemoveScript + for _, want := range []string{"pm uninstall --user 0 " + pixelLauncherPackage + " || exit 1", + "/data/system/users/0/package-restrictions.xml", "stat -c %y", "echo SAVED", "echo UNSAVED", "-lt 40", "sleep 0.5"} { + if !strings.Contains(s, want) { + t.Errorf("script lacks %q: %s", want, s) + } + } + if strings.Contains(s, "'") { + t.Error("script has a single quote") + } + if strings.Index(s, "b=$(stat") < strings.Index(s, "pm uninstall") { + t.Error("the time before the write is taken before pm returns") + } + if pixelLauncherRemoveTimeout <= 20*time.Second { + t.Errorf("timeout %v does not cover the 20 s wait", pixelLauncherRemoveTimeout) + } +} diff --git a/internal/emu/early_windows_test.go b/internal/emu/early_windows_test.go new file mode 100644 index 0000000..316bed0 --- /dev/null +++ b/internal/emu/early_windows_test.go @@ -0,0 +1,51 @@ +//go:build windows + +package emu + +import ( + "context" + "testing" + "time" +) + +// TestWaitBootEarly: the boot wait hands each poll where adb answers before the boot has completed to early, until +// early says done; a poll where adb does not answer does not call it; the boot completing ends the wait. +func TestWaitBootEarly(t *testing.T) { + m, _ := opsTestManager(t) + q, _ := startSleeper(t) + bootAdbFakes(t, q, false) + saved := waitBootProbe + t.Cleanup(func() { waitBootProbe = saved }) + // polls: adb not up, up (not done), up (done), up, booted + probes := []struct{ booted, answered bool }{{false, false}, {false, true}, {false, true}, {false, true}, {true, true}} + n := 0 + waitBootProbe = func(_ *Manager, _ context.Context, _ int, _ time.Duration, _ bool) (bool, bool) { + p := probes[min(n, len(probes)-1)] + n++ + return p.booted, p.answered + } + var calls []int // the probe number each early call followed + early := func() bool { + calls = append(calls, n) + return len(calls) == 2 + } + got, err := m.waitBoot(context.Background(), 3, time.Minute, &q, nil, "", &progressor{}, nil, nil, early) + if err != nil || got.PID != q.PID { + t.Fatalf("waitBoot: %v %+v", err, got) + } + if len(calls) != 2 || calls[0] != 2 || calls[1] != 3 { + t.Errorf("early after probes %v, want [2 3]", calls) + } + if n != 5 { + t.Errorf("%d probes, want 5", n) + } + + // booted at once: early never runs + n, calls = len(probes)-1, nil + if _, err := m.waitBoot(context.Background(), 3, time.Minute, &q, nil, "", &progressor{}, nil, nil, early); err != nil { + t.Fatal(err) + } + if len(calls) != 0 { + t.Errorf("early ran on a booted guest: %v", calls) + } +} diff --git a/internal/emu/firstboot.go b/internal/emu/firstboot.go index 0868f78..51e819a 100644 --- a/internal/emu/firstboot.go +++ b/internal/emu/firstboot.go @@ -169,16 +169,20 @@ func (m *Manager) installLauncher(ctx context.Context, i int) string { // The stock launcher is uninstalled for user 0 (the system partition keeps it; `cmd package install-existing` // restores it), not disabled: disabling sends PACKAGE_CHANGED, SystemUI's OverviewProxyService then looks for // the stock launcher's recents service and crashes on null, which breaks the home switch transition and leaves - // only the wallpaper on the first boot. Uninstalling sends PACKAGE_REMOVED, which it ignores (10-08). - cmds := []string{ - "cmd package set-home-activity " + lightLauncherHome, - "pm uninstall --user 0 " + pixelLauncherPackage, - "input keyevent KEYCODE_HOME", - } - if res := m.shell(ctx, i, strings.Join(cmds, " ; "), 0); res.Code != 0 { + // only the wallpaper on the first boot. Uninstalling sends PACKAGE_REMOVED, which it ignores (10-08). The removal + // is waited for until it is on disk (pixelLauncherRemoveScript); one that fails is retried at the next boot + // (ensurePixelLauncherRemoved), the light launcher is home all the same. + if res := m.shell(ctx, i, "cmd package set-home-activity "+lightLauncherHome, 0); res.Code != 0 { m.Log.Warnf("实例 %d 设置轻量桌面失败: %s", i, res.Out) return "pixel" } + ok, saved, out := m.removePixelLauncher(ctx, i) + if r := pixelLauncherRemoveReport(i, "卸载原生 Pixel 桌面", ok, saved, out); r.warn { + m.logReport(r) + } + if res := m.shell(ctx, i, "input keyevent KEYCODE_HOME", 0); res.Code != 0 { + m.Log.Warnf("实例 %d 回到轻量桌面失败: %s", i, res.Out) + } return lightLauncherPackage } diff --git a/internal/emu/guestfix.go b/internal/emu/guestfix.go index 6e36fff..9aaf184 100644 --- a/internal/emu/guestfix.go +++ b/internal/emu/guestfix.go @@ -105,12 +105,84 @@ func (m *Manager) ensureGuestFixes(ctx context.Context, inst *avd.Instance, mode }, profiles, mode == setupOwed, until) } +// earlyGuestFixes mounts the guest library fixes of a launched boot while that boot is still on its way: adb answers, +// zygote runs, sys.boot_completed is not 1 yet. The zygote restart then cuts short a framework start nobody has seen, +// and a window keeps showing the boot animation until the restarted framework is up, instead of the home screen going +// away and coming back after the boot (11-15). Measured on a 1080p instance: adb answers about 11 s after the launch, +// the boot completes about 5 s later. +// +// done=false: the guest is not that far yet (adb error, zygote not running): the boot wait asks again at its next +// poll. Everything else is done, also a failure or a boot that completed meanwhile: afterBoot's guest fix step then +// mounts what is still missing, after the boot as before. restarted: zygote was restarted here. +func (m *Manager) earlyGuestFixes(ctx context.Context, inst *avd.Instance, prog *progressor) (done, restarted bool) { + i := inst.Index + profiles, err := m.guestLibFixes(inst) + if err != nil { + return true, false // afterBoot's step says why + } + state, ok := earlyBootState(m.shell(ctx, i, earlyBootProbe, statusAdbTimeout)) + switch { + case !ok: + return false, false + case state.booted: + return true, false + case !state.zygote: + return false, false + } + remote, ok := m.pushGuestScript(ctx, i, guest.LibFix) + if !ok { + return true, false + } + prog.emit("vulkan_fix", fmt.Sprintf("实例 %d 开机过程中挂客体库补丁(Vulkan 驱动、ARM 转译层)", i), 0) + g := m.guestIO(ctx, i) + restarted, _ = m.mountGuestFixes(ctx, i, guestFixIO{ + guestIO: g, + remote: remote, + library: func(p guestpatch.Profile) string { return m.patchedGuestLibrary(ctx, i, p) }, + waitBack: func(uiBefore string) bool { + // The boot may have completed right before the restart: sys.boot_completed then stays 1 while the + // framework comes back, and the boot wait would go on at once. Otherwise it waits for the restarted one. + if m.bootCompleted(ctx, i, statusAdbTimeout, false) { + return m.waitFrameworkBack(ctx, g, uiBefore, frameworkBackTimeout) + } + return true + }, + early: true, + }, profiles, false, time.Time{}) + return true, restarted +} + +// earlyBootProbe prints the zygote service state and sys.boot_completed (no root needed). +const earlyBootProbe = `echo "zygote=$(getprop init.svc.zygote) booted=$(getprop sys.boot_completed)"` + +// bootState is earlyBootProbe's answer: zygote runs, the boot has completed. +type bootState struct{ zygote, booted bool } + +// earlyBootState reads earlyBootProbe's output; ok=false when adb failed or the line is missing. +func earlyBootState(res adb.Result) (bootState, bool) { + if res.Code != 0 { + return bootState{}, false + } + for _, line := range outputLines(res.Out) { + f := strings.Fields(line) + if len(f) == 0 || !strings.HasPrefix(f[0], "zygote=") { + continue + } + var s bootState + s.zygote = f[0] == "zygote=running" + s.booted = len(f) > 1 && f[1] == "booted=1" + return s, true + } + return bootState{}, false +} + // guestFixIO is what mountGuestFixes works through: the instance's adb in Manager, a fake guest in tests. type guestFixIO struct { guestIO remote string // libfix.sh in the guest (pushed already) library func(p guestpatch.Profile) string // the host's patched copy (patchedGuestLibrary); "" when it cannot be had waitBack func(uiBefore string) bool // after the zygote restart (waitFrameworkBack) + early bool // during the boot (earlyGuestFixes): the messages say so } // report is one log line: a warning or an info. @@ -293,6 +365,11 @@ func (m *Manager) mountGuestFixes(ctx context.Context, i int, fx guestFixIO, pro if ctx.Err() != nil { return true, false // canceled while waiting: zygote did restart, but nothing is known about the framework } + if fx.early && back { + m.Log.Infof("实例 %d 客体库补丁已在开机过程中挂上(%s),zygote 已重启,接着等安卓开机完成", i, + strings.Join(mounted, "、")) + return true, false + } how := "超时未回来" if back { how = "已回来" diff --git a/internal/emu/guestfix_test.go b/internal/emu/guestfix_test.go index 8d94a78..de7bbd9 100644 --- a/internal/emu/guestfix_test.go +++ b/internal/emu/guestfix_test.go @@ -420,6 +420,7 @@ func TestMountGuestFixes(t *testing.T) { cases := []struct { name string owed bool + early bool // during the boot (earlyGuestFixes) installing bool // an install holds the guest lock from the start installDuringPush bool // an install takes it while a library is uploaded pushFail []string @@ -436,6 +437,12 @@ func TestMountGuestFixes(t *testing.T) { {name: "launched, cached in the guest", fixes: []string{mountedBoth}, commands: []string{"pidof", "fix", "wait"}, runs: [][]string{bothRuns}, locked: []bool{true}, restarted: true, level: logx.Info, has: []string{"客体库补丁已挂上(" + both + "),zygote 重启后系统界面已回来"}}, + {name: "launched early, cached in the guest", early: true, fixes: []string{mountedBoth}, + commands: []string{"pidof", "fix", "wait"}, runs: [][]string{bothRuns}, locked: []bool{true}, restarted: true, + level: logx.Info, has: []string{"客体库补丁已在开机过程中挂上(" + both + "),zygote 已重启,接着等安卓开机完成"}}, + {name: "launched early, nothing to mount", early: true, fixes: []string{gfLine(gfVK, "IMAGE_PATCHED") + + gfLine(gfNDK, "ABSENT") + "UNCHANGED\r\n"}, commands: []string{"pidof", "fix"}, runs: [][]string{bothRuns}, + locked: []bool{true}, level: logx.Info, has: []string{"已是补丁版,不用挂"}}, {name: "launched, both uploaded", fixes: []string{uploadBoth, mountedBoth}, commands: []string{"pidof", "fix", "push", "push", "fix", "wait"}, runs: [][]string{bothRuns, bothRuns}, pushes: []string{gfVK.UploadPath, gfNDK.UploadPath}, locked: []bool{true, true}, restarted: true, @@ -532,7 +539,9 @@ func TestMountGuestFixes(t *testing.T) { f.onPush = takeInstall } - restarted, pending := m.mountGuestFixes(context.Background(), 3, f.io(), gfAll, c.owed, until) + fx := f.io() + fx.early = c.early + restarted, pending := m.mountGuestFixes(context.Background(), 3, fx, gfAll, c.owed, until) install.Unlock() if restarted != c.restarted || pending != c.pending { diff --git a/internal/emu/ime.go b/internal/emu/ime.go index 8adcb53..6e9dfa4 100644 --- a/internal/emu/ime.go +++ b/internal/emu/ime.go @@ -392,26 +392,3 @@ func installFailure(res adb.Result) string { } return fmt.Sprintf("退出码 %d", res.Code) } - -// recheckHostIme runs after the zygote restart of the Vulkan fix: the default was the host IME at the end of the IME -// step; when it is not any more, set it back (AUTO-MAS _recheck_host_ime; the launcher only reports it). -func (m *Manager) recheckHostIme(i int, g guestIO) { - current, ok := defaultImeFrom(g.shell(hostImeReadDefault, 0).Out) - if ok && current == hostImeID { - return - } - if !ok { - m.Log.Warnf("实例 %d 宿主输入法: 重启 zygote 后读不出默认输入法", i) - return - } - restored, rok := defaultImeFrom(g.shell("ime set "+hostImeID+" >/dev/null; "+hostImeReadDefault, 0).Out) - if rok && restored == hostImeID { - m.Log.Infof("实例 %d 宿主输入法: 重启 zygote 后默认变成了 %s,已设回", i, orText(current, "没设")) - return - } - now := "读不出" - if rok { - now = orText(restored, "没设") - } - m.Log.Warnf("实例 %d 宿主输入法: 重启 zygote 后默认变成了 %s,没能设回(现在 %s)", i, orText(current, "没设"), now) -} diff --git a/internal/emu/ime_test.go b/internal/emu/ime_test.go index 9e51492..6c0649f 100644 --- a/internal/emu/ime_test.go +++ b/internal/emu/ime_test.go @@ -529,46 +529,6 @@ func TestRunHostImeProbeFails(t *testing.T) { } } -func TestRecheckHostIme(t *testing.T) { - cases := []struct { - name string - def string // before - fails bool // ime set does not take - after string - level logx.Level - msg string - }{ - {"still ours", hostImeID, false, hostImeID, -1, ""}, - {"lost: set back", gboard, false, hostImeID, logx.Info, - "实例 4 宿主输入法: 重启 zygote 后默认变成了 " + gboard + ",已设回"}, - {"lost: cannot set back", "", true, "", logx.Warn, - "实例 4 宿主输入法: 重启 zygote 后默认变成了 没设,没能设回(现在 没设)"}, - } - for _, c := range cases { - g := fakeImeGuest{imeState: imeState{installed: 3, build: releaseSigner, enabled: true, def: c.def, marker: true}, - imeFaults: imeFaults{setFails: c.fails}} - m, lines := recordingManager() - m.recheckHostIme(4, g.io()) - if g.def != c.after || len(g.unknown) > 0 { - t.Errorf("%s: default %q (unknown %q), want %q", c.name, g.def, g.unknown, c.after) - } - switch { - case c.msg == "" && len(*lines) != 0: - t.Errorf("%s: logged %v", c.name, *lines) - case c.msg != "" && (len(*lines) != 1 || (*lines)[0].level != c.level || (*lines)[0].msg != c.msg): - t.Errorf("%s: log %v, want %v %q", c.name, *lines, c.level, c.msg) - } - } - // settings unreadable: no ime set, a warning - m, lines := recordingManager() - m.recheckHostIme(4, guestIO{shell: func(string, time.Duration) adb.Result { - return adb.Result{Code: -1, Out: "adb shell 超时(30 秒)"} - }}) - if len(*lines) != 1 || (*lines)[0].msg != "实例 4 宿主输入法: 重启 zygote 后读不出默认输入法" { - t.Errorf("unreadable: %v", *lines) - } -} - // TestSetupHostImeSkips: the quiet and the warned skips before the guest is touched (no adb here at all). func TestSetupHostImeSkips(t *testing.T) { dir := testutil.TempDir(t) diff --git a/internal/emu/pixellauncher.go b/internal/emu/pixellauncher.go new file mode 100644 index 0000000..b89bd88 --- /dev/null +++ b/internal/emu/pixellauncher.go @@ -0,0 +1,85 @@ +package emu + +import ( + "context" + "fmt" + "strings" + "time" + + "modavd/internal/adb" +) + +// pixelLauncherRemoveScript removes the stock launcher for user 0 (run as root) and waits until the package manager +// has written that to disk: it only schedules the write of package-restrictions.xml (10 s later), so a framework +// restart or a power cut before then brings the launcher back at the next boot. 11-15: the first-boot setup removed +// it 2.6 s before the zygote restart of the guest library fixes, and every instance created since kept the stock +// launcher, which draws its taskbar over every home app once the display counts as a tablet (1080p, 280 dpi). +// Prints SAVED once the file's modification time changed, UNSAVED after 20 s without; exits 1 when pm fails. The time +// is taken after pm returns: a write that starts later has the removal in it, one that ran during pm may not have. +const pixelLauncherRemoveScript = `f=/data/system/users/0/package-restrictions.xml; ` + + `pm uninstall --user 0 ` + pixelLauncherPackage + ` || exit 1; b=$(stat -c %y $f 2>/dev/null); n=0; ` + + `while [ $n -lt 40 ]; do sleep 0.5; [ "$(stat -c %y $f 2>/dev/null)" != "$b" ] && { echo SAVED; exit 0; }; ` + + `n=$((n+1)); done; echo UNSAVED` + +// pixelLauncherRemoveTimeout covers the script's 20 s wait and pm itself. +const pixelLauncherRemoveTimeout = 45 * time.Second + +// pixelLauncherListed: `pm list packages --user 0 ` lists the stock launcher itself (the filter also matches +// longer names). +func pixelLauncherListed(out string) bool { + for _, line := range outputLines(out) { + if strings.TrimSpace(line) == "package:"+pixelLauncherPackage { + return true + } + } + return false +} + +// removePixelLauncher runs pixelLauncherRemoveScript. ok: pm removed it; saved: the removal is on disk. out is the +// script's output for the messages. +func (m *Manager) removePixelLauncher(ctx context.Context, i int) (ok, saved bool, out string) { + res := m.su(ctx, i, pixelLauncherRemoveScript, pixelLauncherRemoveTimeout) + ok, saved = pixelLauncherRemoveResult(res) + return ok, saved, res.Out +} + +// pixelLauncherRemoveResult reads pixelLauncherRemoveScript's result: ok when it exited 0 with SAVED or UNSAVED last. +func pixelLauncherRemoveResult(res adb.Result) (ok, saved bool) { + last := lastNonEmptyLine(res.Out) + ok = res.Code == 0 && (last == "SAVED" || last == "UNSAVED") + return ok, ok && last == "SAVED" +} + +// pixelLauncherRemoveReport is the log line of removePixelLauncher's result (what: what was done, for the message). +func pixelLauncherRemoveReport(i int, what string, ok, saved bool, out string) report { + switch { + case !ok: + return report{true, fmt.Sprintf("实例 %d %s失败,下次开机再试: %s", i, what, orText(tail(strings.TrimSpace(out), 200), "无输出"))} + case !saved: + return report{true, fmt.Sprintf("实例 %d %s:已卸载,但 20 秒内没见系统写盘,下次开机会再检查", i, what)} + } + return report{false, fmt.Sprintf("实例 %d %s:已卸载并写盘", i, what)} +} + +// ensurePixelLauncherRemoved removes the stock launcher again when an instance set up with the light launcher still +// has it for user 0 (see pixelLauncherRemoveScript for how that happened). Instances whose first-boot setup kept the +// stock launcher (meta launcher "pixel") are left alone. Every boot after the first; failures are only logged. +func (m *Manager) ensurePixelLauncherRemoved(ctx context.Context, i int) { + meta := m.Root.InstanceMeta(i) + if meta == nil { + return + } + if launcher, _ := meta.Get("launcher").Str(); launcher != lightLauncherPackage { + return + } + res := m.shell(ctx, i, "pm list packages --user 0 "+pixelLauncherPackage, 0) + if res.Code != 0 { + m.Log.Debugf("实例 %d 读不出原生桌面在不在: %s", i, tail(res.Out, 200)) + return + } + if !pixelLauncherListed(res.Out) { + return + } + ok, saved, out := m.removePixelLauncher(ctx, i) + m.logReport(pixelLauncherRemoveReport(i, "原生 Pixel 桌面又出现了(之前的卸载没写进磁盘),重新卸载", ok, saved, out)) +} diff --git a/internal/emu/qemu_errors_test.go b/internal/emu/qemu_errors_test.go index 63714a7..6ab2ff6 100644 --- a/internal/emu/qemu_errors_test.go +++ b/internal/emu/qemu_errors_test.go @@ -75,7 +75,7 @@ func TestQemuWaitsPropagateUnsupported(t *testing.T) { "waitQemuGone": func() error { return m.waitQemuGone(ctx, 1) }, "stopAndWait": func() error { return m.stopAndWait(ctx, 1) }, "waitBoot": func() error { - _, err := m.waitBoot(ctx, 1, 0, nil, nil, "", nil, nil, nil) + _, err := m.waitBoot(ctx, 1, 0, nil, nil, "", nil, nil, nil, nil) return err }, } { diff --git a/internal/emu/start.go b/internal/emu/start.go index 78fdbb2..5aaad95 100644 --- a/internal/emu/start.go +++ b/internal/emu/start.go @@ -28,10 +28,10 @@ const ( bootProgressFrom = 100 bootProgressTo = 600 progressBooted = 610 + progressVulkanFix = 615 progressTune = 620 progressIme = 700 progressFirstBoot = 800 - progressVulkanFix = 900 bootReportInterval = 5 * time.Second // how long a start waits for a boot lock nobody should hold (the start lock is ours) bootLockWait = 10 * time.Second @@ -216,6 +216,7 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption var marker *setupMarker var mode bootSetup var qemu host.Process + earlyRestarted := false // earlyGuestFixes restarted zygote during the boot // owed: errors from here on leave a boot whose setup the next start finishes owed := func(err error) error { if marker == nil { @@ -355,7 +356,17 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption prog.emit("launch", fmt.Sprintf("实例 %d 的模拟器已拉起(pid %d),等安卓开机", i, p.PID), progressLaunch) } - qemu, err = m.waitBoot(ctx, i, timeout, emulator, adopted, res.LogFile, prog, onQemu, &stopSeen) + // A launched boot of an instance set up before mounts the guest library fixes under the boot animation; the + // first boot of a new one leaves them to afterBoot (system_server's very first start is not cut short). + var early func() bool + if mode == setupLaunched && m.initialized(i) { + early = func() bool { + done, restarted := m.earlyGuestFixes(ctx, inst, prog) + earlyRestarted = earlyRestarted || restarted + return done + } + } + qemu, err = m.waitBoot(ctx, i, timeout, emulator, adopted, res.LogFile, prog, onQemu, &stopSeen, early) bootLock.Unlock() if err == nil { break @@ -400,7 +411,7 @@ func (m *Manager) start(ctx context.Context, inst *avd.Instance, opt StartOption return nil, m.startFailure(ctx, i, owed(err), unknownState) } res.FirstBoot = ab.FirstBoot - res.ZygoteRestarted = ab.ZygoteRestarted + res.ZygoteRestarted = ab.ZygoteRestarted || earlyRestarted res.LogcatFile = ab.LogcatFile res.HostIME = ab.HostIME @@ -489,9 +500,10 @@ func pollUntil(ctx context.Context, limit, every time.Duration, ok func() bool) // one may have missed a server restart and is. Fails when the deadline passes, when emulator.exe has exited while // no qemu is there, or when the adopted qemu is gone. onQemu, when set, is told the qemu process each time the scan // finds it (the setup marker records it the first time). stopSeen, when set and a qemu was adopted, is set to true -// once a stop of this instance is seen holding its lock (relaunchAfterAdoptedGone). +// once a stop of this instance is seen holding its lock (relaunchAfterAdoptedGone). early, when set, runs each time +// adb answers before the boot has completed, until it returns true (earlyGuestFixes). func (m *Manager) waitBoot(ctx context.Context, i int, timeout time.Duration, emulator, adopted *host.Process, - logPath string, prog *progressor, onQemu func(host.Process), stopSeen *bool) (host.Process, error) { + logPath string, prog *progressor, onQemu func(host.Process), stopSeen *bool, early func() bool) (host.Process, error) { launched := emulator != nil started := time.Now() deadline := started.Add(timeout) @@ -510,8 +522,15 @@ func (m *Manager) waitBoot(ctx context.Context, i int, timeout time.Duration, em // before the getprop, which may take seconds: a cancel then must find qemu already recorded onQemu(p) } - if found && m.bootCompleted(ctx, i, statusAdbTimeout, !launched) { - return p, nil + if found { + done, answered := waitBootProbe(m, ctx, i, statusAdbTimeout, !launched) + if done { + return p, nil + } + if answered && early != nil && early() { + early = nil + continue // ask getprop again right away + } } if err := ctxErr(ctx); err != nil { return host.Process{}, err @@ -592,6 +611,9 @@ var emulatorReportedBoot = func(r *root.Root, i int, qemu host.Process) bool { // waitBootFindQemu is the boot wait's process scan (a variable for the tests). var waitBootFindQemu = func(m *Manager, i int) (host.Process, bool, error) { return m.findQemu(i) } +// waitBootProbe is the boot wait's getprop (a variable for the tests). +var waitBootProbe = (*Manager).bootProbe + // registerBooted is adb's RegisterBooted for instance i (a variable for the tests). var registerBooted = func(ctx context.Context, m *Manager, i int) bool { return m.ADB.RegisterBooted(ctx, m.Root.Ports().Serial(i)) diff --git a/internal/emu/start_test.go b/internal/emu/start_test.go index c6b8514..9d97743 100644 --- a/internal/emu/start_test.go +++ b/internal/emu/start_test.go @@ -408,8 +408,8 @@ func TestProgressor(t *testing.T) { } func TestProgressOrder(t *testing.T) { - order := []int{progressLaunch, bootProgressFrom, bootProgressTo, progressBooted, progressTune, progressIme, - progressFirstBoot, progressVulkanFix, progressTotal} + order := []int{progressLaunch, bootProgressFrom, bootProgressTo, progressBooted, progressVulkanFix, progressTune, + progressIme, progressFirstBoot, progressTotal} for k := 1; k < len(order); k++ { if order[k] <= order[k-1] { t.Errorf("progress constants out of order at %d: %v", k, order) @@ -554,11 +554,11 @@ func TestWaitBootAdoptedGone(t *testing.T) { q, kill := startSleeper(t) kill() stopSeen := false - _, err := m.waitBoot(context.Background(), 3, 10*time.Second, nil, &q, "", &progressor{}, nil, &stopSeen) + _, err := m.waitBoot(context.Background(), 3, 10*time.Second, nil, &q, "", &progressor{}, nil, &stopSeen, nil) if !errors.Is(err, errAdoptedGone) || errs.CodeOf(err) != errs.LaunchFailed || stopSeen { t.Fatalf("adopted qemu gone: %v, stopSeen %v", err, stopSeen) } - _, err = m.waitBoot(context.Background(), 3, 10*time.Second, &q, nil, "", &progressor{}, nil, &stopSeen) + _, err = m.waitBoot(context.Background(), 3, 10*time.Second, &q, nil, "", &progressor{}, nil, &stopSeen, nil) if errors.Is(err, errAdoptedGone) || errs.CodeOf(err) != errs.LaunchFailed { t.Fatalf("launched emulator gone: %v", err) } @@ -570,11 +570,11 @@ func TestWaitBootAdoptedGone(t *testing.T) { defer l.Unlock() // a launched emulator.exe that still runs: the wait polls (and times out) without looking at the stop lock live, _ := startSleeper(t) - _, err = m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &live, nil, "", &progressor{}, nil, &stopSeen) + _, err = m.waitBoot(context.Background(), 3, 1500*time.Millisecond, &live, nil, "", &progressor{}, nil, &stopSeen, nil) if errs.CodeOf(err) != errs.Timeout || stopSeen { t.Fatalf("launched emulator during a stop: %v, stopSeen %v", err, stopSeen) } - _, err = m.waitBoot(context.Background(), 3, 10*time.Second, nil, &q, "", &progressor{}, nil, &stopSeen) + _, err = m.waitBoot(context.Background(), 3, 10*time.Second, nil, &q, "", &progressor{}, nil, &stopSeen, nil) if !errors.Is(err, errAdoptedGone) || !stopSeen { t.Fatalf("adopted qemu gone during a stop: %v, stopSeen %v", err, stopSeen) } From fe281de81b2ef8adceb034359fcf52c03f2013e7 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:41:27 +0000 Subject: [PATCH 5/9] =?UTF-8?q?=E5=8A=A0=20changelog.d=EF=BC=9A=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E7=9C=8B=E5=BE=97=E8=A7=81=E7=9A=84=E6=94=B9=E5=8A=A8?= =?UTF-8?q?=E5=9C=A8=20PR=20=E9=87=8C=E5=B8=A6=E4=B8=80=E8=A1=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E8=AF=B4=E6=98=8E=20(#179)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs ModAVD/ModAVD#216 --- changelog.d/README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 changelog.d/README.md diff --git a/changelog.d/README.md b/changelog.d/README.md new file mode 100644 index 0000000..f58ac25 --- /dev/null +++ b/changelog.d/README.md @@ -0,0 +1,23 @@ +# 更新说明 / Release note lines + +用户看得见的改动,在同一个 PR 里往这个文件夹加一个文件,写一行给用户看的话。ModAVD 发版时,工具把这个仓库上一版以后新加的文件汇总进 ModAVD 发版公告的「更新内容」,并在行尾补上这个 PR 的编号。不加文件的 PR 不会出现在公告里。 + +- **文件名**:`<名字>.<类型>.md`。名字用小写字母、数字、`-`、`_`,起一个不会和别的改动重复的(比如 issue 号加几个词:`210-resize-crash.fix.md`)。 +- **类型**:`feat` 新增,`fix` 修复,`change` 变更,`remove` 移除。 +- **内容**:只有一行,不超过 60 字,不能有 `--`。写用户会看到的结果,不写原因和实现,比如「调高分辨率后开机不再卡死退出」。 +- 想让公告指向 issue 而不是 PR,就自己在行尾写上,issue 都在 ModAVD 仓库,要写全称:`……不再卡死退出 (ModAVD/ModAVD#210)`;这样工具不再补 PR 编号。 +- 只和开发、测试、CI、文档有关的 PR 不用加。 +- 已经发过版的文件不要改内容、也不要重复用它的名字;以后的改动另起一个文件。 + +汇总的工具和完整的说明在 ModAVD 仓库:[changelog.d/README.md](https://github.com/ModAVD/ModAVD/blob/main/changelog.d/README.md)、[tools/pubrel/README.md](https://github.com/ModAVD/ModAVD/blob/main/tools/pubrel/README.md)。 + +--- + +A change that users can see adds one file here, in the same pull request, with a single line written for users. When ModAVD is released, its tools collect the files this repository gained since the previous release into the ModAVD release notes and append the pull request number. A pull request without a file is not announced. + +- **Name**: `..md`, the name in lowercase letters, digits, `-`, `_`, and unique (for example the issue number and a few words: `210-resize-crash.fix.md`). +- **Type**: `feat` (新增), `fix` (修复), `change` (变更), `remove` (移除). +- **Content**: one line in Chinese, at most 60 characters, without `--`. Say what users will notice, not the cause or the implementation. +- To point at an issue instead of the pull request, end the line with it yourself, in full: `…… (ModAVD/ModAVD#210)`. +- Pull requests that only touch development, tests, CI or documentation need no file. +- Do not edit or reuse a file that has already been released; a later change takes a new file. From 2bf52daea52c4c6eac09a5b0ca031ffeda3935f9 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:52:40 +0000 Subject: [PATCH 6/9] =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E7=9B=98=E5=90=8D?= =?UTF-8?q?=E5=8D=95=E5=8A=A0=E4=B8=8A=E7=BB=88=E6=9C=AB=E5=9C=B0=EF=BC=9A?= =?UTF-8?q?=E5=90=8C=E4=B8=80=E5=A5=97=E4=B8=8B=E8=BD=BD=E5=99=A8=EF=BC=8C?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=92=8C=E5=86=99=E6=B3=95=E7=9B=B8=E5=90=8C?= =?UTF-8?q?=20(#180)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs ModAVD/ModAVD#35 --- README.en.md | 2 +- README.md | 2 +- changelog.d/dldisk-endfield.feat.md | 1 + internal/guest/dldisk_sh_test.go | 22 ++++++++++++++++++++++ internal/guest/scripts/modavd-dldisk.sh | 4 +++- 5 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 changelog.d/dldisk-endfield.feat.md diff --git a/README.en.md b/README.en.md index 3131e28..d11654c 100644 --- a/README.en.md +++ b/README.en.md @@ -202,7 +202,7 @@ On Apple Silicon macOS, downloads and imports use Android 15 Google Play `arm64- - After the emulator is killed or the computer crashes, the download folder is what it was at its last commit, at most 3 seconds of progress short, and the game carries on. What the game has unpacked, accounts and settings are not on this disk and behave as before. - A watcher looks every 3 seconds: the disk is mounted once the game is installed, before its first start; a running game is left alone; a download that began in the plain folder finishes there first; uninstalling the game or clearing its app data removes the disk. - The disk is `/data/local/tmp/modavd-dldisk//dl.img` in the guest, a sparse file of at most 16 GB; space of deleted packages goes back to the data disk. Downloading is faster than unpacking, so finished packages queue up on the disk: during a full resource download the data disk's peak use is about 6 GB higher than before. No disk is made when the data disk has less than 2 GB free. - - The list holds the official `com.hypergryph.arknights` and the bilibili `com.hypergryph.arknights.bilibili` (not tested on the latter; the folder is the same). + - The list holds Arknights, official `com.hypergryph.arknights` and bilibili `com.hypergryph.arknights.bilibili` (not tested on the latter; the folder is the same), and Arknights: Endfield `com.hypergryph.endfield` (same downloader, same folder and write pattern). - Boot with the environment variable `MODAVD_DL_DISK=off` to move unfinished downloads back into the plain folder, delete the disk and start no watcher. Two display presets are available: 1080p is 1920×1080 / DPI 280; 720p is 1280×720 / DPI 240. New instances default to 1080p. 720p uses fewer resources. The manager forms, CLI `--resolution 1080|720` and MCP `resolution` share these presets. Existing landscape or portrait 1920×1080 instances stay at 1080p; other configurations, including missing dimensions, stay at 720p. Changing the preset updates width, height and DPI together, preserves orientation, and takes effect at the next cold boot. DPI is not a separate option. No runtime `wm size` or `wm density` is used. Update the resolution in your automation tool as well. diff --git a/README.md b/README.md index 634982d..815bc16 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ Apple Silicon macOS 的下载与导入使用 Android 15 Google Play `arm64-v8a` - 模拟器被强杀或电脑崩溃以后,下载目录回到最后一次落盘时的样子,最多少 3 秒的进度,游戏接着下。解压出来的资源、账号、设置不在这块盘上,和以前一样。 - 守护每 3 秒看一次:游戏装上以后、第一次启动之前就把盘挂好;游戏开着时不动它;普通目录里有下到一半的,等那一轮下完再挂;卸载游戏或清了它的应用数据,盘跟着删。 - 盘是客体里的 `/data/local/tmp/modavd-dldisk/<包名>/dl.img`,一个最大 16 GB 的稀疏文件,删掉的包占的空间会还给数据盘。下载比解压快,下好的包会先堆在盘里:下整包资源时,数据盘的占用高峰比以前多约 6 GB。数据盘剩余不到 2 GB 时不建盘。 - - 名单里是官服 `com.hypergryph.arknights` 和 B 服 `com.hypergryph.arknights.bilibili`(B 服没有实测,目录相同)。 + - 名单里是明日方舟官服 `com.hypergryph.arknights`、B 服 `com.hypergryph.arknights.bilibili`(B 服没有实测,目录相同),以及明日方舟:终末地 `com.hypergryph.endfield`(同一套下载器,目录和写法相同)。 - 设环境变量 `MODAVD_DL_DISK=off` 再开机:把盘里还没下完的搬回普通目录,删掉盘,不再起守护。 分辨率只有两档:1080p 为 1920×1080 / DPI 280,720p 为 1280×720 / DPI 240。新建默认 1080p,720p 更省资源。管理器的新建和实例设置、CLI `--resolution 1080|720`、MCP `resolution` 使用同一套档位。已有实例按宽高识别:横屏或竖屏的 1920×1080 保持 1080p,其余配置及缺字段的旧配置保持 720p。换档联动宽、高、DPI,保留方向,下次冷启动生效;DPI 不单独设置,不使用运行时 `wm size` 或 `wm density`。自动化工具里的分辨率也要跟着改。 diff --git a/changelog.d/dldisk-endfield.feat.md b/changelog.d/dldisk-endfield.feat.md new file mode 100644 index 0000000..a963e59 --- /dev/null +++ b/changelog.d/dldisk-endfield.feat.md @@ -0,0 +1 @@ +终末地下载资源也走下载盘,不再被频繁落盘拖慢 (ModAVD/ModAVD#35) diff --git a/internal/guest/dldisk_sh_test.go b/internal/guest/dldisk_sh_test.go index efaeca0..c564c66 100644 --- a/internal/guest/dldisk_sh_test.go +++ b/internal/guest/dldisk_sh_test.go @@ -242,6 +242,28 @@ func TestDownloadDiskNotInstalled(t *testing.T) { } } +// Every game on the list gets a disk of its own, on its own folder. +func TestDownloadDiskEveryListedGame(t *testing.T) { + g := newDDGuest(t) + pkgs := []string{"com.hypergryph.arknights", "com.hypergryph.arknights.bilibili", "com.hypergryph.endfield"} + for n, pkg := range pkgs { + g.mkdir("/data/data/" + pkg) + g.write("/data/data/"+pkg+".owner", "1019"+string(rune('4'+n))+":1019"+string(rune('4'+n))) + } + out := g.run("once") + for _, pkg := range pkgs { + if !g.mountedOn(ddBase+"/"+pkg+"/inner") || !g.mountedOn(ddView+"/"+pkg+ddRel) { + t.Errorf("%s: not on its disk; mountinfo:\n%s", pkg, g.read("/proc/self/mountinfo")) + } + if !strings.Contains(out, pkg+": disk mounted (new image)") { + t.Errorf("%s: output %q", pkg, out) + } + } + if g.calls("mke2fs.log") != len(pkgs) { + t.Errorf("%d images made", g.calls("mke2fs.log")) + } +} + // Installed and never started: the folders are made as the system makes them, so the disk is there before the game's // first download. func TestDownloadDiskBeforeFirstStart(t *testing.T) { diff --git a/internal/guest/scripts/modavd-dldisk.sh b/internal/guest/scripts/modavd-dldisk.sh index 93df365..33ca3d1 100644 --- a/internal/guest/scripts/modavd-dldisk.sh +++ b/internal/guest/scripts/modavd-dldisk.sh @@ -53,7 +53,9 @@ BASE=$R/data/local/tmp/$TAG MEDIA=$R/data/media/0/Android/data VIEW=$R/mnt/user/0/emulated/0/Android/data MI=$R/proc/self/mountinfo -LIST="com.hypergryph.arknights:files/HGGameUpdate/HGDownload com.hypergryph.arknights.bilibili:files/HGGameUpdate/HGDownload" +# Endfield uses the same downloader: same folder, same 8 KB writes (11-15: 15700 write calls for 124 MB in 10 s, +# 5.5 times that written to the data disk). Its packages are up to 1.6 GB each, two at a time. +LIST="com.hypergryph.arknights:files/HGGameUpdate/HGDownload com.hypergryph.arknights.bilibili:files/HGGameUpdate/HGDownload com.hypergryph.endfield:files/HGGameUpdate/HGDownload" SIZE=16G MIN_FREE_KB=2097152 TICK=3 From b8bedbfa1570d3f9cc55b011ad8a75d4baf45081 Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:18:18 +0000 Subject: [PATCH 7/9] =?UTF-8?q?=E5=AE=9E=E4=BE=8B=E5=86=85=E5=AD=98?= =?UTF-8?q?=E5=8A=A0=208=20GB=20=E4=B8=80=E6=A1=A3=20(#181)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 默认仍是 6 GB。命令行、界面、MCP 都从 avd.MemoryChoicesMB 取档位;对照用的 instances_ref.py 同步加上。 --- README.en.md | 2 +- README.md | 2 +- changelog.d/memory-8g.feat.md | 1 + internal/avd/avd.go | 2 +- internal/avd/avd_test.go | 12 +++++++++--- internal/avd/testdata/instances_ref.py | 2 +- internal/cli/commands.go | 2 +- internal/ui/web/dev/mock.js | 4 ++-- internal/ui/web/js/forms.js | 2 +- 9 files changed, 18 insertions(+), 11 deletions(-) create mode 100644 changelog.d/memory-8g.feat.md diff --git a/README.en.md b/README.en.md index d11654c..3e743dd 100644 --- a/README.en.md +++ b/README.en.md @@ -82,7 +82,7 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] Apple Silicon macOS supports `report-config` and `collect-info`, including hardware, macOS, HVF, Metal and component versions. Game lists are queried only through an existing private ADB server and running instances with verified ownership; no service is started. The package contains an allowlist of local instance settings and at most eight emulator logs, capped at 2 MiB each and 20 MiB of text in total. Common credential fields, paths and device identifiers are filtered. macOS does not collect screenshots, system dumps or other applications' logs. Review the package before sharing it. Clipboard copying and Finder reveal can be disabled with `--no-clipboard` and `--no-explorer`. -- Write `` as `3` or `mas_3` (0-9, except 5). Memory is written as `6144`, `6144M` or `6G`, with only four tiers: 3 / 4 / 5 / 6 GB. Cores are 2 / 4 / 6, and the frame rate is any whole number from 1 to 60 (default 60). +- Write `` as `3` or `mas_3` (0-9, except 5). Memory is written as `6144`, `6144M` or `6G`, with only five tiers: 3 / 4 / 5 / 6 / 8 GB. Cores are 2 / 4 / 6, and the frame rate is any whole number from 1 to 60 (default 60). - Root folder: `--root`; if not given, the environment variable `MODAVD_ROOT`; otherwise the folder containing `modavd.exe`, or its parent. - From 0.3.0 there is no `restart`: `stop`, then `start`. An old call gets a usage error (exit code 2) that says so. diff --git a/README.md b/README.md index 815bc16..954dea9 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] Apple Silicon macOS 支持 `report-config` 和 `collect-info`:读取硬件、macOS、HVF、Metal 和组件版本;游戏列表只向归属已确认的运行实例与现有私有 ADB 查询,不启动服务。问题包只收本目录的实例配置白名单和最多 8 份模拟器日志,每份最多 2 MiB、总文本最多 20 MiB,过滤常见凭据字段、路径和设备标识。macOS 不收截图、系统转储或其他应用日志;分享前请检查问题包。默认复制配置到剪贴板、用 Finder 显示问题包,自动化可用 `--no-clipboard` / `--no-explorer`。 -- `` 写成 `3` 或 `mas_3`(0–9,5 除外);内存写成 `6144`、`6144M` 或 `6G`,只有 3 / 4 / 5 / 6 GB 四档,核数 2 / 4 / 6,帧率 1–60 的整数(默认 60)。 +- `` 写成 `3` 或 `mas_3`(0–9,5 除外);内存写成 `6144`、`6144M` 或 `6G`,只有 3 / 4 / 5 / 6 / 8 GB 五档,核数 2 / 4 / 6,帧率 1–60 的整数(默认 60)。 - 根目录:`--root`,没给就用环境变量 `MODAVD_ROOT`,再没有就用 `modavd.exe` 所在目录或它的上一级。 - 0.3.0 起没有 `restart`:先 `stop` 再 `start`。旧的调用报用法错误(退出码 2),提示改用这两步。 diff --git a/changelog.d/memory-8g.feat.md b/changelog.d/memory-8g.feat.md new file mode 100644 index 0000000..8a20baa --- /dev/null +++ b/changelog.d/memory-8g.feat.md @@ -0,0 +1 @@ +实例内存可以选 8 GB diff --git a/internal/avd/avd.go b/internal/avd/avd.go index 12710ee..6efccb9 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -25,7 +25,7 @@ import ( // Instance options (user decisions: memory and cores only in these steps, no silent rounding). var ( - MemoryChoicesMB = []int{3072, 4096, 5120, 6144} + MemoryChoicesMB = []int{3072, 4096, 5120, 6144, 8192} CPUChoices = []int{2, 4, 6} ResolutionChoices = []int{1080, 720} ) diff --git a/internal/avd/avd_test.go b/internal/avd/avd_test.go index e3727c7..2d97669 100644 --- a/internal/avd/avd_test.go +++ b/internal/avd/avd_test.go @@ -441,7 +441,7 @@ func TestPropertiesMatchPython(t *testing.T) { titles := []string{"", " ", "星铁", "a=b", "mas_x"} metas := []string{`{"memoryMb": 4096}`, `{"memoryMb": 4096.0}`, `{"memoryMb": "4096"}`, `{"memoryMb": true}`, `{"memoryMb": 3000}`, `{"memoryMb": null}`, `5`, `{"memoryMb": 5120}`, `{}`, `{"memoryMb": 3072, "x": 1}`, - `{"memoryMb": 6144e0}`, `{"memoryMb": -0}`} + `{"memoryMb": 6144e0}`, `{"memoryMb": -0}`, `{"memoryMb": 8192}`, `{"memoryMb": 7168}`} setup := map[string]string{} var instMeta []string @@ -760,8 +760,8 @@ func TestValidate(t *testing.T) { memory, cpu, data *int msg string }{ - {ip(1000), nil, nil, "ModAVD 的内存只能选 3 GB / 4 GB / 5 GB / 6 GB"}, - {ip(0), ip(3), ip(1), "ModAVD 的内存只能选 3 GB / 4 GB / 5 GB / 6 GB"}, + {ip(1000), nil, nil, "ModAVD 的内存只能选 3 GB / 4 GB / 5 GB / 6 GB / 8 GB"}, + {ip(0), ip(3), ip(1), "ModAVD 的内存只能选 3 GB / 4 GB / 5 GB / 6 GB / 8 GB"}, {nil, ip(3), ip(1), "ModAVD 的 CPU 核数只能选 2 / 4 / 6"}, {nil, nil, ip(15), "数据盘上限只能在 16–512 GB 之间"}, {nil, nil, ip(513), "数据盘上限只能在 16–512 GB 之间"}, @@ -772,6 +772,12 @@ func TestValidate(t *testing.T) { t.Errorf("got %q want %q", err.Error(), tc.msg) } } + if m, _, _, err := ValidateOptions(ip(8192), nil, nil); err != nil || m != 8192 { + t.Errorf("8 GB: %d %v", m, err) + } + if _, _, _, err := ValidateOptions(ip(7168), nil, nil); errs.CodeOf(err) != errs.InvalidArgument { + t.Errorf("7 GB: %v", err) + } if _, _, d, err := ValidateOptions(nil, nil, ip(16)); err != nil || d != 16 { t.Error("16 GB") } diff --git a/internal/avd/testdata/instances_ref.py b/internal/avd/testdata/instances_ref.py index bba3885..c70cbbd 100644 --- a/internal/avd/testdata/instances_ref.py +++ b/internal/avd/testdata/instances_ref.py @@ -31,7 +31,7 @@ AVD_DIR = "avd" METADATA_FILE = "mas-avd.json" SYSTEM_IMAGE_SYSDIR = "system-images\\android-34\\google_apis\\x86_64\\" -MEMORY_CHOICES_MB = (3072, 4096, 5120, 6144) +MEMORY_CHOICES_MB = (3072, 4096, 5120, 6144, 8192) # 8192: added in ModAVDManager, not in AUTO-MAS CPU_CHOICES = (2, 4, 6) DEFAULT_MEMORY_MB = 6144 DEFAULT_CPU = 6 diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 9f65ba8..66ceb8d 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -86,7 +86,7 @@ func dataGBOpt(inv *invocation) (gb *int, auto bool, err error) { var ( optIndex = flagSpec{"index", kindString, "N", "实例编号(不给就取最小的空闲编号,端口也要空着)"} optTitle = flagSpec{"title", kindString, "T", "显示名称"} - optMemory = flagSpec{"memory", kindString, "M", "内存:3072 / 4096 / 5120 / 6144 MB,也可写 6G"} + optMemory = flagSpec{"memory", kindString, "M", "内存:3072 / 4096 / 5120 / 6144 / 8192 MB,也可写 6G"} optCPU = flagSpec{"cpu", kindInt, "N", "核数:2 / 4 / 6"} optDataGB = flagSpec{"data-gb", kindString, "auto|N", "数据盘:auto 自动扩盘(默认),或指定大小 16–512 GB"} optResolution = flagSpec{"resolution", kindInt, "", "分辨率:1080 / 720,DPI 随档位切换;新建默认 1080"} diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index ce47c80..5b5edf3 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -9,7 +9,7 @@ const ROOT = 'X:\\ModAVD'; const INDEXES = [0, 1, 2, 3, 4, 6, 7, 8, 9]; -const MEM = [3072, 4096, 5120, 6144]; +const MEM = [3072, 4096, 5120, 6144, 8192]; const db = { insts: new Map(), jobs: [], streams: new Set(), seq: 40, check: 'ok', offline: false, drop: false, ready: true, diagMode: '', componentsReady: false, componentSource: { source: 'auto', mirror: '', mirror_urls: [], configured: false }, // the root's Google Play Store files (sdk\playstore): source is download | import once they are there @@ -853,7 +853,7 @@ function probeAt(server) { const errResp = (code, message, advice) => fail(STATUS_OF[code] || 500, code, message, advice); function validate(b, create) { - if (b.memory_mb != null && !MEM.includes(b.memory_mb)) return ['invalid_argument', `内存只能选 3、4、5、6 GB(收到 ${b.memory_mb} MB)`, '']; + if (b.memory_mb != null && !MEM.includes(b.memory_mb)) return ['invalid_argument', `内存只能选 3、4、5、6、8 GB(收到 ${b.memory_mb} MB)`, '']; if (b.cpu != null && ![2, 4, 6].includes(b.cpu)) return ['invalid_argument', `CPU 核数只能是 2、4 或 6(收到 ${b.cpu})`, '']; if (b.resolution != null && ![1080, 720].includes(b.resolution)) return ['invalid_argument', '分辨率只能是 1080 或 720', '']; if (b.fps != null && !(Number.isInteger(b.fps) && b.fps >= 1 && b.fps <= 60)) return ['invalid_argument', '帧率只能在 1–60 之间', '']; diff --git a/internal/ui/web/js/forms.js b/internal/ui/web/js/forms.js index 9cee0ca..2bc04ff 100644 --- a/internal/ui/web/js/forms.js +++ b/internal/ui/web/js/forms.js @@ -8,7 +8,7 @@ import { quoted, label, ownTitle, defaultName, uptime, fmtBytes } from './format import * as A from './actions.js'; import { regionalFields, guestRegionalText } from './regional.js'; -const MEM = [[3072, '3 GB'], [4096, '4 GB'], [5120, '5 GB'], [6144, '6 GB']]; +const MEM = [[3072, '3 GB'], [4096, '4 GB'], [5120, '5 GB'], [6144, '6 GB'], [8192, '8 GB']]; const CPU = [[2, '2 核'], [4, '4 核'], [6, '6 核']]; const FPS_MIN = 1; const FPS_MAX = 60; From c99e56749c548bc565a01547a3844e8221f04e5d Mon Sep 17 00:00:00 2001 From: qiyinxi <52456734+qiyinxi@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:32:29 +0000 Subject: [PATCH 8/9] =?UTF-8?q?=E6=98=9F=E9=93=81=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E9=A2=84=E8=AE=BE=E4=B8=BA=20Vulkan=EF=BC=9A?= =?UTF-8?q?=E6=96=B0=E8=A3=85=E5=90=8E=E9=A6=96=E6=AC=A1=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E9=97=AA=E9=80=80=20(#182)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 星铁显示模式预设为 Vulkan:首次启动不再走 GLES 闪退 新装的崩坏:星穹铁道第一次启动自己选 OpenGL ES(files/vulkancaps.bin 写成 03),gfxstream 的 GLES 缺它要的功能,十几秒后闪退;换成 Vulkan 正常。实测首次启动前在 Android/data/<包名>/files 放好 customvulkancaps.bin 和 vulkancaps.bin(都是 0x01),游戏就走 Vulkan、两个文件保持 01;只放 vulkancaps.bin 会被游戏改回 03,只放 customvulkancaps.bin 仍走 GLES。 新客体脚本 modavd-vkmode.sh,照下载盘守护的做法:开机先过一遍,再后台每 3 秒看一遍,开机后才装的游戏在首次启动前也能处理到。名单 com.miHoYo.hkrpg、com.miHoYo.hkrpg.bilibili(B 服没实测)。对每个已安装、不在运行、files/customvulkancaps.bin 不存在的包:缺的目录按系统的建法补上(应用 uid、ext_data_rw、2770,标签取 Android/data 的),两个文件先写成临时名、设好属主和 660 再改名到位,customvulkancaps.bin 最后放,中途失败下一轮补;建出来属主设不上的目录当场删掉。customvulkancaps.bin 已在(游戏里选过,或者我们写过)就不动。 另起脚本而不是加进下载盘守护:下载盘有 MODAVD_DL_DISK=off 的关法、带锁和挂载逻辑,两件事分开互不影响。开机后设置加一步 12b,日志写「游戏显示模式预设」一行;和下载盘一样只在 Windows 上做、默认开。 Refs ModAVD/ModAVD#222 * 星铁显示模式预设:写完落盘,空文件不算选过,日志带文件当前值 两个文件都改名到位后跑一次 sync(只在真的写了的那一轮);判断「已选过」从 customvulkancaps.bin 存在改成存在且非空,硬杀留下的 0 字节残骸会被重写成 01。每次真的写了文件都记一行 logcat,备注已是 set to Vulkan 时(文件被改坏后补写)也记。 status 对已安装的包带上两个文件的当前值([custom=01 caps=01],不存在写 -,空文件写 empty),管理器开机日志那一行跟着带上。 单测:空 custom(caps 在 / 不在)重写;vulkancaps.bin 改名失败时不写 customvulkancaps.bin、下一轮补齐(钉住写入顺序);补写也有日志;sync 只在写成的那一轮跑。README 中英对齐:闪退时间统一为十几秒 / about fifteen seconds,游戏设置项不用自起的中文叫法。 Refs ModAVD/ModAVD#222 --- README.en.md | 3 + README.md | 3 + changelog.d/222-starrail-vulkan.fix.md | 1 + internal/emu/afterboot.go | 2 + internal/emu/vkmode.go | 102 +++++ internal/emu/vkmode_test.go | 59 +++ internal/guest/guest.go | 3 + internal/guest/guest_test.go | 2 +- internal/guest/scripts/modavd-vkmode.sh | 163 ++++++++ internal/guest/vkmode_sh_test.go | 497 ++++++++++++++++++++++++ 10 files changed, 834 insertions(+), 1 deletion(-) create mode 100644 changelog.d/222-starrail-vulkan.fix.md create mode 100644 internal/emu/vkmode.go create mode 100644 internal/emu/vkmode_test.go create mode 100644 internal/guest/scripts/modavd-vkmode.sh create mode 100644 internal/guest/vkmode_sh_test.go diff --git a/README.en.md b/README.en.md index 3e743dd..c57c6bb 100644 --- a/README.en.md +++ b/README.en.md @@ -204,6 +204,9 @@ On Apple Silicon macOS, downloads and imports use Android 15 Google Play `arm64- - The disk is `/data/local/tmp/modavd-dldisk//dl.img` in the guest, a sparse file of at most 16 GB; space of deleted packages goes back to the data disk. Downloading is faster than unpacking, so finished packages queue up on the disk: during a full resource download the data disk's peak use is about 6 GB higher than before. No disk is made when the data disk has less than 2 GB free. - The list holds Arknights, official `com.hypergryph.arknights` and bilibili `com.hypergryph.arknights.bilibili` (not tested on the latter; the folder is the same), and Arknights: Endfield `com.hypergryph.endfield` (same downloader, same folder and write pattern). - Boot with the environment variable `MODAVD_DL_DISK=off` to move unfinished downloads back into the plain folder, delete the disk and start no watcher. +- Honkai: Star Rail (official `com.miHoYo.hkrpg` and bilibili `com.miHoYo.hkrpg.bilibili`, not tested on the latter) gets its display mode set to Vulkan in advance (guest script `modavd-vkmode.sh`, Windows only). At its first start the game picks OpenGL ES on its own and closes on ModAVD about fifteen seconds later; in Vulkan mode (Normal Mode under Settings > Graphics > Display Settings in the game) it runs. + - A watcher looks every 3 seconds: once the game is installed, before its first start, it writes `vulkancaps.bin` and `customvulkancaps.bin` in the game's `Android/data//files`. A game already stuck in OpenGL ES after such a crash is switched to Vulkan as well, at the next boot or once it has exited. + - A display mode chosen in the game's settings (`customvulkancaps.bin` is there and not empty) is left alone; so is a running game; no folder is made for a game that is not installed. Two display presets are available: 1080p is 1920×1080 / DPI 280; 720p is 1280×720 / DPI 240. New instances default to 1080p. 720p uses fewer resources. The manager forms, CLI `--resolution 1080|720` and MCP `resolution` share these presets. Existing landscape or portrait 1920×1080 instances stay at 1080p; other configurations, including missing dimensions, stay at 720p. Changing the preset updates width, height and DPI together, preserves orientation, and takes effect at the next cold boot. DPI is not a separate option. No runtime `wm size` or `wm density` is used. Update the resolution in your automation tool as well. AUTO-MAS currently prefers the packaged CLI, which preserves the selected preset. Old roots without a usable CLI fall back to the Python launch path, which still forces 720p. Update the packaged CLI before using 1080p there. AUTO-MAS creation and display settings still need matching two-preset support; use the ModAVD manager to set the preset meanwhile. diff --git a/README.md b/README.md index 954dea9..2b328fc 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,9 @@ Apple Silicon macOS 的下载与导入使用 Android 15 Google Play `arm64-v8a` - 盘是客体里的 `/data/local/tmp/modavd-dldisk/<包名>/dl.img`,一个最大 16 GB 的稀疏文件,删掉的包占的空间会还给数据盘。下载比解压快,下好的包会先堆在盘里:下整包资源时,数据盘的占用高峰比以前多约 6 GB。数据盘剩余不到 2 GB 时不建盘。 - 名单里是明日方舟官服 `com.hypergryph.arknights`、B 服 `com.hypergryph.arknights.bilibili`(B 服没有实测,目录相同),以及明日方舟:终末地 `com.hypergryph.endfield`(同一套下载器,目录和写法相同)。 - 设环境变量 `MODAVD_DL_DISK=off` 再开机:把盘里还没下完的搬回普通目录,删掉盘,不再起守护。 +- 崩坏:星穹铁道(官服 `com.miHoYo.hkrpg`、B 服 `com.miHoYo.hkrpg.bilibili`,B 服没有实测)的显示模式预先设成 Vulkan(客体脚本 `modavd-vkmode.sh`,只在 Windows 上)。游戏第一次启动时自己选 OpenGL ES,在 ModAVD 上十几秒后闪退;在游戏设置里的显示设置(Display Settings)选 Vulkan 模式就正常。 + - 守护每 3 秒看一次:游戏装上以后、第一次启动之前,在它的 `Android/data/<包名>/files` 里写好 `vulkancaps.bin`、`customvulkancaps.bin`。已经因为闪退停在 OpenGL ES 的,下次开机或游戏退出后也改成 Vulkan。 + - 在游戏设置里选过显示模式的(`customvulkancaps.bin` 已经在、不是空文件)不动;游戏开着时不动;没装的游戏不建任何目录。 分辨率只有两档:1080p 为 1920×1080 / DPI 280,720p 为 1280×720 / DPI 240。新建默认 1080p,720p 更省资源。管理器的新建和实例设置、CLI `--resolution 1080|720`、MCP `resolution` 使用同一套档位。已有实例按宽高识别:横屏或竖屏的 1920×1080 保持 1080p,其余配置及缺字段的旧配置保持 720p。换档联动宽、高、DPI,保留方向,下次冷启动生效;DPI 不单独设置,不使用运行时 `wm size` 或 `wm density`。自动化工具里的分辨率也要跟着改。 AUTO-MAS 当前优先调用包内 CLI,这条启动路径保持所选档位。没有可用 CLI 的旧根目录会回退到固定 720p 的 Python 启动路径,使用 1080p 前须更新包内 CLI。AUTO-MAS 的旧新建和显示配置表单仍需配套支持两档;可先在 ModAVD 管理器里设置。 diff --git a/changelog.d/222-starrail-vulkan.fix.md b/changelog.d/222-starrail-vulkan.fix.md new file mode 100644 index 0000000..83909ba --- /dev/null +++ b/changelog.d/222-starrail-vulkan.fix.md @@ -0,0 +1 @@ +新装的崩坏:星穹铁道默认用 Vulkan 显示模式,首次启动不再闪退 (ModAVD/ModAVD#222) diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go index e54e939..a0d2ec8 100644 --- a/internal/emu/afterboot.go +++ b/internal/emu/afterboot.go @@ -238,6 +238,8 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe // 12) download disks (dldisk.go). After the guest library fixes (0a): the framework restart there remounts the // shared storage, and a disk mounted on it before would be gone with it func() { m.setupDownloadDisk(ctx, i) }, + // 12b) listed games that have not chosen a display mode start in Vulkan (vkmode.go, ModAVD#222) + func() { m.setupVulkanMode(ctx, i) }, // 13) the guest's clock source into the log, its kernel log's clock lines saved when an x86_64 guest is not on // tsc (clocksource.go, ModAVD#110). Last: the later the one read, the more of a fallback during boot it sees func() { m.recordClocksource(ctx, inst) }, diff --git a/internal/emu/vkmode.go b/internal/emu/vkmode.go new file mode 100644 index 0000000..e4f0090 --- /dev/null +++ b/internal/emu/vkmode.go @@ -0,0 +1,102 @@ +package emu + +import ( + "context" + "fmt" + "strings" + "time" + + "modavd/internal/guest" + "modavd/internal/root" +) + +// The Vulkan display mode (guest.VulkanMode, ModAVD/ModAVD#222). Honkai: Star Rail picks OpenGL ES at its first start, +// and on gfxstream's GLES it closes about 15 s later; in Vulkan mode it runs. For the listed games that have not +// chosen a mode (in the game's settings, or by an earlier pass), a guest watcher writes the Vulkan mode before the game +// starts: installed before the boot or after it. A mode chosen in the game is never overwritten. The script's header +// has the files and what was measured. +// +// On by default, without a switch. Windows only so far: that is where it was measured. + +// vulkanModeTimeout covers the script's wait for the shared storage folder (20 s) and one pass. +const vulkanModeTimeout = 60 * time.Second + +// setupVulkanMode starts the watcher, which makes one pass before it returns: a game already installed is set before +// the boot is reported as done and a script starts it. +func (m *Manager) setupVulkanMode(ctx context.Context, i int) { + if !root.CurrentPlatform().Windows() { + return + } + remote, ok := m.pushGuestScript(ctx, i, guest.VulkanMode) + if !ok { + return + } + started := m.shell(ctx, i, "su 0 sh "+remote+" daemon", vulkanModeTimeout).Out + status := m.shell(ctx, i, "su 0 sh "+remote+" status", 0).Out + if warn, msg := vulkanModeReport(i, started, status); warn { + m.Log.Warnf("%s", msg) + } else { + m.Log.Infof("%s", msg) + } +} + +// vulkanModeReport judges `modavd-vkmode.sh daemon` + `status`: running when a watcher pid is listed. The message +// names the listed games that are installed and what the script last said about each; a game it could not set makes +// it a warning. +func vulkanModeReport(i int, started, status string) (warn bool, msg string) { + lines := parseStatusLines(status) + if lines["watchers"] == "" { + return true, fmt.Sprintf("实例 %d 游戏显示模式预设没起来: %s", i, tail(strings.TrimSpace(started)+" / "+status, 300)) + } + var games []string + for _, line := range outputLines(status) { + pkg, state, ok := strings.Cut(line, ":") + state = strings.TrimSpace(state) + if !ok || pkg == "watchers" || state == "" || state == "not installed" { + continue + } + state, files := vulkanModeFiles(state) + if strings.HasPrefix(state, "cannot ") { + warn = true + } + text := vulkanModeState(state) + if files != "" { + text += "," + files + } + games = append(games, pkg+"("+text+")") + } + if len(games) == 0 { + return false, fmt.Sprintf("实例 %d 游戏显示模式预设: 守护已起(pid %s),名单里的游戏都没装", i, lines["watchers"]) + } + return warn, fmt.Sprintf("实例 %d 游戏显示模式预设: 守护已起(pid %s);%s", i, lines["watchers"], strings.Join(games, ",")) +} + +// vulkanModeFiles splits what status prints after the note, " [custom=01 caps=01]" (the two files' bytes in hex, +// "-" for a missing one), from the note; files is "" when there is none (a script of an older build). +func vulkanModeFiles(state string) (note, files string) { + if strings.HasSuffix(state, "]") { + if k := strings.LastIndex(state, " ["); k >= 0 { + return strings.TrimSpace(state[:k]), strings.TrimSpace(state[k+2 : len(state)-1]) + } + } + return state, "" +} + +// vulkanModeState puts the script's notes into the log's language; one it does not know stays as it is. +func vulkanModeState(state string) string { + switch { + case state == "set to Vulkan": + return "已预设为 Vulkan" + case state == "display mode chosen already": + return "已选过显示模式,不动" + case state == "running, set once it exits": + return "游戏开着,等它退出后再写" + case state == "nothing done yet": + return "还没处理" + case state == "cannot write the display mode files": + return "显示模式文件写不进去" + case strings.HasPrefix(state, "cannot make "): + return "建不了 " + strings.TrimPrefix(state, "cannot make ") + } + return state +} diff --git a/internal/emu/vkmode_test.go b/internal/emu/vkmode_test.go new file mode 100644 index 0000000..fb87921 --- /dev/null +++ b/internal/emu/vkmode_test.go @@ -0,0 +1,59 @@ +package emu + +import "testing" + +func TestVulkanModeReport(t *testing.T) { + status := "watchers: 5481 \r\ncom.miHoYo.hkrpg: set to Vulkan\r\ncom.miHoYo.hkrpg.bilibili: not installed\r\n" + warn, msg := vulkanModeReport(3, "modavd-vkmode: com.miHoYo.hkrpg: set to Vulkan\n", status) + if warn || msg != "实例 3 游戏显示模式预设: 守护已起(pid 5481);com.miHoYo.hkrpg(已预设为 Vulkan)" { + t.Errorf("set: %v %q", warn, msg) + } + warn, msg = vulkanModeReport(3, "", "watchers: 5481\ncom.miHoYo.hkrpg: not installed\ncom.miHoYo.hkrpg.bilibili: not installed\n") + if warn || msg != "实例 3 游戏显示模式预设: 守护已起(pid 5481),名单里的游戏都没装" { + t.Errorf("none installed: %v %q", warn, msg) + } + for state, want := range map[string]struct { + text string + warn bool + }{ + "display mode chosen already": {"已选过显示模式,不动", false}, + "running, set once it exits": {"游戏开着,等它退出后再写", false}, + "nothing done yet": {"还没处理", false}, + "cannot write the display mode files": {"显示模式文件写不进去", true}, + "cannot make /data/media/0/Android/data/com.miHoYo.hkrpg/files": {"建不了 /data/media/0/Android/data/com.miHoYo.hkrpg/files", true}, + "something this build does not know": {"something this build does not know", false}, + } { + warn, msg = vulkanModeReport(1, "", "watchers: 7\ncom.miHoYo.hkrpg: "+state+"\n") + if warn != want.warn || msg != "实例 1 游戏显示模式预设: 守护已起(pid 7);com.miHoYo.hkrpg("+want.text+")" { + t.Errorf("%s: %v %q", state, warn, msg) + } + } + // both listed games installed + warn, msg = vulkanModeReport(2, "", "watchers: 9\ncom.miHoYo.hkrpg: display mode chosen already\ncom.miHoYo.hkrpg.bilibili: set to Vulkan\n") + if warn || msg != "实例 2 游戏显示模式预设: 守护已起(pid 9);com.miHoYo.hkrpg(已选过显示模式,不动),com.miHoYo.hkrpg.bilibili(已预设为 Vulkan)" { + t.Errorf("both: %v %q", warn, msg) + } + // no watcher: a warning with what the script said + warn, msg = vulkanModeReport(2, "modavd-vkmode: oops\n", "watchers: \ncom.miHoYo.hkrpg: not installed\n") + if !warn || msg != "实例 2 游戏显示模式预设没起来: modavd-vkmode: oops / watchers: \ncom.miHoYo.hkrpg: not installed" { + t.Errorf("no watcher: %v %q", warn, msg) + } + if warn, _ = vulkanModeReport(2, "", ""); !warn { + t.Error("empty status: no warning") + } + // what the two files hold, as status prints it + warn, msg = vulkanModeReport(4, "", "watchers: 11 \r\ncom.miHoYo.hkrpg: set to Vulkan [custom=01 caps=01]\r\n"+ + "com.miHoYo.hkrpg.bilibili: display mode chosen already [custom=00 caps=-]\r\n") + if warn || msg != "实例 4 游戏显示模式预设: 守护已起(pid 11);com.miHoYo.hkrpg(已预设为 Vulkan,custom=01 caps=01),"+ + "com.miHoYo.hkrpg.bilibili(已选过显示模式,不动,custom=00 caps=-)" { + t.Errorf("files: %v %q", warn, msg) + } + warn, msg = vulkanModeReport(4, "", "watchers: 11\ncom.miHoYo.hkrpg: cannot make /data/media/0/Android/data/com.miHoYo.hkrpg/files [custom=- caps=-]\n") + if !warn || msg != "实例 4 游戏显示模式预设: 守护已起(pid 11);com.miHoYo.hkrpg(建不了 /data/media/0/Android/data/com.miHoYo.hkrpg/files,custom=- caps=-)" { + t.Errorf("cannot, with files: %v %q", warn, msg) + } + warn, msg = vulkanModeReport(4, "", "watchers: 11\ncom.miHoYo.hkrpg: nothing done yet [custom=empty caps=03]\n") + if warn || msg != "实例 4 游戏显示模式预设: 守护已起(pid 11);com.miHoYo.hkrpg(还没处理,custom=empty caps=03)" { + t.Errorf("empty file: %v %q", warn, msg) + } +} diff --git a/internal/guest/guest.go b/internal/guest/guest.go index 8f0b38f..66d5943 100644 --- a/internal/guest/guest.go +++ b/internal/guest/guest.go @@ -95,6 +95,9 @@ const ( // DownloadDisk keeps the download folder of games that fsync after every few KB on a disk of its own, where // fsync does not wait and the folder is committed as a whole every 3 s (modavd only, ModAVD/ModAVD#35). DownloadDisk = "modavd-dldisk.sh" + // VulkanMode writes the Vulkan display mode for listed games that have not chosen one, before their first start + // (modavd only, ModAVD/ModAVD#222). + VulkanMode = "modavd-vkmode.sh" ) // RemoteDir is where the scripts go in the guest. diff --git a/internal/guest/guest_test.go b/internal/guest/guest_test.go index a9933a8..d61b78a 100644 --- a/internal/guest/guest_test.go +++ b/internal/guest/guest_test.go @@ -15,7 +15,7 @@ import ( ) func TestScriptsHaveNoCR(t *testing.T) { - for _, name := range []string{CPUInfoBind, IdlePoll, WifiFastpath, LibFix, PlayStore, DownloadDisk} { + for _, name := range []string{CPUInfoBind, IdlePoll, WifiFastpath, LibFix, PlayStore, DownloadDisk, VulkanMode} { b, err := Script(name) if err != nil { t.Fatalf("%s: %v", name, err) diff --git a/internal/guest/scripts/modavd-vkmode.sh b/internal/guest/scripts/modavd-vkmode.sh new file mode 100644 index 0000000..8989358 --- /dev/null +++ b/internal/guest/scripts/modavd-vkmode.sh @@ -0,0 +1,163 @@ +#!/system/bin/sh +# modavd-vkmode.sh - listed games start in their Vulkan display mode. Run as root +# (adb shell su 0 sh ...). +# +# daemon one pass now (waits up to 20 s for the shared storage folder), then +# start "watch" in the background unless it is already running +# watch loop: one pass every TICK seconds +# once one pass +# status print current state +# +# Why (ModAVD/ModAVD#222): Honkai: Star Rail picks its display mode at its first +# start. It picks OpenGL ES (files/vulkancaps.bin = 03), and gfxstream's GLES +# lacks what the game needs there: it closes about 15 s after the start. In +# Vulkan mode ("Normal Mode" under Settings > Graphics > Display Settings) it +# runs. 11-16: with files/customvulkancaps.bin and files/vulkancaps.bin both +# 0x01 before the first start, the game starts in Vulkan and keeps both at 01 +# (dozens of starts). vulkancaps.bin alone: Vulkan once, then the game rewrites +# it to 03; customvulkancaps.bin alone: GLES. The game writes both when the user +# picks a mode in its settings, so customvulkancaps.bin holding something means +# a mode was chosen (by the user, or by an earlier pass). Both write one byte; +# an empty one is what a hard kill leaves of a file moved into a new name 5-7 s +# before (measured on ModAVD), not a choice: it is written again. +# +# What a pass does for each package of LIST, never while a process of the +# package runs: +# - not installed: nothing (no folder is made); +# - files/customvulkancaps.bin there and not empty: nothing; +# - otherwise: the missing folders are made the way the system makes them for +# the app (owner, ext_data_rw, 2770); both files are written as 01 (owner, +# ext_data_rw, 660) under a temporary name and moved into place, +# customvulkancaps.bin last, then sync. A pass that fails half way leaves +# that one missing, so the next pass does it again. Every write is logged. +# The watcher repeats this, so a game installed after boot is set before its +# first start. status also prints what the two files hold (hex; - when missing). + +R=${MODAVD_VKMODE_ROOT:-} +TAG=modavd-vkmode +BASE=$R/data/local/tmp/$TAG +MEDIA=$R/data/media/0/Android/data +LIST="com.miHoYo.hkrpg com.miHoYo.hkrpg.bilibili" +TICK=3 + +say() { echo "$TAG: $*"; /system/bin/log -t $TAG "$*" 2>/dev/null; } + +# note : say it when it changes; status prints the latest +note() { + f=$BASE/.$1.note + [ "$(cat "$f" 2>/dev/null)" = "$2" ] && return 0 + mkdir -p "$BASE" && echo "$2" > "$f" + say "$1: $2" +} + +uid_of() { stat -c %u "$R/data/data/$1" 2>/dev/null; } +running() { [ -n "$(pgrep -u "$1" 2>/dev/null | head -1)" ]; } +label_of() { ls -Zd "$1" 2>/dev/null | cut -d' ' -f1; } +# bytes : its first bytes in hex ("01"), "empty", or "-" when missing +bytes() { + [ -e "$1" ] || { echo -; return; } + b=$(od -An -tx1 -N4 "$1" 2>/dev/null | tr -d ' \n') + echo "${b:-empty}" +} + +# mkpath : /files under MEDIA; a folder that cannot be given its owner is not left behind +mkpath() { + c=$(label_of "$MEDIA") + [ -n "$c" ] || return 1 + p=$MEDIA + for seg in $1 files; do + p=$p/$seg + [ -d "$p" ] && continue + mkdir "$p" || return 1 + chown "$2:1078" "$p" && chmod 2770 "$p" && chcon "$c" "$p" || { rmdir "$p" 2>/dev/null; return 1; } + done +} + +# put : the file holds the byte 01 and belongs to the app +put() { + t=$2/.$3.$TAG + rm -f "$t" + printf '\001' > "$t" && chown "$1:1078" "$t" && chmod 660 "$t" && mv -f "$t" "$2/$3" || { rm -f "$t"; return 1; } +} + +setup() { + pkg=$1 + uid=$(uid_of "$pkg") + if [ -z "$uid" ]; then + rm -f "$BASE/.$pkg.note" + return 0 + fi + dir=$MEDIA/$pkg/files + if [ -s "$dir/customvulkancaps.bin" ]; then + [ "$(cat "$BASE/.$pkg.note" 2>/dev/null)" = "set to Vulkan" ] || note "$pkg" "display mode chosen already" + return 0 + fi + if running "$uid"; then + note "$pkg" "running, set once it exits" + return 0 + fi + [ -d "$MEDIA" ] || return 0 + mkpath "$pkg" "$uid" || { note "$pkg" "cannot make ${dir#$R}"; return 0; } + # vulkancaps.bin first: customvulkancaps.bin alone makes the game pick GLES, and it stops the next passes + if put "$uid" "$dir" vulkancaps.bin && put "$uid" "$dir" customvulkancaps.bin; then + sync + # logged on every write, also when the note says so already (a game set before and broken since) + rm -f "$BASE/.$pkg.note" + note "$pkg" "set to Vulkan" + else + note "$pkg" "cannot write the display mode files" + fi +} + +pass() { + mkdir -p "$BASE" || return 1 + # one pass at a time (daemon and watch can meet); a lock older than a minute is a leftover + if ! mkdir "$BASE/.lock" 2>/dev/null; then + [ -n "$(find "$BASE/.lock" -maxdepth 0 -mmin +1 2>/dev/null)" ] && rmdir "$BASE/.lock" 2>/dev/null + return 0 + fi + for pkg in $LIST; do setup "$pkg"; done + rmdir "$BASE/.lock" +} + +watchers() { pgrep -f "$TAG.sh watch"; } + +case "$1" in +daemon) + if [ -z "$(watchers)" ]; then + # first call of this boot: nothing of the last boot is running any more + rmdir "$BASE/.lock" 2>/dev/null + rm -f "$BASE"/.*.note 2>/dev/null + fi + i=0 + while [ ! -d "$MEDIA" ] && [ $i -lt 20 ]; do sleep 1; i=$((i + 1)); done + pass + [ -n "$(watchers)" ] || { nohup setsid sh "$0" watch > /dev/null 2>&1 & } + i=0 + while [ $i -lt 10 ] && [ -z "$(watchers)" ]; do sleep 0.1; i=$((i + 1)); done + ;; +watch) + for p in $(watchers); do + [ "$p" -lt $$ ] && exit 0 + done + while true; do + sleep $TICK + pass + done + ;; +once) + pass + ;; +status) + echo "watchers: $(watchers | tr '\n' ' ')" + for pkg in $LIST; do + if [ -z "$(uid_of "$pkg")" ]; then echo "$pkg: not installed"; continue; fi + d=$MEDIA/$pkg/files + echo "$pkg: $(cat "$BASE/.$pkg.note" 2>/dev/null || echo "nothing done yet") [custom=$(bytes "$d/customvulkancaps.bin") caps=$(bytes "$d/vulkancaps.bin")]" + done + ;; +*) + echo "usage: $0 daemon|watch|once|status" + exit 2 + ;; +esac diff --git a/internal/guest/vkmode_sh_test.go b/internal/guest/vkmode_sh_test.go new file mode 100644 index 0000000..d112c12 --- /dev/null +++ b/internal/guest/vkmode_sh_test.go @@ -0,0 +1,497 @@ +package guest + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "modavd/internal/testutil" +) + +// vkGuest is a fake guest for modavd-vkmode.sh under a POSIX sh (Git's on Windows): MODAVD_VKMODE_ROOT is a temporary +// directory standing for /. Stubs on PATH: +// - stat -c %u, chown, chmod, chcon, ls -Zd keep owner, mode and label in .owner / .mode / .label next to the +// path; mv moves those with the file and logs the call; +// - pgrep -u prints a pid when /running lists the uid; pgrep -f finds nothing (no watcher); +// - chown and mv fail (doing nothing) on a path containing what /.fail holds; +// - sync logs the call. +type vkGuest struct { + t *testing.T + sh, root string + env []string +} + +const ( + vkPkg = "com.miHoYo.hkrpg" + vkUID = "10197" + vkBili = "com.miHoYo.hkrpg.bilibili" + vkBUID = "10198" + vkMedia = "/data/media/0/Android/data" + vkLabel = "u:object_r:media_rw_data_file:s0" +) + +func vkFiles(pkg string) string { return vkMedia + "/" + pkg + "/files" } + +func newVKGuest(t *testing.T) *vkGuest { + t.Helper() + sh, err := exec.LookPath("sh") + if err != nil { + t.Skip("no sh") + } + for _, tool := range []string{"cut", "head", "cat", "rm", "mkdir", "rmdir", "mv", "find", "tr", "od"} { + if _, err := exec.LookPath(tool); err != nil { + t.Skip("no " + tool) + } + } + base := testutil.TempDir(t) + if strings.ContainsAny(base, " \t") { + t.Skip("the temporary directory has a space in its path (the guest's never do)") + } + g := &vkGuest{t: t, sh: sh, root: filepath.ToSlash(filepath.Join(base, "root"))} + bin := filepath.Join(base, "bin") + for _, d := range []string{bin, g.path("/data/local/tmp"), g.path("/data/data"), g.path(vkMedia)} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + g.write(vkMedia+".label", vkLabel) + + stub := func(name, body string) { + if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\nR=$MODAVD_VKMODE_ROOT\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + fails := func(what, path string) string { + return `f=$(cat "$R/` + what + `.fail" 2>/dev/null) +if [ -n "$f" ]; then case "` + path + `" in *"$f"*) echo "` + what + `: failed" >&2; exit 1 ;; esac; fi +` + } + stub("stat", `[ "$1" = -c ] && [ "$2" = %u ] && [ -e "$3" ] || exit 1 +cut -d: -f1 "$3.owner" 2>/dev/null || echo 0`) + stub("chown", fails("chown", "$2")+`printf '%s\n' "$1" > "$2.owner"`) + stub("chmod", `printf '%s\n' "$1" > "$2.mode"`) + stub("chcon", `printf '%s\n' "$1" > "$2.label"`) + stub("ls", `[ "$1" = -Zd ] || { echo "ls: unexpected $*" >&2; exit 1; } +[ -e "$2" ] || exit 1 +echo "$(cat "$2.label" 2>/dev/null || echo u:object_r:unlabeled:s0) $2"`) + stub("pgrep", `[ "$1" = -u ] || exit 1 +grep -qx "$2" "$R/running" 2>/dev/null && echo 4242 +exit 0`) + // the stub directory is the first PATH entry (stubbedSh): without it, mv is the real one + stub("mv", `[ "$1" = -f ] || { echo "mv: unexpected $*" >&2; exit 1; } +`+fails("mv", "$3")+`PATH=${PATH#*:} +mv -f "$2" "$3" || exit 1 +for x in owner mode label; do + if [ -e "$2.$x" ]; then mv -f "$2.$x" "$3.$x"; else rm -f "$3.$x"; fi +done +echo "${3#$R}" >> "$R/mv.log"`) + stub("nohup", `exit 0`) + stub("sync", `echo sync >> "$R/sync.log"`) + g.env = append(os.Environ(), "MODAVD_VKMODE_ROOT="+g.root, "MODAVD_PS_STUBS="+filepath.ToSlash(bin)) + return g +} + +func (g *vkGuest) path(p string) string { return filepath.FromSlash(g.root + p) } + +func (g *vkGuest) write(p, data string) { + g.t.Helper() + if err := os.MkdirAll(filepath.Dir(g.path(p)), 0o755); err != nil { + g.t.Fatal(err) + } + if err := os.WriteFile(g.path(p), []byte(data), 0o644); err != nil { + g.t.Fatal(err) + } +} + +// raw is the file as it is ("" when missing); read is it trimmed, for the stubs' text files. +func (g *vkGuest) raw(p string) string { + b, _ := os.ReadFile(g.path(p)) + return string(b) +} + +func (g *vkGuest) read(p string) string { + return strings.TrimSpace(strings.ReplaceAll(g.raw(p), "\r", "")) +} + +func (g *vkGuest) exists(p string) bool { + _, err := os.Stat(g.path(p)) + return err == nil +} + +func (g *vkGuest) remove(p string) { + g.t.Helper() + if err := os.RemoveAll(g.path(p)); err != nil { + g.t.Fatal(err) + } +} + +func (g *vkGuest) run(action string) string { + g.t.Helper() + b, err := Script(VulkanMode) + if err != nil { + g.t.Fatal(err) + } + script := g.path("/data/local/tmp/" + VulkanMode) + if err := os.WriteFile(script, b, 0o644); err != nil { + g.t.Fatal(err) + } + cmd := exec.Command(g.sh, "-c", stubbedSh, "sh", filepath.ToSlash(script), action) + cmd.Env = g.env + b, _ = cmd.CombinedOutput() + out := strings.ReplaceAll(string(b), "\r", "") + g.t.Logf("%s: %s", action, out) + return out +} + +// install makes the package's private data directory, which is how the script tells an installed app and its uid. +func (g *vkGuest) install(pkg, uid string) { + g.t.Helper() + if err := os.MkdirAll(g.path("/data/data/"+pkg), 0o755); err != nil { + g.t.Fatal(err) + } + g.write("/data/data/"+pkg+".owner", uid+":"+uid) +} + +// launched makes the folders the app gets from the system at its first start. +func (g *vkGuest) launched(pkg, uid string) { + g.t.Helper() + for _, p := range []string{vkMedia + "/" + pkg, vkFiles(pkg)} { + if err := os.MkdirAll(g.path(p), 0o755); err != nil { + g.t.Fatal(err) + } + g.write(p+".owner", uid+":1078") + g.write(p+".mode", "2770") + g.write(p+".label", vkLabel) + } +} + +func (g *vkGuest) lines(p string) int { + if s := g.read(p); s != "" { + return strings.Count(s, "\n") + 1 + } + return 0 +} + +func (g *vkGuest) mvCalls() int { return g.lines("/mv.log") } +func (g *vkGuest) syncCalls() int { return g.lines("/sync.log") } + +// wantVulkan: both files hold the byte 01 and belong to the app; the folders are the app's; no temporary file is left. +func (g *vkGuest) wantVulkan(pkg, uid, what string) { + g.t.Helper() + dir := vkFiles(pkg) + for _, p := range []string{vkMedia + "/" + pkg, dir} { + if g.read(p+".owner") != uid+":1078" || g.read(p+".mode") != "2770" || g.read(p+".label") != vkLabel { + g.t.Errorf("%s: %s: owner %q mode %q label %q", what, p, g.read(p+".owner"), g.read(p+".mode"), g.read(p+".label")) + } + } + for _, name := range []string{"vulkancaps.bin", "customvulkancaps.bin"} { + p := dir + "/" + name + if got := g.raw(p); got != "\x01" { + g.t.Errorf("%s: %s holds %q", what, name, got) + } + if g.read(p+".owner") != uid+":1078" || g.read(p+".mode") != "660" { + g.t.Errorf("%s: %s: owner %q mode %q", what, name, g.read(p+".owner"), g.read(p+".mode")) + } + } + g.wantNoTemp(pkg, what) +} + +func (g *vkGuest) wantNoTemp(pkg, what string) { + g.t.Helper() + entries, _ := os.ReadDir(g.path(vkFiles(pkg))) + for _, e := range entries { + // (the stubs' .owner / .mode files of a removed one stay: the real guest has none) + if strings.HasSuffix(e.Name(), ".modavd-vkmode") { + g.t.Errorf("%s: temporary file %s left", what, e.Name()) + } + } +} + +func TestVulkanModeNotInstalled(t *testing.T) { + g := newVKGuest(t) + if out := g.run("once"); strings.TrimSpace(out) != "" { + t.Errorf("output %q", out) + } + for _, pkg := range []string{vkPkg, vkBili} { + if g.exists(vkMedia + "/" + pkg) { + t.Errorf("made folders for %s, which is not installed", pkg) + } + } + out := g.run("status") + if !strings.Contains(out, "watchers: \n") || !strings.Contains(out, vkPkg+": not installed") || + !strings.Contains(out, vkBili+": not installed") { + t.Errorf("status %q", out) + } +} + +// Installed and never started: the folders are made as the system makes them, both files are 01; the next passes have +// nothing to do. +func TestVulkanModeBeforeFirstStart(t *testing.T) { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + out := g.run("once") + if !strings.Contains(out, vkPkg+": set to Vulkan") { + t.Errorf("output %q", out) + } + g.wantVulkan(vkPkg, vkUID, "first pass") + if g.exists(vkMedia + "/" + vkBili) { + t.Error("made folders for the bilibili package, which is not installed") + } + if out := g.run("status"); !strings.Contains(out, vkPkg+": set to Vulkan [custom=01 caps=01]\n") || + !strings.Contains(out, vkBili+": not installed\n") { + t.Errorf("status %q", out) + } + n := g.mvCalls() + if n != 2 { + t.Errorf("%d moves, want 2", n) + } + if s := g.syncCalls(); s != 1 { + t.Errorf("%d syncs, want 1", s) + } + for k := 0; k < 2; k++ { + if out := g.run("once"); strings.TrimSpace(out) != "" { + t.Errorf("pass %d: output %q", k+2, out) + } + } + if g.mvCalls() != n || g.syncCalls() != 1 { + t.Errorf("later passes wrote again (%d moves, %d syncs)", g.mvCalls(), g.syncCalls()) + } + g.wantVulkan(vkPkg, vkUID, "later passes") + if out := g.run("status"); !strings.Contains(out, vkPkg+": set to Vulkan [custom=01 caps=01]\n") { + t.Errorf("status after the later passes %q", out) + } + + // broken since (the game crashed into GLES once more): written again, and the write is logged although the note + // says "set to Vulkan" already + g.remove(vkFiles(vkPkg) + "/customvulkancaps.bin") + g.write(vkFiles(vkPkg)+"/vulkancaps.bin", "\x03") + if out := g.run("status"); !strings.Contains(out, vkPkg+": set to Vulkan [custom=- caps=03]\n") { + t.Errorf("status of the broken files %q", out) + } + if out := g.run("once"); !strings.Contains(out, vkPkg+": set to Vulkan") { + t.Errorf("rewrite not logged: output %q", out) + } + g.wantVulkan(vkPkg, vkUID, "rewritten") + if g.syncCalls() != 2 { + t.Errorf("%d syncs after the rewrite, want 2", g.syncCalls()) + } +} + +// Started once without it: the game chose GLES on its own (vulkancaps.bin 03, no customvulkancaps.bin) and closed. +func TestVulkanModeAfterTheGameChoseGLES(t *testing.T) { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + g.launched(vkPkg, vkUID) + g.write(vkFiles(vkPkg)+"/vulkancaps.bin", "\x03") + g.write(vkFiles(vkPkg)+"/vulkancaps.bin.owner", vkUID+":1078") + g.write(vkFiles(vkPkg)+"/vulkancaps.bin.mode", "660") + g.write(vkFiles(vkPkg)+"/other.dat", "game data") + g.run("once") + g.wantVulkan(vkPkg, vkUID, "after GLES") + if g.raw(vkFiles(vkPkg)+"/other.dat") != "game data" { + t.Error("another file of the game was touched") + } +} + +// customvulkancaps.bin there and not empty: a mode was chosen (in the game, or by an earlier pass), whatever the files +// hold. +func TestVulkanModeChosenAlready(t *testing.T) { + for _, c := range []struct{ custom, caps string }{{"\x01", "\x01"}, {"\x03", "\x03"}, {"\x02", ""}, {"\x00", "\x00"}} { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + g.launched(vkPkg, vkUID) + g.write(vkFiles(vkPkg)+"/customvulkancaps.bin", c.custom) + if c.caps != "" { + g.write(vkFiles(vkPkg)+"/vulkancaps.bin", c.caps) + } + out := g.run("once") + if g.raw(vkFiles(vkPkg)+"/customvulkancaps.bin") != c.custom || g.raw(vkFiles(vkPkg)+"/vulkancaps.bin") != c.caps || + g.mvCalls() != 0 { + t.Errorf("custom %q caps %q: changed to %q %q", c.custom, c.caps, + g.raw(vkFiles(vkPkg)+"/customvulkancaps.bin"), g.raw(vkFiles(vkPkg)+"/vulkancaps.bin")) + } + if !strings.Contains(out, vkPkg+": display mode chosen already") { + t.Errorf("custom %q caps %q: output %q", c.custom, c.caps, out) + } + hex := func(s string) string { + if s == "" { + return "-" + } + return fmt.Sprintf("%02x", s) + } + want := vkPkg + ": display mode chosen already [custom=" + hex(c.custom) + " caps=" + hex(c.caps) + "]\n" + if out := g.run("status"); !strings.Contains(out, want) { + t.Errorf("status %q, want %q", out, want) + } + if g.syncCalls() != 0 { + t.Errorf("custom %q caps %q: synced without a write", c.custom, c.caps) + } + } +} + +// customvulkancaps.bin empty: what a hard kill leaves of the file a few seconds after it was moved into place, not a +// choice. Both are written again. +func TestVulkanModeEmptyLeftover(t *testing.T) { + for _, caps := range []string{"\x03", ""} { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + g.launched(vkPkg, vkUID) + g.write(vkFiles(vkPkg)+"/customvulkancaps.bin", "") + g.write(vkFiles(vkPkg)+"/customvulkancaps.bin.owner", vkUID+":1078") + if caps != "" { + g.write(vkFiles(vkPkg)+"/vulkancaps.bin", caps) + } + want := "custom=empty caps=-" + if caps != "" { + want = "custom=empty caps=03" + } + if out := g.run("status"); !strings.Contains(out, vkPkg+": nothing done yet ["+want+"]\n") { + t.Errorf("caps %q: status %q", caps, out) + } + if out := g.run("once"); !strings.Contains(out, vkPkg+": set to Vulkan") { + t.Errorf("caps %q: output %q", caps, out) + } + g.wantVulkan(vkPkg, vkUID, fmt.Sprintf("empty custom, caps %q", caps)) + if g.syncCalls() != 1 { + t.Errorf("caps %q: %d syncs, want 1", caps, g.syncCalls()) + } + } +} + +// Nothing is done while the game runs; once it has exited, the next pass sets it. +func TestVulkanModeNeverUnderARunningGame(t *testing.T) { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + g.write("/running", vkUID+"\n") + g.run("once") + if g.exists(vkMedia + "/" + vkPkg) { + t.Error("made folders under a running game") + } + if out := g.run("status"); !strings.Contains(out, vkPkg+": running, set once it exits") { + t.Errorf("status %q", out) + } + // the game made its folders and chose GLES meanwhile + g.launched(vkPkg, vkUID) + g.write(vkFiles(vkPkg)+"/vulkancaps.bin", "\x03") + g.run("once") + if g.raw(vkFiles(vkPkg)+"/vulkancaps.bin") != "\x03" || g.exists(vkFiles(vkPkg)+"/customvulkancaps.bin") { + t.Error("wrote under a running game") + } + g.remove("/running") + g.run("once") + g.wantVulkan(vkPkg, vkUID, "game exited") +} + +// The two listed packages are independent of each other. +func TestVulkanModeBothListedGames(t *testing.T) { + g := newVKGuest(t) + g.install(vkBili, vkBUID) + g.run("once") + g.wantVulkan(vkBili, vkBUID, "bilibili alone") + if g.exists(vkMedia + "/" + vkPkg) { + t.Error("made folders for the official package, which is not installed") + } + + // the official one installed and running, bilibili's mode chosen in the game since + g.install(vkPkg, vkUID) + g.write("/running", vkUID+"\n") + g.write(vkFiles(vkBili)+"/customvulkancaps.bin", "\x03") + g.write(vkFiles(vkBili)+"/vulkancaps.bin", "\x03") + g.run("once") + if g.exists(vkMedia+"/"+vkPkg) || g.raw(vkFiles(vkBili)+"/customvulkancaps.bin") != "\x03" || + g.raw(vkFiles(vkBili)+"/vulkancaps.bin") != "\x03" { + t.Error("one package's state changed what was done to the other") + } + out := g.run("status") + if !strings.Contains(out, vkPkg+": running, set once it exits") || !strings.Contains(out, vkBili+": set to Vulkan") { + t.Errorf("status %q", out) + } + g.remove("/running") + g.run("once") + g.wantVulkan(vkPkg, vkUID, "official after it exited") + if g.raw(vkFiles(vkBili)+"/vulkancaps.bin") != "\x03" { + t.Error("bilibili's choice was overwritten") + } +} + +// A pass that fails half way is finished by the next one; a folder that cannot be given its owner is not left. +func TestVulkanModeFailures(t *testing.T) { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + + // the package's folder cannot be given its owner + g.write("/chown.fail", "/"+vkPkg) + out := g.run("once") + if g.exists(vkMedia + "/" + vkPkg) { + t.Error("a folder without its owner was left") + } + if !strings.Contains(out, vkPkg+": cannot make /data/media/0/Android/data/"+vkPkg+"/files") { + t.Errorf("output %q", out) + } + if out := g.run("status"); !strings.Contains(out, vkPkg+": cannot make ") { + t.Errorf("status %q", out) + } + + // files/ cannot be given its owner: the package's folder stays (it is right), files/ goes + g.write("/chown.fail", "/files") + g.run("once") + if !g.exists(vkMedia+"/"+vkPkg) || g.exists(vkFiles(vkPkg)) { + t.Errorf("package folder %v, files folder %v", g.exists(vkMedia+"/"+vkPkg), g.exists(vkFiles(vkPkg))) + } + g.remove("/chown.fail") + + // vulkancaps.bin does not get into place: customvulkancaps.bin is not written either (alone it makes the game pick + // GLES and stops the next passes), so the next pass does both + g.write("/mv.fail", "/vulkancaps.bin") + out = g.run("once") + if g.exists(vkFiles(vkPkg)+"/customvulkancaps.bin") || g.exists(vkFiles(vkPkg)+"/vulkancaps.bin") || + !strings.Contains(out, vkPkg+": cannot write the display mode files") { + t.Errorf("after a failed move of vulkancaps.bin: custom %v caps %v, output %q", + g.exists(vkFiles(vkPkg)+"/customvulkancaps.bin"), g.exists(vkFiles(vkPkg)+"/vulkancaps.bin"), out) + } + if out := g.run("status"); !strings.Contains(out, vkPkg+": cannot write the display mode files [custom=- caps=-]\n") { + t.Errorf("status %q", out) + } + g.wantNoTemp(vkPkg, "failed move of vulkancaps.bin") + + // customvulkancaps.bin does not get into place: the next pass writes it + g.write("/mv.fail", "customvulkancaps.bin") + g.run("once") + // (the note is the same as after the last pass, so it is not said again) + if out := g.run("status"); g.exists(vkFiles(vkPkg)+"/customvulkancaps.bin") || + !strings.Contains(out, vkPkg+": cannot write the display mode files [custom=- caps=01]\n") { + t.Errorf("after a failed move: status %q", out) + } + g.wantNoTemp(vkPkg, "failed move") + g.remove("/mv.fail") + out = g.run("once") + if !strings.Contains(out, vkPkg+": set to Vulkan") { + t.Errorf("output %q", out) + } + g.wantVulkan(vkPkg, vkUID, "after the failures") + if g.syncCalls() != 1 { + t.Errorf("%d syncs, want 1 (only after the write that went through)", g.syncCalls()) + } +} + +// The package's folder already there (made by the system) is kept as it is; only files/ is made. +func TestVulkanModeKeepsExistingFolder(t *testing.T) { + g := newVKGuest(t) + g.install(vkPkg, vkUID) + p := vkMedia + "/" + vkPkg + if err := os.MkdirAll(g.path(p), 0o755); err != nil { + t.Fatal(err) + } + g.write(p+".owner", vkUID+":1078") + g.write(p+".mode", "2770") + g.write(p+".label", vkLabel) + g.write(p+"/cache/x", "kept") + g.run("once") + g.wantVulkan(vkPkg, vkUID, "existing folder") + if g.raw(p+"/cache/x") != "kept" { + t.Error("the existing folder's content changed") + } +} From b82d5ae9d2c61e2ed32134ca71d3c153376ce70a Mon Sep 17 00:00:00 2001 From: qiyinxi Date: Mon, 16 Nov 2026 13:10:33 +0100 Subject: [PATCH 9/9] v0.41.1: version, resources, release notes and checksums Adds the changelog.d entries for ModAVD#218, #220, #221 (ModAVDManager#177 and #178 merged before changelog.d existed). --- changelog.d/218-apk-install.fix.md | 1 + changelog.d/220-boot-once.fix.md | 1 + changelog.d/221-taskbar-1080p.fix.md | 1 + cmd/modavd-gui/rsrc_windows_amd64.syso | Bin 73396 -> 73396 bytes internal/buildinfo/buildinfo.go | 2 +- release/0.41.1.SHA256SUMS.txt | 3 +++ release/0.41.1.md | 13 +++++++++++++ rsrc_windows_amd64.syso | Bin 73428 -> 73428 bytes 8 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 changelog.d/218-apk-install.fix.md create mode 100644 changelog.d/220-boot-once.fix.md create mode 100644 changelog.d/221-taskbar-1080p.fix.md create mode 100644 release/0.41.1.SHA256SUMS.txt create mode 100644 release/0.41.1.md diff --git a/changelog.d/218-apk-install.fix.md b/changelog.d/218-apk-install.fix.md new file mode 100644 index 0000000..1770a00 --- /dev/null +++ b/changelog.d/218-apk-install.fix.md @@ -0,0 +1 @@ +新建的实例用浏览器装安装包不再提示不允许安装未知应用 (ModAVD/ModAVD#218) diff --git a/changelog.d/220-boot-once.fix.md b/changelog.d/220-boot-once.fix.md new file mode 100644 index 0000000..54eeef7 --- /dev/null +++ b/changelog.d/220-boot-once.fix.md @@ -0,0 +1 @@ +开机时不再先进桌面再黑屏重来一遍 (ModAVD/ModAVD#220) diff --git a/changelog.d/221-taskbar-1080p.fix.md b/changelog.d/221-taskbar-1080p.fix.md new file mode 100644 index 0000000..97adec1 --- /dev/null +++ b/changelog.d/221-taskbar-1080p.fix.md @@ -0,0 +1 @@ +1080p 实例的桌面底部不再多出一条任务栏 (ModAVD/ModAVD#221) diff --git a/cmd/modavd-gui/rsrc_windows_amd64.syso b/cmd/modavd-gui/rsrc_windows_amd64.syso index 8d578287052ee00d4a960ce62b7a27f0c648d714..5fcfb014b0db9e1a5d80777103d4f4f8cee93f4d 100644 GIT binary patch delta 60 zcmdn8mu1UdmWC~iJ!1Tt3?RVB0HvqT7GwO%Zo**5pvPdieY!ZKA|sr)UxM)~D*&T$ B4GI7N delta 60 zcmdn8mu1UdmWC~iJ!1Sk3=jaNr_UB+{K{^~V8o!uV6c6