249 lines
14 KiB
Java
249 lines
14 KiB
Java
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());
|
|
}
|
|
}
|