Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions internal/cli/game_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ func humanGameImport(w io.Writer, data any) {
switch r := data.(type) {
case []gamesource.Player:
for _, p := range r {
if p.Message != "" {
fmt.Fprintf(w, "%s\t-\t%s\n", p.Kind, p.Message)
continue
}
fmt.Fprintf(w, "%s\t%d\t%s\n", p.Kind, p.Index, p.Name)
}
case []string:
Expand Down
60 changes: 44 additions & 16 deletions internal/emu/game_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func copyAPKs(ctx context.Context, src, dst importDevice, pkg string, files []st
args := []string{"pm install -R --user 0 --pkg", pkg}
for _, f := range files {
target := importQuote(path.Join(dir, path.Base(f)))
err := importStream(ctx, src, dst, "cat "+importQuote(f), "cat > "+target, func(w io.Writer, r io.Reader) error { _, err := io.Copy(io.MultiWriter(w, p), r); return err })
err := importStreamFunc(ctx, src, dst, "cat "+importQuote(f), "cat > "+target, func(w io.Writer, r io.Reader) error { _, err := io.Copy(io.MultiWriter(w, p), r); return err })
if err != nil {
return err
}
Expand Down Expand Up @@ -174,6 +174,24 @@ func checkImportSpace(ctx context.Context, dst importDevice, need int64) error {
return nil
}

// appIdentity is the su argument that runs a command as the app's UID, with AID_EVERYBODY so it can traverse /storage.
func appIdentity(ctx context.Context, dst importDevice, pkg string) (string, error) {
out, err := dst.shell(ctx, "pm list packages -U --user 0 "+pkg)
if err != nil {
return "", err
}
for line := range strings.SplitSeq(out, "\n") {
f := strings.Fields(line)
if len(f) == 2 && f[0] == "package:"+pkg {
uid, e := strconv.Atoi(strings.TrimPrefix(f[1], "uid:"))
if e == nil && uid >= 10000 && uid < 100000 {
return fmt.Sprintf("%d,%d,9997", uid, uid), nil
}
}
}
return "", errs.Newf(errs.NotReady, "无法确认 %s 的应用 UID", pkg)
}

func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progress func(Progress)) (GameImportResult, error) {
result := GameImportResult{Package: g.Package}
apks, err := apkPaths(ctx, src, g.Package)
Expand Down Expand Up @@ -220,6 +238,20 @@ func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progre
sizes[f] = n
result.ResourceBytes += n
}
// Staging directories left by an interrupted import still hold their data. Remove them before the space check.
// The package's own directories belong to its app UID, so they wait for the UID unless the app is installed.
if err := removeStaleImportDirs(ctx, dst, []string{"/data/local/tmp"}); err != nil {
return result, err
}
var identity string
if reuse && len(resources) > 0 {
if identity, err = appIdentity(ctx, dst, g.Package); err != nil {
return result, err
}
if err := removeStaleImportDirs(ctx, dst.as(identity), resourceParents(resources)); err != nil {
return result, err
}
}
// pm holds its own copy of the APKs while installing them. Allow space for small files and dex optimization.
if err := checkImportSpace(ctx, dst, 2*result.APKBytes+result.ResourceBytes+(64<<20)); err != nil {
return result, err
Expand All @@ -232,28 +264,21 @@ func importGame(ctx context.Context, src, dst importDevice, g ImportGame, progre
}
}
if len(resources) > 0 {
out, err := dst.shell(ctx, "pm list packages -U --user 0 "+g.Package)
if err != nil {
return result, err
}
for line := range strings.SplitSeq(out, "\n") {
f := strings.Fields(line)
if len(f) == 2 && f[0] == "package:"+g.Package {
uid, e := strconv.Atoi(strings.TrimPrefix(f[1], "uid:"))
if e == nil && uid >= 10000 && uid < 100000 {
dst.identity = fmt.Sprintf("%d,%d,9997", uid, uid) // AID_EVERYBODY can traverse /storage.
}
if identity == "" {
if identity, err = appIdentity(ctx, dst, g.Package); err != nil {
return result, err
}
if err := removeStaleImportDirs(ctx, dst.as(identity), resourceParents(resources)); err != nil {
return result, err
}
}
if dst.identity == "" {
return result, errs.Newf(errs.NotReady, "无法确认 %s 的应用 UID", g.Package)
}
dst.identity = identity
}
for _, f := range resources {
if err := checkGuestSpace(ctx, dst, f, sizes[f]); err != nil {
return result, err
}
if err := copyResource(ctx, src, dst, f, &p); err != nil {
if err := copyResource(ctx, src, dst, f, sizes[f], &p); err != nil {
return result, errs.Newf(errs.CodeOf(err), "导入 %s 失败:%v", f, err)
}
}
Expand Down Expand Up @@ -314,6 +339,9 @@ func (m *Manager) ImportGames(ctx context.Context, target int, source gamesource
return nil, errs.New(errs.InvalidArgument, "请选择第三方应用")
}
}
if err := checkGamesStopped(ctx, src, dst, games); err != nil {
return nil, err
}
results := make([]GameImportResult, 0, len(games))
for _, g := range games {
r, err := importGame(ctx, src, dst, g, progress)
Expand Down
52 changes: 52 additions & 0 deletions internal/emu/game_import_device.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type importDevice struct {
serial string
bootID string
identity string
exec func(ctx context.Context, args ...string) (string, error) // replaces adb in tests
}

func (d importDevice) command(ctx context.Context, args ...string) *exec.Cmd {
Expand All @@ -42,6 +43,9 @@ func (d importDevice) command(ctx context.Context, args ...string) *exec.Cmd {
}

func (d importDevice) output(ctx context.Context, args ...string) (string, error) {
if d.exec != nil {
return d.exec(ctx, args...)
}
ctx, cancel := context.WithTimeout(ctx, 15*time.Minute)
defer cancel()
cmd := d.command(ctx, args...)
Expand Down Expand Up @@ -184,6 +188,54 @@ func packageList(ctx context.Context, d importDevice, flags string) ([]string, e
return pkgs, nil
}

// appRunning asks the guest, read-only, for the names of its processes (Toybox ps; NAME is argv[0], so a service of
// the app is "<package>:<service>"). The app runs when one of them is the package or starts with "<package>:". An
// answer that is not a process list (no ps -A, adb trouble) is an error rather than a guess.
func appRunning(ctx context.Context, d importDevice, pkg string) (bool, error) {
out, err := d.shell(ctx, "ps -A -o NAME; echo exit:$?")
if err != nil {
return false, err
}
var names []string
for line := range strings.SplitSeq(out, "\n") {
if line = strings.TrimSpace(line); line != "" && line != "NAME" {
names = append(names, line)
}
}
if n := len(names); n < 2 || names[n-1] != "exit:0" {
return false, fmt.Errorf("ps: %q", tail(out, 200))
}
for _, name := range names {
if name == pkg || strings.HasPrefix(name, pkg+":") {
return true, nil
}
}
return false, nil
}

// checkGamesStopped refuses to start while any of the games is running on the target (it would be writing the
// resources being merged) or on the source (its files would change during the copy). It never stops a game.
func checkGamesStopped(ctx context.Context, src, dst importDevice, games []ImportGame) error {
for _, g := range games {
running, err := appRunning(ctx, dst, g.Package)
if err != nil {
return err
}
if running {
return errs.Newf(errs.PrecheckFailed, "目标实例上的 %s 正在运行,请先退出游戏再导入", g.Package)
}
}
for _, g := range games {
running, err := appRunning(ctx, src, g.Package)
if err != nil {
return err
}
if running {
return errs.Newf(errs.PrecheckFailed, "源模拟器上的 %s 正在运行,请先退出游戏再导入", g.Package)
}
}
return nil
}
func (m *Manager) SourcePackages(ctx context.Context, source gamesource.Source) ([]string, error) {
d, err := m.gameSource(ctx, source)
if err != nil {
Expand Down
124 changes: 124 additions & 0 deletions internal/emu/game_import_flow_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
//go:build windows

// Copyright 2026 jinghero. SPDX-License-Identifier: AGPL-3.0-or-later
package emu

import (
"context"
"slices"
"strings"
"testing"

"modavd/internal/logx"
)

const (
flowSum = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
flowDF = "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/block 100000000 1 99999999 1% /data\n"
)

// flowGuests are a source and a target answering importGame's queries. The target holds the app already when
// installed is true.
func flowGuests(t *testing.T, installed bool) (src, dst *scriptedGuest) {
t.Helper()
m := &Manager{Root: managerTestRoot(t, 1), Log: logx.Nop()}
apk := "package:/data/app/~~x/example.game-1/base.apk\n"
common := func(script string) (string, bool) {
switch {
case strings.Contains(script, "pm path --user 0"):
return apk, true
case strings.Contains(script, "sha256sum"):
return flowSum + " /data/app/~~x/example.game-1/base.apk\n", true
}
return "", false
}
src = &scriptedGuest{reply: func(script string) (string, error) {
if out, ok := common(script); ok {
return out, nil
}
switch {
case strings.Contains(script, "-printf '%s"):
if strings.Contains(script, "/sdcard/") {
return "200", nil
}
return "100", nil
}
return "", nil
}}
dst = &scriptedGuest{reply: func(script string) (string, error) {
if out, ok := common(script); ok {
return out, nil
}
switch {
case strings.Contains(script, "pm list packages -u"):
if installed {
return "package:example.game\n", nil
}
return "", nil
case strings.Contains(script, "pm list packages -U"):
return "package:example.game uid:10123\n", nil
case strings.Contains(script, "df -Pk"):
return flowDF, nil
case strings.Contains(script, "pm install"):
return "Success\n", nil
}
return "", nil
}}
src.m, dst.m = m, m
return src, dst
}

func (g *scriptedGuest) index(sub string) int {
g.mu.Lock()
defer g.mu.Unlock()
return slices.IndexFunc(g.scripts, func(s string) bool { return strings.Contains(s, sub) })
}

// ModAVD/ModAVD#272: the leftovers are gone before the space check, whether or not the app is installed yet, and
// the ones in the package's own directories are removed as the app's UID.
func TestImportGameRemovesStaleDirsBeforeCopying(t *testing.T) {
for _, installed := range []bool{false, true} {
name := "installing"
if installed {
name = "already installed"
}
t.Run(name, func(t *testing.T) {
fakeStream(t, func(read, write string) int {
if strings.HasPrefix(write, "cat > ") {
return 100
}
return 200
})
src, dst := flowGuests(t, installed)
sd, dd := src.device(), dst.device()
g := ImportGame{Package: "example.game", Data: []string{"files/assets"}}
res, err := importGame(context.Background(), sd, dd, g, nil)
if err != nil {
t.Fatal(err)
}
if res.ResourceBytes != 200 {
t.Fatalf("result=%+v", res)
}
tmp := dst.index("-exec rm -rf")
df := dst.index("df -Pk")
if tmp < 0 || df < 0 || tmp > df || !strings.Contains(dst.scripts[tmp], "/data/local/tmp") || strings.Contains(dst.scripts[tmp], "su 10123") {
t.Fatalf("/data/local/tmp cleanup at %d, space check at %d: %q", tmp, df, dst.scripts)
}
app := "/sdcard/Android/data/example.game/files"
appClean := -1
for i, s := range dst.scripts {
if strings.Contains(s, "-exec rm -rf") && strings.Contains(s, app) && strings.Contains(s, "su 10123,10123,9997") {
appClean = i
break
}
}
stage := dst.index(app + "/.modavd-import.XXXXXXXX") // the first staging directory in the app's directory
if appClean < 0 || stage < 0 || appClean > stage {
t.Fatalf("app directory cleanup at %d, staging at %d: %q", appClean, stage, dst.scripts)
}
if installed && appClean > df {
t.Fatalf("an installed app's directories must be cleaned before the space check: %d > %d", appClean, df)
}
})
}
}
Loading
Loading