Initialize local project and fix ranch growth synchronization

This commit is contained in:
AttilaNet
2026-11-07 22:14:49 +08:00
commit 657f5f33b5
1417 changed files with 202171 additions and 0 deletions
+106
View File
@@ -0,0 +1,106 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ABC;
import com.jpexs.decompiler.flash.abc.ScriptPack;
import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction;
import com.jpexs.decompiler.flash.abc.types.MethodBody;
import java.io.BufferedInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/** Checks reachable operand/scope stack heights and every branch destination. */
public final class AuditBattleBytecode {
public static int verify(ABC abc, MethodBody body) {
var code = body.getCode();
Map<Long, Integer> positions = new HashMap<>();
for (int i = 0; i < code.code.size(); i++) positions.put(code.code.get(i).getAddress(), i);
int errors = 0;
for (var ins : code.code) {
if (ins.isBranch() || ins.isJump()) for (long target : ins.getOffsets()) {
if (!positions.containsKey(target)) {
System.out.println(" INVALID BRANCH " + ins.getAddress() + " -> " + target);
errors++;
}
}
}
Deque<int[]> pending = new ArrayDeque<>();
pending.add(new int[]{0, 0, body.init_scope_depth});
for (var ex : body.exceptions) {
if (positions.containsKey((long) ex.target)) pending.add(new int[]{positions.get((long) ex.target), 1, body.init_scope_depth});
}
Map<Integer, String> seen = new HashMap<>();
while (!pending.isEmpty()) {
int[] state = pending.removeFirst();
int index = state[0], height = state[1], scope = state[2];
if (index < 0 || index >= code.code.size()) continue;
String value = height + "/" + scope;
String old = seen.putIfAbsent(index, value);
var ins = code.code.get(index);
if (old != null) {
if (!old.equals(value)) {
System.out.println(" STACK MERGE " + ins.getAddress() + " " + old + " != " + value);
errors++;
}
continue;
}
int pops = ins.definition.getStackPopCount(ins, abc);
int pushes = ins.definition.getStackPushCount(ins, abc);
if (height < pops) {
System.out.println(" STACK UNDERFLOW at " + ins.getAddress() + " " + ins.definition.instructionName + " height=" + height + " needs=" + pops);
errors++;
continue;
}
height += pushes - pops;
scope += ins.definition.getScopeStackDelta(ins, abc);
if (height > body.max_stack || scope < body.init_scope_depth || scope > body.max_scope_depth) {
System.out.println(" STACK LIMIT at " + ins.getAddress() + " stack=" + height + "/" + body.max_stack + " scope=" + scope + "/" + body.max_scope_depth);
errors++;
}
if (ins.isBranch() || ins.isJump()) for (long target : ins.getOffsets()) {
Integer next = positions.get(target);
if (next != null) pending.add(new int[]{next, height, scope});
}
if (!ins.isExit() && !ins.isJump() && !ins.definition.instructionName.equals("lookupswitch")) pending.add(new int[]{index + 1, height, scope});
}
return errors;
}
public static void main(String[] args) throws Exception {
boolean bad = false;
for (String filename : args) {
if (filename.equals("--dump")) continue;
boolean dump = Arrays.asList(args).contains("--dump");
try (var input = new BufferedInputStream(Files.newInputStream(Path.of(filename)))) {
SWF swf = new SWF(input, false);
for (ScriptPack pack : swf.getAS3Packs()) {
String name = pack.getClassPath().toString();
Set<String> methods = switch (name) {
case "net.pixvi.myr.battle.view.BattleMon" -> Set.of("beHurt", "all_atk", "init");
case "net.pixvi.myr.center.TeamCenter" -> Set.of("getBattleTeamVo");
case "net.pixvi.myrloader.MYRLoaderStarter" -> Set.of("fixComplete");
case "MYRStarter" -> Set.of("MYRStart");
default -> Set.of();
};
if (methods.isEmpty()) continue;
ABC abc = pack.abc;
for (MethodBody body : abc.bodies) {
String method = abc.constants.getString(abc.method_info.get(body.method_info).name_index);
if (method == null || !methods.contains(method)) continue;
System.out.println("CHECK " + filename + " " + name + "." + method + " method=" + body.method_info + " bytes=" + body.getCodeBytes().length);
int errors = verify(abc, body);
System.out.println((errors == 0 ? "PASS" : "FAIL") + " control-flow/stack errors=" + errors);
bad |= errors != 0;
if (dump) {
Path target = Path.of("analysis", "bytecode_audit", Path.of(filename).getFileName() + "." + method + ".txt");
Files.createDirectories(target.getParent());
StringBuilder out = new StringBuilder();
for (var ins : body.getCode().code) out.append(String.format("%04x %s%n", ins.getAddress(), ins.toStringNoAddress(abc.constants, List.of())));
Files.writeString(target, out);
}
}
}
}
}
if (bad) System.exit(1);
}
}
+44
View File
@@ -0,0 +1,44 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ScriptPack;
import java.io.BufferedInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HexFormat;
/** Offline byte comparison of check/report methods; does not execute game code. */
public final class CompareBattleChecks {
private static byte[] method(SWF swf, String target, String name) {
for (ScriptPack pack : swf.getAS3Packs()) {
if (!pack.getClassPath().toString().equals(target)) continue;
int index = pack.abc.findMethodBodyByName(target, name);
if (index >= 0) return pack.abc.bodies.get(index).getCodeBytes();
}
throw new IllegalArgumentException("Method missing: " + target + "." + name);
}
public static void main(String[] args) throws Exception {
if (args.length != 2) throw new IllegalArgumentException("original.app patched.app");
try (var a = new BufferedInputStream(Files.newInputStream(Path.of(args[0])));
var b = new BufferedInputStream(Files.newInputStream(Path.of(args[1])))) {
SWF original = new SWF(a, false), patched = new SWF(b, false);
String[][] targets = {
{"net.pixvi.myr.panel.battle.BattlePanel", "cheatCheck"},
{"net.pixvi.myr.element.battle.BattleMonVo", "checkCheat"},
{"net.pixvi.myr.element.battle.BattleData", "getObj"},
{"net.pixvi.myr.battle.view.BattleMon", "beCure"},
{"net.pixvi.myr.battle.BattleGround", "deadHandler"},
{"net.pixvi.myr.net.NetStage", "finishStageBattle"}
};
for (var target : targets) {
byte[] left = method(original, target[0], target[1]);
byte[] right = method(patched, target[0], target[1]);
boolean same = Arrays.equals(left, right);
String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(right));
System.out.println((same ? "UNCHANGED " : "CHANGED ") + target[0] + "." + target[1]
+ " bytes=" + right.length + " sha256=" + digest);
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import jadx.api.*;
import java.nio.file.*;
public final class InspectAirExtraction {
public static void main(String[] args) throws Exception {
JadxArgs config = new JadxArgs();
config.setInputFile(Path.of(args[0]).toFile());
Path output = Path.of("analysis", "air_runtime");
Files.createDirectories(output);
try (JadxDecompiler decompiler = new JadxDecompiler(config)) {
decompiler.load();
for (String name : new String[]{"com.adobe.air.ApplicationFileManager", "com.adobe.air.ApplicationFileInfo", "com.adobe.air.ResourceFileManager", "air.net.pixvi.myrzx.AppEntry"}) {
JavaClass cls = decompiler.searchJavaClassByOrigFullName(name);
if (cls == null) { System.out.println("MISSING " + name); continue; }
Files.writeString(output.resolve(name + ".java"), cls.getCode());
System.out.println("EXPORTED " + name);
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import jadx.api.*;
import java.nio.file.*;
import java.util.*;
public final class InspectGameSdk {
public static void main(String[] args) throws Exception {
JadxArgs config = new JadxArgs();
config.setInputFile(Path.of(args[0]).toFile());
Path output = Path.of("analysis", "sdk_login");
Files.createDirectories(output);
try (JadxDecompiler decompiler = new JadxDecompiler(config)) {
decompiler.load();
if (args[1].equals("list")) {
for (JavaClass cls : decompiler.getClassesWithInners()) {
String name = cls.getFullName();
if (args.length > 2 ? name.matches(args[2]) : name.toLowerCase().contains("diyidan") && name.toLowerCase().matches(".*(login|user|account|api|http|request|crypt|sign|game).*")) System.out.println(name);
}
} else {
for (int i = 1; i < args.length; i++) {
JavaClass cls = decompiler.searchJavaClassByOrigFullName(args[i]);
if (cls == null) { System.out.println("MISSING " + args[i]); continue; }
Files.writeString(output.resolve(args[i] + ".java"), cls.getCode());
System.out.println("EXPORTED " + args[i]);
}
}
}
}
}
+248
View File
@@ -0,0 +1,248 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ABC;
import com.jpexs.decompiler.flash.abc.ScriptPack;
import com.jpexs.decompiler.flash.abc.avm2.AVM2Code;
import com.jpexs.decompiler.flash.abc.avm2.AVM2ConstantPool;
import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction;
import com.jpexs.decompiler.flash.abc.types.MethodBody;
import com.jpexs.decompiler.flash.abc.types.Namespace;
import com.jpexs.decompiler.flash.tags.Tag;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/** Inserts real instructions; preserves existing instructions, signatures and other SWF tags. */
public final class SurgicalBattlePatch {
private static final String STATUS_NAME = "local_battle_mod_v3";
private static final Map<String, Integer> OPCODES = new HashMap<>();
static {
for (var def : AVM2Code.instructionSet) if (def != null) OPCODES.put(def.instructionName, def.instructionCode);
}
private static AVM2Instruction op(String name, int... operands) {
Integer code = OPCODES.get(name);
if (code == null) throw new IllegalArgumentException("Unknown instruction " + name);
return new AVM2Instruction(0, code, operands);
}
private static int q(ABC abc, String ns, String name) {
return abc.constants.getQnameId(name, Namespace.KIND_PACKAGE, ns, true);
}
private static int p(ABC abc, String name) { return q(abc, "", name); }
private static final class Fragment {
final ABC abc;
final List<AVM2Instruction> instructions = new ArrayList<>();
final IdentityHashMap<AVM2Instruction, AVM2Instruction> branches = new IdentityHashMap<>();
Fragment(ABC abc) { this.abc = abc; }
Fragment add(String name, int... values) { instructions.add(op(name, values)); return this; }
Fragment string(String value) { return add("pushstring", abc.constants.getStringId(value, true)); }
Fragment get(String value) { return add("getproperty", p(abc, value)); }
Fragment set(String value) { return add("setproperty", p(abc, value)); }
Fragment local(int index) { return add("getlocal", index); }
AVM2Instruction label() { var label = op("nop"); instructions.add(label); return label; }
AVM2Instruction branch(String name) { var instruction = op(name, 0); instructions.add(instruction); return instruction; }
void target(AVM2Instruction branch, AVM2Instruction target) { branches.put(branch, target); }
Fragment stage() { return add("getlex", q(abc, "net.pixvi.common.driver", "StageDriver")).get("stage"); }
}
private static final class Editor {
final ABC abc;
final MethodBody body;
final AVM2Code code;
final IdentityHashMap<AVM2Instruction, List<AVM2Instruction>> targets = new IdentityHashMap<>();
Editor(ABC abc, MethodBody body) {
this.abc = abc; this.body = body; this.code = body.getCode();
Map<Long, AVM2Instruction> byAddress = new HashMap<>();
for (var ins : code.code) byAddress.put(ins.getAddress(), ins);
for (var ins : code.code) if (ins.isBranch() || ins.isJump()) {
List<AVM2Instruction> list = new ArrayList<>();
for (long offset : ins.getOffsets()) {
var target = byAddress.get(offset);
if (target == null) throw new IllegalStateException("Invalid original branch " + offset);
list.add(target);
}
targets.put(ins, list);
}
if (body.exceptions.length != 0) throw new IllegalStateException("Exception relocation needs explicit handling");
}
void insertBefore(AVM2Instruction anchor, Fragment fragment) {
int index = code.code.indexOf(anchor);
if (index < 0 || fragment.instructions.isEmpty()) throw new IllegalArgumentException("Missing anchor/fragment");
// A branch to the original statement must enter the new prefix too.
for (var list : targets.values()) for (int i = 0; i < list.size(); i++) {
if (list.get(i) == anchor) list.set(i, fragment.instructions.get(0));
}
code.code.addAll(index, fragment.instructions);
fragment.branches.forEach((branch, target) -> targets.put(branch, new ArrayList<>(List.of(target))));
}
void finish() {
long address = 0;
for (var ins : code.code) { ins.setAddress(address); address += ins.getBytesLength(); }
targets.forEach((branch, list) -> {
if (branch.definition.instructionName.equals("lookupswitch")) {
branch.operands[0] = Math.toIntExact(list.get(0).getAddress() - branch.getAddress());
for (int i = 1; i < list.size(); i++) branch.operands[i + 1] = Math.toIntExact(list.get(i).getAddress() - branch.getAddress());
} else {
branch.operands[0] = Math.toIntExact(list.get(0).getAddress() - branch.getAddress() - branch.getBytesLength());
}
});
body.max_stack = Math.max(body.max_stack, 10);
body.setCode(code);
body.setModified();
((Tag) abc.parentTag).setModified(true);
if (AuditBattleBytecode.verify(abc, body) != 0) throw new AssertionError("Inserted code failed stack/control-flow verification");
}
}
private static MethodBody method(ScriptPack pack, String name) {
List<MethodBody> found = new ArrayList<>();
for (var body : pack.abc.bodies) {
String value = pack.abc.constants.getString(pack.abc.method_info.get(body.method_info).name_index);
if (name.equals(value)) found.add(body);
}
if (found.size() != 1) throw new IllegalStateException(name + " matches=" + found.size());
return found.get(0);
}
private static void makeBanner(ScriptPack pack, String title) {
ABC abc = pack.abc;
MethodBody body = method(pack, "MYRStart");
Editor edit = new Editor(abc, body);
var anchor = edit.code.code.get(edit.code.code.size() - 1);
if (!anchor.definition.instructionName.equals("returnvoid")) throw new IllegalStateException("Unexpected startup ending");
int reg = body.max_regs++;
int textField = q(abc, "flash.text", "TextField");
Fragment f = new Fragment(abc);
f.add("findpropstrict", textField).add("constructprop", textField, 0).add("coerce", textField).add("setlocal", reg);
f.local(reg).string(STATUS_NAME).set("name");
f.local(reg).add("pushshort", 760).set("width");
f.local(reg).add("pushbyte", 64).set("height");
f.local(reg).add("pushfalse").set("mouseEnabled");
f.local(reg).add("pushfalse").set("selectable");
f.local(reg).add("pushtrue").set("background");
f.local(reg).add("pushint", abc.constants.getIntId(0x123526, true)).set("backgroundColor");
int format = q(abc, "flash.text", "TextFormat");
f.local(reg).add("findpropstrict", format).string("_sans").add("pushbyte", 22)
.add("pushint", abc.constants.getIntId(0xffffff, true)).add("pushtrue")
.add("constructprop", format, 4).set("defaultTextFormat");
f.local(reg).string(title + "\nWAITING FOR LOCAL BATTLE").set("text");
f.stage().local(reg).add("callpropvoid", p(abc, "addChild"), 1);
edit.insertBefore(anchor, f);
edit.finish();
}
private static AVM2Instruction beginStatus(Fragment f, int reg) {
f.stage().string(STATUS_NAME).add("callproperty", p(f.abc, "getChildByName"), 1)
.add("coerce", q(f.abc, "flash.text", "TextField")).add("setlocal", reg).local(reg);
var absent = f.branch("iffalse");
f.local(reg);
return absent;
}
private static void finishStatus(Fragment f, AVM2Instruction absent) {
f.set("text");
var end = f.label();
f.target(absent, end);
}
private static void teamPatch(ScriptPack pack, boolean stats, String title) {
ABC abc = pack.abc;
MethodBody body = method(pack, "getBattleTeamVo");
Editor edit = new Editor(abc, body);
if (body.getCodeBytes().length != 284) throw new IllegalStateException("Expected pristine team method");
var anchor = edit.code.code.stream().filter(i -> i.getAddress() == 0xd4).findFirst().orElseThrow();
Fragment f = new Fragment(abc);
if (stats) {
String[] ints = {"atk", "def", "dex", "hp", "hpMax", "atkPoiDmg", "sunFire", "moonHeal", "deadBoom", "thorns"};
String[] numbers = {"crit", "selfCure", "atkVim", "atkStun", "defStun", "atkPoi", "skillCooldown"};
for (String name : ints) f.local(5).local(5).get(name).add("pushbyte", 2).add("multiply").add("convert_i").set(name);
for (String name : numbers) f.local(5).local(5).get(name).add("pushbyte", 2).add("multiply").add("convert_d").set(name);
}
var absent = beginStatus(f, body.max_regs++);
f.string(title + "\nENTRY ATK=").local(5).get("atk").add("add")
.string(" DEF=").add("add").local(5).get("def").add("add")
.string(" DEX=").add("add").local(5).get("dex").add("add")
.string(" HP=").add("add").local(5).get("hp").add("add")
.string("/").add("add").local(5).get("hpMax").add("add");
finishStatus(f, absent);
edit.insertBefore(anchor, f);
edit.finish();
}
private static void damagePatch(ScriptPack pack, String title) {
ABC abc = pack.abc;
MethodBody body = method(pack, "beHurt");
Editor edit = new Editor(abc, body);
if (body.getCodeBytes().length != 1552) throw new IllegalStateException("Expected pristine damage method");
var anchor = edit.code.code.stream().filter(i -> i.getAddress() == 0x280).findFirst().orElseThrow();
Fragment f = new Fragment(abc);
f.local(2).add("pushnull").add("equals");
var noEnemy = f.branch("iftrue");
f.local(2).get("team").add("pushbyte", 1);
var notPlayer = f.branch("ifne");
f.add("getlocal0").get("team").add("pushbyte", 2);
var notEnemy = f.branch("ifne");
int oldDamage = body.max_regs++;
f.local(14).add("setlocal", oldDamage);
// Cap before converting back to int, so multiplication cannot wrap.
f.add("getlex", p(abc, "Math")).local(14).add("pushbyte", 10).add("multiply")
.add("pushint", abc.constants.getIntId(50000, true)).add("callproperty", p(abc, "min"), 2)
.add("convert_i").add("setlocal", 14);
var absent = beginStatus(f, body.max_regs++);
f.string(title + "\nHIT ").local(oldDamage).add("add").string(" -> ").add("add")
.local(14).add("add").string(" (PLAYER > ENEMY)").add("add");
finishStatus(f, absent);
var end = f.label();
f.target(noEnemy, end); f.target(notPlayer, end); f.target(notEnemy, end);
edit.insertBefore(anchor, f);
edit.finish();
}
private static byte[] spliceTags(byte[] original, Collection<Tag> tags) throws IOException {
if (original[0] != 'F' || original[1] != 'W' || original[2] != 'S') throw new IllegalArgumentException("FWS input required");
ByteArrayOutputStream output = new ByteArrayOutputStream(original.length + 4096);
int start = 0;
for (Tag tag : tags.stream().sorted(Comparator.comparingLong(Tag::getPos)).toList()) {
int position = Math.toIntExact(tag.getPos());
int end = Math.toIntExact(tag.getDataPos() + tag.getOriginalDataLength());
output.write(original, start, position - start);
byte[] data = tag.getData();
int header = (82 << 6) | 63;
output.write(header & 0xff); output.write((header >>> 8) & 0xff);
for (int i = 0; i < 4; i++) output.write((data.length >>> (8 * i)) & 0xff);
output.write(data);
start = end;
System.out.println("TAG " + position + " old=" + (end - position) + " new=" + (data.length + 6));
}
output.write(original, start, original.length - start);
byte[] bytes = output.toByteArray();
for (int i = 0; i < 4; i++) bytes[4 + i] = (byte)(bytes.length >>> (8 * i));
return bytes;
}
public static void main(String[] args) throws Exception {
if ((args.length != 3 && args.length != 4) || !Set.of("damage", "stats").contains(args[2])) throw new IllegalArgumentException("Usage: SurgicalBattlePatch original.app output.app damage|stats [revision]");
byte[] input = Files.readAllBytes(Path.of(args[0]));
boolean stats = args[2].equals("stats");
String revision = args.length == 4 ? args[3] : "V3";
if (!revision.matches("V[0-9]+")) throw new IllegalArgumentException("Invalid revision");
String title = stats ? "LOCAL S2 " + revision + " | PLAYER STATS x2" : "LOCAL D10 " + revision + " | DAMAGE x10 CAP 50000";
SWF swf = new SWF(new ByteArrayInputStream(input), false);
Set<Tag> modified = Collections.newSetFromMap(new IdentityHashMap<>());
Set<String> found = new HashSet<>();
for (ScriptPack pack : swf.getAS3Packs()) {
String name = pack.getClassPath().toString();
if (name.equals("MYRStarter")) makeBanner(pack, title);
else if (name.equals("net.pixvi.myr.center.TeamCenter")) teamPatch(pack, stats, title);
else if (!stats && name.equals("net.pixvi.myr.battle.view.BattleMon")) damagePatch(pack, title);
else continue;
modified.add((Tag) pack.abc.parentTag);
found.add(name);
}
if (found.size() != (stats ? 2 : 3)) throw new IllegalStateException("Targets missing " + found);
Files.write(Path.of(args[1]), spliceTags(input, modified));
System.out.println("WROTE " + args[1] + " modified tags=" + modified.size());
}
}
+145
View File
@@ -0,0 +1,145 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ABC;
import com.jpexs.decompiler.flash.abc.avm2.LocalDataArea;
import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction;
import com.jpexs.decompiler.flash.abc.types.MethodBody;
import com.jpexs.decompiler.flash.ecma.Null;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/** Executes inserted bytes with FFDec arithmetic/branches and stubbed display/property access.
* This is a fragment test, not a substitute for Android AIR runtime testing.
*/
public final class TestBattleFragment {
private static String property(ABC abc, AVM2Instruction ins) {
return abc.constants.getString(abc.constants.getMultiname(ins.operands[0]).name_index);
}
@SuppressWarnings("unchecked")
private static void execute(ABC abc, MethodBody body, long start, long end, Map<Integer, Object> registers, Map<String, Object> banner) throws Exception {
var code = body.getCode().code;
Map<Long, Integer> positions = new HashMap<>();
for (int i = 0; i < code.size(); i++) positions.put(code.get(i).getAddress(), i);
LocalDataArea area = new LocalDataArea();
area.localRegisters.putAll(registers);
Object stage = new Object();
Map<String, Object> driver = Map.of("stage", stage);
int index = positions.get(start), steps = 0;
while (code.get(index).getAddress() < end) {
if (++steps > 2000) throw new AssertionError("Fragment did not terminate");
var ins = code.get(index);
String opcode = ins.definition.instructionName;
area.jump = null;
switch (opcode) {
case "getlex" -> {
String name = property(abc, ins);
area.operandStack.push(switch (name) {
case "Math" -> Math.class;
case "StageDriver" -> driver;
default -> throw new AssertionError("Unexpected global " + name);
});
}
case "getproperty" -> {
Object object = area.operandStack.pop();
area.operandStack.push(((Map<String, Object>) object).get(property(abc, ins)));
}
case "setproperty" -> {
Object value = area.operandStack.pop();
Map<String, Object> object = (Map<String, Object>) area.operandStack.pop();
object.put(property(abc, ins), value);
}
case "callproperty" -> {
List<Object> args = new ArrayList<>();
for (int i = 0; i < ins.operands[1]; i++) args.add(0, area.operandStack.pop());
Object receiver = area.operandStack.pop();
String name = property(abc, ins);
if (receiver == Math.class && name.equals("min")) {
area.operandStack.push(Math.min(((Number) args.get(0)).doubleValue(), ((Number) args.get(1)).doubleValue()));
} else if (receiver == stage && name.equals("getChildByName")) {
area.operandStack.push(banner == null ? Null.INSTANCE : banner);
} else throw new AssertionError("Unexpected call " + name);
}
case "coerce" -> { /* Display stub is already represented by its map. */ }
default -> {
if (!ins.definition.execute(area, abc.constants, ins)) throw new AssertionError("Unsupported instruction " + opcode);
}
}
index = area.jump == null ? index + 1 : positions.get(ins.getTargetAddress());
}
if (code.get(index).getAddress() != end || !area.operandStack.empty()) throw new AssertionError("Fragment exit/stack mismatch");
registers.putAll(area.localRegisters);
}
private static void damageCases(ABC abc, MethodBody body) throws Exception {
long end = -1;
var code = body.getCode().code;
for (int i = 0; i < code.size() - 1; i++) {
var a = code.get(i); var b = code.get(i + 1);
if (a.getAddress() > 0x280 && a.definition.instructionName.equals("getlex")
&& property(abc, a).equals("monVo") && b.definition.instructionName.equals("debugline") && b.operands[0] == 977) {
end = a.getAddress(); break;
}
}
if (end < 0) throw new AssertionError("Damage insertion boundaries missing");
int[][] cases = {
{1, 2, 123, 1230}, {1, 2, 0, 0}, {1, 2, 4999, 49990},
{1, 2, 5000, 50000}, {1, 2, 9000, 50000}, {1, 2, Integer.MAX_VALUE, 50000},
{2, 1, 123, 123}, {1, 1, 123, 123}, {2, 2, 123, 123}, {0, 2, 123, 123}
};
for (boolean visible : new boolean[]{true, false}) for (int[] c : cases) {
Map<Integer, Object> locals = new HashMap<>();
locals.put(0, Map.of("team", (long)c[1]));
locals.put(2, c[0] == 0 ? Null.INSTANCE : Map.of("team", (long)c[0]));
locals.put(14, (long)c[2]);
Map<String, Object> banner = visible ? new HashMap<>() : null;
execute(abc, body, 0x280, end, locals, banner);
int actual = ((Number)locals.get(14)).intValue();
if (actual != c[3]) throw new AssertionError("Wrong damage " + Arrays.toString(c) + " actual=" + actual);
if (visible && c[0] == 1 && c[1] == 2 && !banner.get("text").toString().contains(" -> " + c[3])) throw new AssertionError("Hit diagnostics missing");
}
System.out.println("PASS 20 damage fragment cases: player/enemy/null, cap, integer overflow, banner present/absent");
}
private static void statsCase(ABC abc, MethodBody body) throws Exception {
var code = body.getCode().code;
long end = -1;
for (int i = 0; i < code.size() - 1; i++) {
var a = code.get(i); var b = code.get(i + 1);
if (a.getAddress() > 0xd4 && a.definition.instructionName.equals("getlocal") && a.operands[0] == 5
&& b.definition.instructionName.equals("debugline") && b.operands[0] == 202) { end = a.getAddress(); break; }
}
if (end < 0) throw new AssertionError("Stat insertion boundaries missing");
String[] names = {"atk", "def", "dex", "hp", "hpMax", "atkPoiDmg", "sunFire", "moonHeal", "deadBoom", "thorns", "crit", "selfCure", "atkVim", "atkStun", "defStun", "atkPoi", "skillCooldown"};
for (boolean visible : new boolean[]{true, false}) {
Map<String, Object> mon = new HashMap<>();
for (int i = 0; i < names.length; i++) mon.put(names[i], i < 10 ? (Object)Long.valueOf(100 + i) : Double.valueOf(0.1));
Map<String, Object> before = new HashMap<>(mon);
Map<Integer, Object> locals = new HashMap<>(); locals.put(5, mon);
Map<String, Object> banner = visible ? new HashMap<>() : null;
execute(abc, body, 0xd4, end, locals, banner);
for (String name : names) {
double expected = ((Number)before.get(name)).doubleValue() * 2;
if (Math.abs(((Number)mon.get(name)).doubleValue() - expected) > 0.000001) throw new AssertionError("Wrong stat " + name);
}
if (visible && !banner.get("text").toString().contains("ENTRY ATK=200")) throw new AssertionError("Entry diagnostics missing");
}
System.out.println("PASS 34 stat fragment assertions including HP/max HP and fractional modifiers");
}
public static void main(String[] args) throws Exception {
boolean stats = args[1].equals("stats");
try (var input = new BufferedInputStream(Files.newInputStream(Path.of(args[0])))) {
SWF swf = new SWF(input, false);
String target = stats ? "net.pixvi.myr.center.TeamCenter" : "net.pixvi.myr.battle.view.BattleMon";
String name = stats ? "getBattleTeamVo" : "beHurt";
for (var pack : swf.getAS3Packs()) if (pack.getClassPath().toString().equals(target)) {
for (var body : pack.abc.bodies) if (name.equals(pack.abc.constants.getString(pack.abc.method_info.get(body.method_info).name_index))) {
if (stats) statsCase(pack.abc, body); else damageCases(pack.abc, body);
return;
}
}
}
throw new AssertionError("Target method missing");
}
}
+56
View File
@@ -0,0 +1,56 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ScriptPack;
import com.jpexs.decompiler.flash.abc.types.traits.TraitClass;
import com.jpexs.decompiler.flash.abc.types.traits.TraitMethodGetterSetter;
import java.io.BufferedInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/** A deterministic regression check for the exact methods changed in the SWF. */
public final class VerifySwfPatch {
public static void main(String[] args) throws Exception {
if (args.length != 2 || !List.of("damage", "stats").contains(args[1])) {
throw new IllegalArgumentException("Usage: VerifySwfPatch file.app damage|stats");
}
boolean stats = args[1].equals("stats");
try (var input = new BufferedInputStream(Files.newInputStream(Path.of(args[0])))) {
SWF swf = new SWF(input, false);
for (ScriptPack pack : swf.getAS3Packs()) {
String target = stats ? "net.pixvi.myr.center.TeamCenter" : "net.pixvi.myr.battle.view.BattleMon";
if (!pack.getClassPath().toString().equals(target)) continue;
var abc = pack.abc;
String method = stats ? "getBattleTeamVo" : "beHurt";
int index = abc.findMethodBodyByName(target, method);
if (index < 0) throw new AssertionError(method + " not found");
var body = abc.bodies.get(index);
var trait = abc.getMethodIndexing().findMethodTraits(pack, index).get(0);
var signature = abc.method_info.get(((TraitMethodGetterSetter) trait).method_info);
String code = body.getCode().toASMSource(abc);
require(signature.param_types.length == (stats ? 1 : 13), "method signature changed");
if (stats) {
require(count(code, "multiply") == 16, "expected 16 doubled stats");
require(code.contains("getproperty QName(PackageNamespace(\"\"),\"hp\")")
&& code.contains("setproperty QName(PackageNamespace(\"\"),\"hpMax\")"), "HP not doubled");
} else {
require(code.matches("(?s).*pushbyte 10\\s+multiply.*"), "damage multiplier missing");
require(code.contains("pushint 50000"), "damage cap missing");
require(code.indexOf("onHurt") < code.indexOf("pushint 50000"), "controllers override multiplier");
}
System.out.println("PASS " + args[1] + ": " + target + "." + method
+ ", codeBytes=" + body.getCodeBytes().length);
return;
}
}
throw new AssertionError("target script missing");
}
private static void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
private static int count(String text, String token) {
return text.split(token, -1).length - 1;
}
}
+283
View File
@@ -0,0 +1,283 @@
"""Build a source-linked inventory from the retained APK decompilation, offline."""
import csv
import json
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
NETWORK = ROOT / "analysis/as3/scripts/net/pixvi/myr/net"
PURPOSES = {
"hisAchiComplete": "领取成就奖励", "dailyCheck": "每日签到", "dailyGiftSign": "领取每日礼包/签到奖励",
"dailyGiftUpdate": "更新每日礼包状态", "dailyLoopReward": "领取每日循环奖励", "getReward": "领取 VIP 奖励",
"getWeekActivityReward": "领取周活动奖励", "queryWeekActivityInfo": "查询周活动状态",
"alchemyComplete": "领取炼金成品", "alchemyOpen": "开启炼金槽", "alchemySpeed": "加速炼金", "alchemyStart": "开始炼金",
"battleStart": "开始特殊战斗", "recordBattleResult": "记录特殊战斗结果",
"finishHuntBoss": "结算世界 BOSS 挑战", "getBossRewardByDamage": "领取 BOSS 伤害奖励",
"queryCurrentBoss": "查询当前世界 BOSS", "queryCurrentBossHp": "查询世界 BOSS 剩余生命", "startHuntBoss": "开始世界 BOSS 挑战",
"monsterEntangleLevelUp": "提升羁绊等级", "monsterMakeEntangle": "建立魔物羁绊", "monsterResetEntangleSkill": "重置羁绊技能",
"monsterSetEntangleSkill": "设置羁绊技能", "itemEquipUnfix": "卸下装备", "itemEquipUsed": "穿戴装备", "itemExchange": "兑换物品",
"addTeam": "增加探索队伍", "cancelExplore": "取消探索", "finish": "完成并领取探索奖励", "start": "派出探索队伍",
"gachaBuyTimeEgg": "购买时段扭蛋", "gachaGetEggs": "执行扭蛋抽取并返回蛋/附带奖励", "gachaTimeEgg": "执行时段扭蛋操作",
"useGiftCode": "兑换礼包码", "itemSell": "出售物品", "itemUse": "使用物品",
"mailBatchDel": "批量删除邮件", "mailGetReward": "领取邮件附件", "mailQuery": "查询邮件列表", "mailRead": "标记邮件已读",
"guideUpdate": "更新引导进度", "keepAlive": "会话心跳", "masterCheckTiAdd": "检查体力恢复",
"masterLevelUpdate": "更新角色等级状态", "masterNameUpdate": "修改角色名字", "masterQuery": "查询角色基础信息",
"masterQueryDetail": "查询角色主快照(牧场、背包、队伍、任务等)", "queryMasterSecondDetail": "查询角色补充信息",
"queryRoleAvatars": "查询可用头像", "updateMasterAvatar": "更换头像", "migrateIn": "执行角色迁入", "migrateOut": "执行角色迁出",
"createMaster": "创建区服角色", "getArchiveInfo": "读取小游戏存档", "saveInfo": "保存小游戏存档",
"gameOver": "结算小游戏", "gameStart": "开始小游戏", "getRecord": "查询小游戏记录",
"monsterExchange": "交换魔物成长属性", "monsterIntensify": "消耗素材魔物强化目标魔物", "monsterLock": "锁定/解锁魔物",
"monsterNameUpdate": "修改魔物名字", "monsterPotential": "处理魔物潜能", "monsterQualification": "重设/提升魔物资质",
"monsterSell": "派遣/出售魔物", "monsterSendGift": "给魔物赠礼", "monsterTranster2Room": "转移魔物到牧场(保留原拼写)",
"monsterUpStar": "提升魔物星级", "getPayGift": "领取充值积分礼包",
"monsterPotentialLevelUpgrade": "提升魔物潜能等级", "monsterPotentialUpgrade": "提升魔物潜能阶段",
"finishPVE": "结算 PVE 活动挑战", "getPVEWeekReward": "领取 PVE 周奖励", "queryPVEInfo": "查询 PVE 活动信息", "startPVE": "开始 PVE 活动挑战",
"finishFarmEvent": "完成牧场随机事件", "getFarmEvent": "查询牧场随机事件", "queryRank": "查询排行榜",
"roomCreateByKe": "用氪金建造牧场", "roomCreateByMoney": "用金币建造牧场", "roomUpgrade": "升级牧场",
"shopItemBuy": "购买商店物品", "shopQuery": "查询商店商品", "monsterSetSkin": "设置魔物皮肤",
"stackAddMonster": "向培育槽放入魔物蛋", "stackCheckProcess": "推进/检查培育成长阶段", "stackGrowthNumber": "增加培育槽属性加成次数",
"stackOpen": "开启培育槽", "stackSpeedUp": "加速培育", "stackTransferMonster": "从培育槽收取魔物到牧场",
"battleEnd": "提交普通关卡战斗数据并结算", "checkNextWeek": "检查循环关卡跨周更新", "getStageReward": "领取循环关卡阶段奖励",
"stageStart": "进入指定关卡和难度", "queryGameConfig": "查询游戏配置", "queryGameNotice": "查询公告",
"execute": "查询系统时间", "firstOpenGame": "上报首次启动",
"taskComplete": "完成任务并领取奖励", "taskCompleteStep": "推进任务当前步骤", "taskLoopFlush": "刷新每日循环委托",
"taskLoopReceive": "接取指定城市的循环委托", "taskReceive": "接取普通任务", "taskUpdate": "更新任务状态/解锁",
"monsterPlaceBattleTeam": "将魔物加入战斗队伍", "monsterWithdrawBattleTeam": "从战斗队伍移除魔物",
"userActive": "提交激活码", "userRegister": "客户端保留的游戏用户注册路径", "enterGame": "选择区服并进入游戏",
"loginUser": "用渠道会话登录中心并取得区服/角色列表;另有开发模式调用", "userCertification": "提交游戏侧实名信息",
"payApply": "申请支付交易号", "getPayReward": "查询/领取已支付订单奖励", "queryNoGetRewardPay": "查询未领取的支付订单",
"getChargeReward": "领取时段充值奖励", "getChargeRewardList": "查询时段充值奖励列表",
}
GROUPS = {"NetAchi": "成就", "NetActi": "签到与活动", "NetAlchemy": "炼金", "NetBattle": "特殊战斗",
"NetBoss": "世界 BOSS", "NetEntangle": "羁绊", "NetEquip": "装备", "NetExchange": "物品兑换", "NetExplore": "探索派遣",
"NetGacha": "扭蛋", "NetItem": "物品与礼包码", "NetMail": "邮件", "NetMaster": "角色、体力与迁移",
"NetMiniGame": "小游戏与存档", "NetMonster": "魔物管理", "NetPay": "支付订单", "NetPayPoint": "充值奖励",
"NetPotential": "潜能", "NetPve": "PVE 活动", "NetRandomEvent": "牧场事件", "NetRank": "排行榜",
"NetRoom": "牧场建造", "NetShop": "商店", "NetSkin": "皮肤", "NetStack": "培育室",
"NetStage": "冒险关卡与结算", "NetSystem": "配置、公告与时间", "NetTask": "任务与委托", "NetTeam": "战斗编队", "NetUser": "登录、区服与实名"}
def code_chars(text, start=0):
i = start
while i < len(text):
if text[i] in "\"'":
quote = text[i]
i += 1
while i < len(text) and text[i] != quote:
i += 2 if text[i] == "\\" else 1
elif text.startswith("//", i):
i = text.find("\n", i)
if i < 0:
return
continue
elif text.startswith("/*", i):
end = text.find("*/", i + 2)
i = len(text) if end < 0 else end + 2
continue
else:
yield i, text[i]
i += 1
def end_of(text, start):
opening, closing = text[start], {"(": ")", "{": "}", "[": "]"}[text[start]]
depth = 0
for i, char in code_chars(text, start):
if char == opening:
depth += 1
elif char == closing:
depth -= 1
if depth == 0:
return i
raise ValueError("Unbalanced source")
def split_top(text):
start, depth, result = 0, 0, []
for index, char in code_chars(text):
if char in "({[":
depth += 1
elif char in ")}]":
depth -= 1
elif char == "," and depth == 0:
result.append(text[start:index].strip())
start = index + 1
return result + [text[start:].strip()]
def functions(text, java=False):
pattern = r"public\s+void\s+(\w+)\s*\(" if java else r"\bfunction\s+(\w+)\s*\("
result = {}
for match in re.finditer(pattern, text):
end_args = end_of(text, match.end() - 1)
brace = text.index("{", end_args)
end = end_of(text, brace)
result[match[1]] = {"name": match[1], "signature": text[match.start():brace].strip(),
"body": text[brace + 1:end], "offset": brace + 1, "line": text.count("\n", 0, match.start()) + 1}
return result
def request_fields(body, name):
fields = {}
for match in re.finditer(r"\b" + re.escape(name) + r"(?:\s*:\s*\w+)?\s*=\s*\{", body):
start = match.end() - 1
for entry in split_top(body[start + 1:end_of(body, start)]):
item = re.match(r'\s*["\']?(\w+)["\']?\s*:\s*(.*)', entry, re.S)
if item:
fields.setdefault(item[1], []).append(re.sub(r"\s+", " ", item[2]).strip())
for match in re.finditer(r"\b" + re.escape(name) + r"\.(\w+)\s*=\s*([^;]+);", body):
fields.setdefault(match[1], []).append(re.sub(r"\s+", " ", match[2]).strip())
return {key: list(dict.fromkeys(values)) for key, values in fields.items()}
def game_inventory():
endpoints = {}
for path in sorted(NETWORK.glob("*.as")):
text = path.read_text(encoding="utf-8")
constants = {}
for declaration in re.finditer(r'\b(?:const|var)\s+(\w+)\s*:\s*String\s*=\s*"([A-Za-z][\w-]*/[\w/-]+)"', text):
endpoint = declaration[2]
constants[declaration[1]] = endpoint
row = endpoints.setdefault(endpoint, {"path": endpoint, "method": None, "purpose": PURPOSES[endpoint.rsplit("/", 1)[1]],
"evidence": "静态客户端路径;是否找到调用见 calls", "calls": [], "declarations": []})
row["declarations"].append({"source": path.relative_to(ROOT).as_posix(), "class": path.stem,
"constant": declaration[1], "line": text.count("\n", 0, declaration.start()) + 1})
methods = functions(text)
for function in methods.values():
body = function["body"]
for match in re.finditer(r'\.send\(', body):
start = body.index("(", match.start())
args = split_top(body[start + 1:end_of(body, start)])
endpoint = args[0][1:-1] if args[0].startswith('"') and args[0].endswith('"') else constants.get(args[0])
if not endpoint:
continue
callback = methods.get(args[2]) if len(args) > 2 else None
fields = request_fields(body[:match.start()], args[1]) if re.fullmatch(r"\w+", args[1]) else {}
mode = args[5] if len(args) > 5 else "NetCenter.SERVER_MODE_NORMAL"
mode = {"0": "NetCenter.SERVER_MODE_CENTER", "1": "NetCenter.SERVER_MODE_NORMAL", "2": "NetCenter.SERVER_MODE_PAY"}.get(mode, mode)
line = text.count("\n", 0, function["offset"] + match.start()) + 1
response_fields = sorted(set(re.findall(r"\bre\.(\w+)", callback["body"]))) if callback else []
call = {"source": path.relative_to(ROOT).as_posix(), "line": line, "class": path.stem,
"function": function["name"], "signature": function["signature"], "request_argument": args[1],
"request_fields": fields, "callback": args[2] if len(args) > 2 else None,
"callback_line": callback["line"] if callback else None, "callback_fields": response_fields,
"response_forwarded": bool(callback and re.search(r"\w+\(re\)", callback["body"])),
"server_mode": mode, "send_arguments": args}
row = endpoints.setdefault(endpoint, {"path": endpoint, "method": "POST", "purpose": PURPOSES[endpoint.rsplit("/", 1)[1]],
"evidence": "静态客户端调用;未进行官方实服调用验证", "calls": [], "declarations": []})
row["method"] = "POST"
row["evidence"] = "静态客户端 send 调用;未进行官方实服调用验证"
row["calls"].append(call)
return sorted(endpoints.values(), key=lambda row: row["path"])
def sdk_inventory():
path = ROOT / "analysis/sdk_login/com.diyidan.game.network.UserNetwork2.java"
text = path.read_text(encoding="utf-8")
purposes = {"loginByPhone": "账号密码登录", "registerByPhone": "手机号注册", "visitorUpgrade": "游客升级手机号账号",
"registerAsVisitor": "游客注册", "logout": "退出渠道会话", "loginByDydToken": "使用第一弹 Token 登录",
"loginByDydPermanentToken": "使用永久 Token 获取会话", "verifyToken": "验证 Token", "generateToken": "生成指定有效期 Token",
"forgetPassword": "短信验证后重设密码", "bindByDydToken": "通过 Token 绑定已有账号", "bindByPhone": "通过密码绑定已有账号",
"verifyId": "渠道侧实名验证"}
result = []
for function in functions(text, java=True).values():
for match in re.finditer(r"addRequestToQueue\(", function["body"]):
start = function["body"].index("(", match.start())
args = split_top(function["body"][start + 1:end_of(function["body"], start)])
fields = re.findall(r'map\.put\("([^"\n]+)"', function["body"])
result.append({"method": {"0": "GET", "1": "POST", "2": "PUT", "3": "DELETE"}.get(args[0], args[0]),
"url_expression": args[1], "function": function["name"], "purpose": purposes[function["name"]],
"request_fields": fields, "source": path.relative_to(ROOT).as_posix(),
"line": text.count("\n", 0, function["offset"] + match.start()) + 1,
"evidence": "静态 SDK 调用;返回结构需对应响应验证"})
return result
def source_link(call):
path = call["source"].removeprefix("analysis/")
return f"[{Path(path).name}:{call['line']}]({path}#L{call['line']})"
def main():
rows, sdk = game_inventory(), sdk_inventory()
baseline = {endpoint for entry in json.loads((ROOT / "analysis/endpoints.json").read_text(encoding="utf-8")) for endpoint in entry["endpoints"]}
assert baseline <= {row["path"] for row in rows}
inventory = {"artifact": "牧羊人之心_1.9.68.apk", "artifact_sha256": "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d",
"date": "2026-11-07", "game_endpoint_count": len(rows), "sdk_call_variants": len(sdk),
"paths_with_calls": sum(bool(row["calls"]) for row in rows),
"scope": "31 个 Net*.as 文件中的路径常量、字符串 send 调用及本类常量 send 调用,以及已导出的 UserNetwork2 SDK 类;不包含未导出 SDK 类、动态拼接和热更新代码",
"runtime_observations": {"user_confirmed_success": ["SDK password login", "userServerService/loginUser", "userServerService/enterGame", "masterService/masterQueryDetail"],
"other_endpoints": "仅静态代码证据;未进行官方实服操作验证"},
"game": rows, "sdk": sdk}
target = ROOT / "analysis/API_INVENTORY.json"
target.write_text(json.dumps(inventory, ensure_ascii=False, indent=2), encoding="utf-8")
route_names = {"NetCenter.SERVER_MODE_CENTER": "登录中心", "NetCenter.SERVER_MODE_NORMAL": "选中游戏服", "NetCenter.SERVER_MODE_PAY": "区服支付服"}
header = ["# 牧羊人之心客户端接口清单", "", "生成日期:2026-11-07。来源:用户提供的 1.9.68 APK 留存反编译代码。", "",
f"发现 **{len(rows)} 个游戏侧路径**,其中 **{sum(bool(row['calls']) for row in rows)} 个找到实际 send 调用**;另列 **{len(sdk)} 种渠道 SDK 调用方式**。", "主体依据客户端静态证据,用途根据调用方法、参数和回调推定。账号验证、中心登录、进入区服和角色读取已由用户实测成功;其他接口未做官方实服验证。", "",
"## 阅读方式", "", "- 表内请求字段不含统一注入的 `token`、`reqid`、`reqsid`;空字段表示包装方法没有显式业务字段。",
"- 返回字段是该方法回调直接读取的字段,不是完整响应 Schema。`回调透传` 表示把整个响应交给上层。",
"- `JSON` 文件保留每个调用位置、方法签名、参数表达式、回调字段与路由;CSV 可直接用 Excel 打开。",
"- 普通游戏接口是 POST,JSON 经 AES-ECB + PKCS7 + Base64 后作为请求体;支付调用有单独的路由/编码开关。",
"- 登录中心来自 APK 配置;进入区服后的地址来自官方返回的 `gameServerAddress`;支付地址来自 `payServerAddress`。", "",
"## 登录顺序与当前排查", "", "1. `POST https://gameapi.diyidan.net/g0.3/users/reallogin`:发送渠道账号密码,取 SDK 用户会话。",
"2. `userServerService/loginUser`:发送 SDK 用户 ID/Token、渠道和平台,客户端读取 `playerInfo`、`servers`、`masterInfos`。",
"3. 用户选择返回的区服后,`userServerService/enterGame`:发送 `serverId`、设备信息和客户端计算的 `random`。",
"4. 对选中区服调用 `masterService/masterQueryDetail`,读取角色与牧场/背包/任务等状态。", "",
"签名日期必须跟随 `Paster.timestampFormat` 的实际实现:格式串 `yyMMdd` 中的 `yy` 被替换为四位 `Date.fullYear`,因此日期是八位 `yyyyMMdd`。",
"`channel` 与 `tjChannel` 不同:这份 APK 的渠道为 `DYD`,而 `assets/tjchannel.json` 中的追踪渠道为 `taptap`。",
"辅助已修正这两处进入参数,并在调试日志的“进入参数检查”中记录日期、规则和渠道,不记录签名原文或 Token。", "",
"旧版 `AccountCenter.as` 使用 `servers[].id`;内部 `ServerVo` 保存为 `serverId`;`masterInfos[].id` 是角色编号。",
"实际登录日志返回前两条完整区服(含 `id`),后两条是 `$.servers[0]` / `$.servers[1]` 的 `$ref` 引用。",
"辅助现已还原数组引用、按区服编号去重,并按 `masterInfos[].serverId` 关联角色名;本地整理不会再发请求。",
"调试窗口已记录进入解析器之前的解密响应,文件为 `local_state/ranch_helper/network_debug.jsonl`。", "",
"## 培育室和冒险的关键组合", "", "- 看培育槽/背包:`masterQueryDetail`;刷新成长:`stackCheckProcess`;放蛋:`stackAddMonster`。",
"- 收取到牧场:`stackTransferMonster`,`datas` 内具体结构需结合调用者;派遣:`monsterSell`。",
"- 注意 `NetStack.sellMonsters` 发送 `monsterId` 数组,`NetMonster.sellMonsters` 发送 `monsterIds` 数组,不能混用包装层。",
"- 喂养升级:`monsterIntensify`,目标 `targetId`,素材数组 `foods`。",
"- 委托:`taskLoopFlush` → `taskLoopReceive` → `taskCompleteStep` → `taskComplete`。",
"- 普通冒险:`stageStart` → 客户端实际战斗 → `battleEnd`。后者提交 `battleData`,包含伤害、击杀、时间、阵容等。",
"- 本次范围未发现独立扫荡路径;战斗结算不是只发成功标志。服务端如何验证仍未知。", "", "## 游戏接口(按功能)", ""]
csv_rows = []
for cls, group in GROUPS.items():
selected = [(row, call) for row in rows for call in (row["calls"] or row["declarations"]) if call["class"] == cls]
if not selected:
continue
header += [f"### {group}({cls})", "", "| API | 用途 | 请求字段 | 回调读取字段 | 代码位置 |", "|---|---|---|---|---|"]
for row, call in selected:
if not row["calls"]:
header.append(f"| `{row['path']}` | {row['purpose']}(仅常量,未找到 send 调用) | 未确认 | 未确认 | {source_link(call)} |")
csv_rows.append([row["path"], row["purpose"] + "(仅常量,未找到 send 调用)", "未确认", "未确认", "未确认", call["constant"], f"{call['source']}:{call['line']}"])
continue
fields = ", ".join(call["request_fields"]) or ("无显式业务字段" if call["request_argument"] in ("para", "{}") else call["request_argument"])
returns = ", ".join(call["callback_fields"]) or ("回调透传" if call["response_forwarded"] else "此回调未显式读取字段")
purpose = row["purpose"]
if call["function"] == "login":
purpose = "客户端保留的开发模式登录(loginType=dev);辅助不使用此模式"
route = route_names.get(call["server_mode"], call["server_mode"])
header.append(f"| `{row['path']}` | {purpose} | `{fields}` | `{returns}` | {source_link(call)} |")
csv_rows.append([row["path"], purpose, route, fields, returns, call["function"], f"{call['source']}:{call['line']}"])
header.append("")
header += ["## 第一弹渠道 SDK(已导出的 UserNetwork2 类)", "", "SDK 方法号对应 Volley 的 GET/POST/PUT/DELETE。共享 URL 的不同方法/参数分别列出。", "绑定调用额外含混淆常量 `d.p` 对应的字段,未在本清单猜测其原名。", "",
"| 方法 | URL 表达式 | 用途 | 显式表单字段 | 代码位置 |", "|---|---|---|---|---|"]
for row in sdk:
header.append(f"| {row['method']} | `{row['url_expression']}` | {row['purpose']} | `{', '.join(row['request_fields']) or '无显式表单字段'}` | {source_link(row)} |")
header += ["", "账号密码接口的 SDK 查询参数含 `versionCode`、`buildNumber`、`appChannel`,请求头有应用身份签名与设备字段。",
"Token 校验类方法还涉及 SDK 自身的 Header/会话状态,不能把表内空表单理解为无需认证。", "",
"## 范围和待确认项", "", "- 本清单检查 31 个网络类的字符串及常量请求。此前 `endpoints.json` 的 111 路径未覆盖 `pay-server/...` 前缀,本次补入 5 条。",
"- `monsterService/monsterPotential` 只找到常量声明,未在此范围找到调用,不能视为已确认可用的 API。",
"- `NetMonster.addPotential` 实际向 `monsterTranster2Room` 发送潜能参数;清单保留该反编译事实,不改写成猜测的路径。",
"- 参数集合是静态分支的并集,不表示每次都必填。嵌套对象、服务端默认值、类型约束需要逐个联调。",
"- 同一个接口可能被多个包装方法调用;CSV/JSON 保留这些变体,因此行数可能大于唯一接口数。",
"- 未恢复服务端源代码、完整数据库结构、服务端验签/战斗校验规则。未对库存、支付等路径进行官方实服测试。",
"- 动态拼接、其他未导出渠道 SDK、热更新资源或其他版本新增 API 不在当前静态覆盖范围。", ""]
(ROOT / "analysis/API_INVENTORY.md").write_text("\n".join(header), encoding="utf-8")
with (ROOT / "analysis/API_INVENTORY.csv").open("w", encoding="utf-8-sig", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(["API", "用途", "路由", "请求字段", "回调读取字段", "调用方法", "来源"])
writer.writerows(csv_rows)
print(f"Generated {len(rows)} game paths, {sum(len(row['calls']) for row in rows)} call sites, {len(sdk)} SDK variants")
if __name__ == "__main__":
main()
+108
View File
@@ -0,0 +1,108 @@
"""Repack and sign the prepared V3 SWFs without operating any Android device."""
import hashlib
import json
import subprocess
import uuid
import zipfile
from pathlib import Path
from repack_apk import repack_members
ROOT = Path(__file__).resolve().parent.parent
ANALYSIS = ROOT / "analysis"
BUILD_TOOLS = Path(r"C:\Users\11789\AppData\Local\Android\Sdk\build-tools\36.0.0")
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def run(*args: str) -> None:
subprocess.run(list(map(str, args)), cwd=ROOT, check=True)
def build(mode_filter: str = "both", revision: str = "V3", refresh_air_cache: bool = False) -> None:
source = ROOT / "\u7267\u7f8a\u4eba\u4e4b\u5fc3_1.9.68.apk"
expected = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
if sha256(source) != expected:
raise ValueError("Original APK digest mismatch")
manifest = {"original_sha256": expected, "packages": []}
for mode, label in (("damage", "\u4f24\u5bb310\u500d"), ("stats", "\u5c5e\u60272\u500d")):
if mode_filter != "both" and mode_filter != mode:
continue
suffix = label + ("_\u7f13\u5b58\u4fee\u590d" if refresh_air_cache else "_\u8bca\u65ad") + revision
unsigned = ANALYSIS / f"{revision.lower()}_{mode}_unsigned.apk"
aligned = ANALYSIS / f"{revision.lower()}_{mode}_aligned.apk"
output = ROOT / f"\u7267\u7f8a\u4eba\u4e4b\u5fc3_1.9.68_{suffix}.apk"
replacements = {"assets/MYRMain.app": ANALYSIS / f"MYRMain_{mode}_{revision.lower()}.app", "assets/MYRDyd.swf": ANALYSIS / "MYRDyd_v3.swf"}
cache_id = None
if refresh_air_cache:
with zipfile.ZipFile(source) as archive:
original_manifest = archive.read("AndroidManifest.xml")
old_id = "978ba13e-4b54-44d5-ae53-24335a039748"
cache_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "myrzx-local-" + mode + "-" + sha256(replacements["assets/MYRMain.app"])))
candidates = [(old_id.encode(enc), cache_id.encode(enc)) for enc in ("utf-8", "utf-16le")]
matching = [(old, new) for old, new in candidates if original_manifest.count(old) == 1]
if len(matching) != 1:
raise ValueError("Expected exactly one original AIR cache UUID string")
old, new = matching[0]
patched_manifest = original_manifest.replace(old, new)
if len(patched_manifest) != len(original_manifest):
raise ValueError("Manifest patch changed string-pool layout")
manifest_path = ANALYSIS / f"{revision.lower()}_{mode}_AndroidManifest.xml"
manifest_path.write_bytes(patched_manifest)
replacements["AndroidManifest.xml"] = manifest_path
print(f"New AIR extracted-code cache ID: {cache_id}", flush=True)
print(f"Repacking {mode}", flush=True)
repack_members(source, replacements, unsigned)
run(BUILD_TOOLS / "zipalign.exe", "-f", "-p", "4", unsigned, aligned)
if refresh_air_cache:
xmltree = subprocess.check_output([str(BUILD_TOOLS / "aapt.exe"), "dump", "xmltree", str(aligned), "AndroidManifest.xml"]).decode("utf-8", errors="replace")
if cache_id not in xmltree or '"uniqueappversionid"' not in xmltree or '"MYRDyd.swf"' not in xmltree:
raise ValueError("Compiled Android manifest validation failed")
(ANALYSIS / f"{revision.lower()}_manifest_dump.txt").write_text(xmltree, encoding="utf-8")
run(BUILD_TOOLS / "apksigner.bat", "sign", "--ks", ANALYSIS / "myrzx-local-test.p12",
"--ks-key-alias", "myrzx-local", "--ks-pass", "pass:myrzx-local-test",
"--key-pass", "pass:myrzx-local-test", "--out", output, aligned)
run(BUILD_TOOLS / "zipalign.exe", "-c", "-p", "4", output)
run(BUILD_TOOLS / "apksigner.bat", "verify", "--verbose", "--print-certs", output)
with zipfile.ZipFile(output) as apk, zipfile.ZipFile(source) as original:
bad = apk.testzip()
if bad is not None:
raise ValueError(f"ZIP CRC failure: {bad}")
changed = []
for entry in original.infolist():
if entry.filename.startswith("META-INF/"):
continue
actual = apk.getinfo(entry.filename)
if (entry.CRC, entry.file_size) != (actual.CRC, actual.file_size):
changed.append(entry.filename)
if sorted(changed) != sorted(replacements):
raise ValueError(f"Unexpected changed members: {changed}")
for member, replacement in replacements.items():
if apk.read(member) != replacement.read_bytes():
raise ValueError(f"Packaged bytes mismatch: {member}")
manifest["packages"].append({"path": output.name, "mode": mode, "sha256": sha256(output),
"size": output.stat().st_size, "changed_members": changed, "air_cache_id": cache_id})
print(f"Verified {output.name}", flush=True)
# These are intermediates created by this build; retain only the signed deliverable.
unsigned.unlink()
aligned.unlink()
(ANALYSIS / f"battle_{revision.lower()}_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"{revision} build and archive/signature checks complete", flush=True)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=("both", "damage", "stats"), default="both")
parser.add_argument("--revision", choices=("V3", "V4"), default="V3")
parser.add_argument("--refresh-air-cache", action="store_true")
args = parser.parse_args()
build(args.mode, args.revision, args.refresh_air_cache)
+56
View File
@@ -0,0 +1,56 @@
"""Verify that the surgical SWF build changes only the selected ABC tags."""
import hashlib
import struct
from pathlib import Path
def tags(path: Path):
data = path.read_bytes()
if data[:3] != b"FWS" or struct.unpack_from("<I", data, 4)[0] != len(data):
raise ValueError(f"Invalid FWS header: {path}")
rect_bits = data[8] >> 3
offset = 8 + (5 + rect_bits * 4 + 7) // 8 + 4
result = []
while offset < len(data):
start = offset
header, = struct.unpack_from("<H", data, offset)
offset += 2
kind, length = header >> 6, header & 63
if length == 63:
length, = struct.unpack_from("<I", data, offset)
offset += 4
payload = data[offset:offset + length]
if len(payload) != length:
raise ValueError("Truncated SWF tag")
name = payload[4:].split(b"\0", 1)[0].decode("utf-8") if kind == 82 else None
offset += length
result.append((kind, name, start, hashlib.sha256(data[start:offset]).hexdigest()))
if kind == 0:
break
if offset != len(data):
raise ValueError("Unexpected trailing SWF data")
return result
def compare(original: Path, patched: Path, expected_positions: set[int]):
before, after = tags(original), tags(patched)
if len(before) != len(after):
raise AssertionError("SWF tag count changed")
changed = set()
for old, new in zip(before, after):
if old[:2] != new[:2]:
raise AssertionError("SWF tag identity/order changed")
if old[3] != new[3]:
changed.add(old[2])
print(f"Changed {old[1]} at original {old[2]}")
if changed != expected_positions:
raise AssertionError(f"Unexpected modified tags: {changed}")
print(f"PASS {patched.name}: only {len(changed)} intended ABC tags changed; {len(before) - len(changed)} tags identical")
if __name__ == "__main__":
root = Path(__file__).resolve().parent.parent / "analysis"
compare(root / "MYRMain.app", root / "MYRMain_damage_v3.app", {1520, 579859, 609465})
compare(root / "MYRMain.app", root / "MYRMain_stats_v3.app", {1520, 579859})
compare(root / "MYRDyd.swf", root / "MYRDyd_v3.swf", {413})
+56
View File
@@ -0,0 +1,56 @@
"""Recover factual game tables from the user-supplied APK; no network access."""
import hashlib
import json
from pathlib import Path
import sys
import zipfile
import zlib
root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(root))
from ranch_assistant.amf import Reader
apk = next(p for p in root.glob("*.apk") if p.name.endswith("_1.9.68.apk"))
tables = {}
with zipfile.ZipFile(apk) as archive:
tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"}
for name in ("monster_info", "room_info", "game_setting", "stage_info", "stage_sp", "server_info", "task_info", "gacha_machine", "potential_info", "stack_price", "room_price", "item_info"):
path = "data/table/" + name + ".json"
raw = zlib.decompress(archive.read("assets/codes/" + hashlib.md5(path.encode()).hexdigest()))
reader = Reader(raw)
value = reader.read()
if reader.pos != len(raw):
raise ValueError(f"Unconsumed table bytes: {name}")
tables[name] = value.get("datas", value)
if name == "stack_price":
tables["stack_meta"] = {"total": int(value["total"])}
print(name, len(tables[name]))
fields = {"type", "name", "star", "time_1", "time_2", "sell_money", "sell_exp", "hideLib", "npc", "atk", "def", "hp", "dex", "like"}
fields |= {p + "_grow_" + bound for p in ("atk", "def", "hp", "dex") for bound in ("min", "max")}
tables["monster_info"] = {str(k): {f: v for f, v in row.items() if f in fields} for k, row in tables["monster_info"].items()}
liked_items = {str(k) for row in tables["monster_info"].values() for k in (row.get("like") or {})}
tables["item_names"] = {str(key): row.get("name", str(key)) for key, row in tables.pop("item_info").items() if str(key) in liked_items}
# The market button uses sc_city + the selected city ID, even where the table's
# legacy city field still says 4. Exclude tavern/premium/event egg machines.
tables["markets"] = {row["id"]: {k: row.get(k) for k in ("id", "money", "ke", "max", "eggs", "freegift")} |
{"city": int(row["id"][7:]), "name": tables["game_setting"]["cityInfo"][row["id"][7:]]["name"]}
for row in tables.pop("gacha_machine") if row["id"].startswith("sc_city")}
tables["potential_info"] = {k: tables["potential_info"][k] for k in ("potentialLevelMaxAdd", "maxPotentialLevel")}
tables["stage_info"] = {r["id"]: {"id": r["id"], "name": r.get("name", ""), "city": r.get("city", 0), "closed": r.get("closed", False), "cost": r.get("cost", {}),
"level": {k: {f: v for f, v in level.items() if f in ("cost", "levelLock")} for k, level in r.get("level", {}).items()}}
for r in tables["stage_info"]}
tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike") or k.startswith("loopTask") or k.endswith("_xyz")}
task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"}
step_fields = {"statusType", "statusValue", "condition", "des", "position", "npc", "afterStory", "auto"}
tables["task_info"] = {str(k): {f: v for f, v in row.items() if f in task_fields} |
{"steps": [{f: v for f, v in step.items() if f in step_fields} for step in row.get("steps", [])]}
for k, row in tables["task_info"].items() if int(row.get("type", 0)) == 4}
output = root / "ranch_assistant" / "data"
output.mkdir(exist_ok=True)
(output / "catalog.json").write_text(json.dumps(tables, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
for table in ("monster_info", "stage_info"):
values = tables[table].items() if isinstance(tables[table], dict) else enumerate(tables[table])
for key, row in values:
if isinstance(row, dict) and "布丁" in str(row.get("name", "")):
print(table, key, {k: v for k, v in row.items() if k in ("name", "star", "time_1", "time_2", "sell_money", "sell_exp", "cost", "id", "sp")})
+28
View File
@@ -0,0 +1,28 @@
"""Use the packaged main file via an equal-length AVM2 patch of the original loader."""
import hashlib
from pathlib import Path
def patch(source: Path, output: Path) -> None:
original = source.read_bytes()
if hashlib.sha256(original).hexdigest() != "4728d0e23bdf0d6b1468e8cd39f97535e65a09bfa40044e7c73af7e1655af741":
raise ValueError("Expected the unmodified 1.9.68 MYRDyd.swf")
start = 0x28A07
before = bytes.fromhex("60 05 46 0f 00 66 2f 80 14 d5 60 05 2c 80 02 46 2b 01 85 d6")
# File.applicationDirectory.resolvePath("MYRMain.app").url -> local2.
after = bytes.fromhex("60 3d 66 43 2c 80 02 46 3f 01 66 41 85 d6 02 02 02 02 02 02")
if original[start:start + len(before)] != before or len(before) != len(after):
raise ValueError("Original instruction block mismatch")
patched = original[:start] + after + original[start + len(before):]
output.write_bytes(patched)
print(f"Loader: {len(patched)} bytes, {sum(a != b for a, b in zip(before, after))} changed bytes; all offsets retained")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
patch(args.source, args.output)
+32
View File
@@ -0,0 +1,32 @@
"""Read packaged assets through ADB; do not access private saves or change the device."""
import hashlib
import json
import subprocess
import zipfile
from pathlib import Path
root = Path(__file__).resolve().parent.parent
adb = r"C:\Program Files\adb_tools\adb.exe"
device = "3B15C400HGV00000"
prefix = [adb, "-s", device]
paths = subprocess.check_output(prefix + ["shell", "pm", "path", "air.net.pixvi.myrzx"], timeout=15).decode().strip().splitlines()
if len(paths) != 1 or not paths[0].startswith("package:"):
raise RuntimeError("Expected one installed base APK")
installed = paths[0][len("package:"):].strip()
members = {"assets/MYRDyd.swf": "device_latest_loader.swf", "assets/MYRMain.app": "device_latest_main.app"}
observed = {}
for member, filename in members.items():
result = subprocess.run(prefix + ["exec-out", "unzip", "-p", installed, member], capture_output=True, timeout=60, check=True)
data = result.stdout
if data[:3] not in (b"FWS", b"CWS", b"ZWS"):
raise RuntimeError(f"Unexpected asset format for {member}")
(root / "analysis" / filename).write_bytes(data)
observed[member] = {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}
matches = []
for apk in root.glob("*.apk"):
with zipfile.ZipFile(apk) as archive:
if all(hashlib.sha256(archive.read(member)).hexdigest() == record["sha256"] for member, record in observed.items()):
matches.append(apk.name)
report = {"installed_packaged_assets": observed, "matching_local_apks": matches}
(root / "analysis" / "device_latest_identity.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(report, ensure_ascii=False, indent=2))
+112
View File
@@ -0,0 +1,112 @@
"""Replace APK members and preserve the original ZIP metadata of all entries."""
import argparse
import os
import struct
import zipfile
import zlib
from pathlib import Path
LOCAL_HEADER = struct.Struct("<IHHHHHIIIHH")
CENTRAL_FIXED_SIZE = 46
OLD_SIGNATURES = (".SF", ".RSA", ".DSA", ".EC", "MANIFEST.MF")
def is_obsolete_signature(name: str) -> bool:
return name.startswith("META-INF/") and name.upper().endswith(OLD_SIGNATURES)
def repack(source: Path, replacement: Path, member: str, output: Path) -> None:
repack_members(source, {member: replacement}, output)
def repack_members(source: Path, replacements: dict[str, Path], output: Path) -> None:
temporary = output.with_name(output.name + ".tmp")
if temporary.exists():
raise FileExistsError(f"Temporary output already exists: {temporary}")
replacements_data = {name: path.read_bytes() for name, path in replacements.items()}
with source.open("rb") as src, zipfile.ZipFile(src) as zin, temporary.open("xb") as dst:
offsets = {}
for info in zin.infolist():
if is_obsolete_signature(info.filename):
continue
src.seek(info.header_offset)
fields = LOCAL_HEADER.unpack(src.read(LOCAL_HEADER.size))
local_size = LOCAL_HEADER.size + fields[-2] + fields[-1] + info.compress_size
src.seek(info.header_offset)
local_record = src.read(local_size)
if len(local_record) != local_size:
raise IOError(f"Truncated local record: {info.filename}")
if info.filename in replacements_data:
replacement_data = replacements_data[info.filename]
if info.flag_bits & 0x08:
raise ValueError("A streamed data descriptor is not supported here")
compressed = replacement_data
if info.compress_type == zipfile.ZIP_DEFLATED:
compressor = zlib.compressobj(6, zlib.DEFLATED, -15)
compressed = compressor.compress(replacement_data) + compressor.flush()
elif info.compress_type != zipfile.ZIP_STORED:
raise ValueError(f"Unsupported compression method: {info.compress_type}")
info.CRC = zlib.crc32(replacement_data) & 0xFFFFFFFF
info.compress_size = len(compressed)
info.file_size = len(replacement_data)
patched = bytearray(local_record)
struct.pack_into("<III", patched, 14, info.CRC, info.compress_size, info.file_size)
local_record = bytes(patched[:LOCAL_HEADER.size + fields[-2] + fields[-1]]) + compressed
offsets[info.filename] = dst.tell()
dst.write(local_record)
missing = replacements_data.keys() - offsets.keys()
if missing:
raise ValueError(f"Replacement members missing: {sorted(missing)}")
central_offset = dst.tell()
infos = {info.filename: info for info in zin.infolist()}
for info in zin.infolist():
if is_obsolete_signature(info.filename):
continue
if info.extra or info.comment:
raise ValueError("Extra fields and entry comments are not supported")
# Read the source central directory once; entry sizes and names are unchanged.
source_start = zin.start_dir
src.seek(source_start)
source_central = src.read()
pos = 0
remaining = {name for name in infos if not is_obsolete_signature(name)}
while pos < len(source_central):
if source_central[pos:pos + 4] != b"PK\x01\x02":
break
fields = struct.unpack_from("<IHHHHHHIIIHHHHHII", source_central, pos)
name_len, extra_len, comment_len = fields[10:13]
record_len = CENTRAL_FIXED_SIZE + name_len + extra_len + comment_len
name_bytes = source_central[pos + CENTRAL_FIXED_SIZE:pos + CENTRAL_FIXED_SIZE + name_len]
name = name_bytes.decode("utf-8" if fields[3] & 0x800 else "cp437")
if not is_obsolete_signature(name):
record = bytearray(source_central[pos:pos + record_len])
struct.pack_into("<I", record, 42, offsets[name])
info = infos[name]
struct.pack_into("<III", record, 16, info.CRC, info.compress_size, info.file_size)
dst.write(record)
remaining.remove(name)
pos += record_len
if remaining:
raise ValueError(f"Central directory entries missing: {sorted(remaining)}")
central_size = dst.tell() - central_offset
count = len(infos) - sum(is_obsolete_signature(name) for name in infos)
dst.write(struct.pack("<IHHHHIIH", 0x06054B50, 0, 0, count, count,
central_size, central_offset, 0))
os.replace(temporary, output)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("replacement", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--member", default="assets/MYRMain.app")
args = parser.parse_args()
repack(args.source, args.replacement, args.member, args.output)