diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java new file mode 100644 index 0000000..dc5395c --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookArgument.java @@ -0,0 +1,99 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; + +import java.util.List; +import java.util.Objects; + +/** + * A value of the patched method that a {@link Hook} receives as an argument. The hook's + * parameters are the types of its arguments, in order. + */ +public sealed interface HookArgument +{ + /** + * The local variable slot that holds the value at the instruction {@code at} of + * {@code method}. Fails with an {@link IllegalStateException} when the value does not + * exist there. + */ + Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at); + + /** A local variable slot and the type of the value in it. */ + record Slot(int index, Type type) + { + /** The instruction that pushes the value onto the operand stack. */ + public VarInsnNode load() { return new VarInsnNode(this.type.getOpcode(Opcodes.ILOAD), this.index); } + } + + /** + * Parameter {@code index} of the patched method, counted from 0 in the order of its + * descriptor; {@code this} of an instance method is not counted. + */ + record Parameter(int index) implements HookArgument + { + public Parameter + { + if (index < 0) throw new IllegalArgumentException("Not a parameter index: " + index); + } + + @Override + public Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at) + { + Type[] types = Type.getArgumentTypes(method.desc); + + if (this.index >= types.length) throw new IllegalStateException("'" + node.name + "." + method.name + method.desc + "' has no parameter " + this.index + "."); + + int slot = (method.access & Opcodes.ACC_STATIC) != 0 ? 0 : 1; + for (int i = 0; i < this.index; i++) slot += types[i].getSize(); + + return new Slot(slot, types[this.index]); + } + + @Override + public String toString() { return "parameter " + this.index; } + } + + /** + * The local variable {@code name} of the patched method, from its local variable table. + * Exactly one variable of that name has to be in scope at the anchor. + */ + record Local(String name) implements HookArgument + { + public Local + { + Objects.requireNonNull(name); + } + + @Override + public Slot resolve(ClassNode node, MethodNode method, AbstractInsnNode at) + { + List variables = Objects.requireNonNullElse(method.localVariables, List.of()); + int position = method.instructions.indexOf(at); + + List matches = variables.stream() + .filter(variable -> variable.name.equals(this.name)) + .filter(variable -> method.instructions.indexOf(variable.start) <= position && position < method.instructions.indexOf(variable.end)) + .toList(); + + if (matches.size() != 1) { + throw new IllegalStateException( + "Expected exactly one local variable '" + this.name + "' in scope at the anchor in '" + + node.name + "." + method.name + method.desc + "', found " + matches.size() + ); + } + + LocalVariableNode variable = matches.getFirst(); + + return new Slot(variable.index, Type.getType(variable.desc)); + } + + @Override + public String toString() { return "local '" + this.name + "'"; } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java index b033515..c8a701b 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java @@ -206,10 +206,7 @@ public final class JarPatcher ClassNode node = new ClassNode(); new ClassReader(bytes).accept(node, 0); - for (ClassPatch patch : patches) { - JarPatcher.verifyAnchor(patch, node); - patch.apply(node); - } + for (ClassPatch patch : patches) JarPatcher.apply(patch, node); HierarchyClassWriter writer = new HierarchyClassWriter(name -> JarPatcher.read(jar, name + ".class")); node.accept(writer); @@ -217,9 +214,14 @@ public final class JarPatcher return writer.toByteArray(); } - private static void verifyAnchor(ClassPatch patch, ClassNode node) + /** Verifies the anchor of {@code patch}, then applies it; failures name the patch. */ + private static void apply(ClassPatch patch, ClassNode node) { - try { patch.anchor().verify(node); } + try + { + patch.anchor().verify(node); + patch.apply(node); + } catch (IllegalStateException e) { throw new IllegalStateException("'" + patch.getClass().getSimpleName() + "': " + e.getMessage(), e); } } diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java new file mode 100644 index 0000000..1dd4858 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/CancellableHookPatch.java @@ -0,0 +1,93 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.List; +import java.util.Objects; + +/** + * Makes a call in the target class depend on a {@link Hook}: the hook runs directly before the + * call and returns {@code true} to skip it. + * + *
{@code
+ * if (!Hooks.hook(arguments)) Owner.call(...);
+ * }
+ * + * The receiver and the arguments of the call are evaluated before the hook runs; a skipped call + * pops them. The call returns {@code void}, so a skipped call leaves no value missing. The hook + * receives the {@link HookArgument}s, which are read from local variable slots. + */ +public abstract class CancellableHookPatch implements ClassPatch +{ + private final String target; + private final Anchor.Call anchor; + private final Hook hook; + private final List arguments; + + /** A hook with one parameter per element of {@code arguments}, in order, returning {@code boolean}. */ + protected CancellableHookPatch(String target, Anchor.Call anchor, Hook hook, List arguments) + { + if (!Type.getReturnType(anchor.desc()).equals(Type.VOID_TYPE)) + throw new IllegalArgumentException("Anchor call '" + anchor.owner() + "." + anchor.name() + anchor.desc() + "' must return 'V'."); + + if (anchor.name().equals("")) + throw new IllegalArgumentException("Anchor call '" + anchor.owner() + "." + anchor.name() + anchor.desc() + "' is a constructor, which cannot be skipped."); + + HookCall.checkShape(hook, arguments, Type.BOOLEAN_TYPE); + + this.target = Objects.requireNonNull(target); + this.anchor = anchor; + this.hook = hook; + this.arguments = List.copyOf(arguments); + } + + @Override + public final String target() { return this.target; } + @Override + public final Anchor.Call anchor() { return this.anchor; } + @Override + public final Hook hook() { return this.hook; } + + @Override + public final void apply(ClassNode node) + { + MethodNode method = this.anchor.in().resolve(node); + MethodInsnNode call = this.anchor.resolve(node); + InsnList code = HookCall.invoke(this.hook, this.arguments, Type.BOOLEAN_TYPE, node, method, call); + LabelNode run = new LabelNode(); + LabelNode end = new LabelNode(); + + code.add(new JumpInsnNode(Opcodes.IFEQ, run)); + code.add(CancellableHookPatch.discardOperands(call)); + code.add(new JumpInsnNode(Opcodes.GOTO, end)); + code.add(run); + + method.instructions.insertBefore(call, code); + method.instructions.insert(call, end); + } + + /** Pops the arguments of {@code call}, last first, then its receiver. */ + private static InsnList discardOperands(MethodInsnNode call) + { + InsnList code = new InsnList(); + Type[] arguments = Type.getArgumentTypes(call.desc); + + for (int i = arguments.length - 1; i >= 0; i--) code.add(new InsnNode(arguments[i].getSize() == 2 ? Opcodes.POP2 : Opcodes.POP)); + if (call.getOpcode() != Opcodes.INVOKESTATIC) code.add(new InsnNode(Opcodes.POP)); + + return code; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java new file mode 100644 index 0000000..22f845f --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java @@ -0,0 +1,63 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.List; + +/** The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. */ +final class HookCall +{ + private HookCall() {} + + /** + * Fails unless {@code hook} returns {@code returnType} and takes {@code arguments} parameters. + * The parameter types are checked by {@link #invoke}, once the arguments are resolved. + */ + static void checkShape(Hook hook, List arguments, Type returnType) + { + Type actualReturn = Type.getReturnType(hook.desc()); + Type[] parameters = Type.getArgumentTypes(hook.desc()); + + if (!actualReturn.equals(returnType)) + throw new IllegalArgumentException("Hook '" + hook + "' must return '" + returnType.getDescriptor() + "'."); + + if (parameters.length != arguments.size()) + throw new IllegalArgumentException("Hook '" + hook + "' must take " + arguments.size() + " parameter(s), one per argument " + arguments + "."); + } + + /** + * Instructions that push {@code arguments} and call {@code hook}, for insertion directly + * before or after {@code at} in {@code method}. Fails when the hook's descriptor does not + * match the types of the arguments. + */ + static InsnList invoke(Hook hook, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) + { + InsnList code = new InsnList(); + Type[] types = new Type[arguments.size()]; + + for (int i = 0; i < arguments.size(); i++) + { + HookArgument.Slot slot = arguments.get(i).resolve(node, method, at); + + types[i] = slot.type(); + code.add(slot.load()); + } + + String expected = Type.getMethodDescriptor(returnType, types); + if (!hook.desc().equals(expected)) + throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for the arguments " + arguments + "."); + + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false)); + + return code; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java index b344017..dd5210f 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookInjectionPatch.java @@ -3,34 +3,40 @@ package dev.overlord.zomboidforge.patcher.Patches; import dev.overlord.zomboidforge.patcher.Anchor; import dev.overlord.zomboidforge.patcher.ClassPatch; import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; -import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import java.util.List; import java.util.Objects; /** - * Inserts a call to a {@link Hook} directly after a call in the target class. The hook takes - * no arguments and returns nothing, so the operand stack and the stack map frames of the - * patched method stay unchanged. + * Inserts a call to a {@link Hook} directly after a call in the target class. The hook returns + * nothing and receives the {@link HookArgument}s, which are read from local variable slots, so + * the operand stack after the inserted code is the same as before it. */ public abstract class HookInjectionPatch implements ClassPatch { - private static final String HOOK_DESC = "()V"; + private final String target; + private final Anchor.Call anchor; + private final Hook hook; + private final List arguments; - private final String target; - private final Anchor.Call anchor; - private final Hook hook; + /** A hook without arguments, {@code ()V}. */ + protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook) { this(target, anchor, hook, List.of()); } - protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook) + /** A hook with one parameter per element of {@code arguments}, in order, returning {@code void}. */ + protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook, List arguments) { - if (!hook.desc().equals(HookInjectionPatch.HOOK_DESC)) - throw new IllegalArgumentException("Hook '" + hook + "' must have descriptor '" + HookInjectionPatch.HOOK_DESC + "'."); + HookCall.checkShape(hook, arguments, Type.VOID_TYPE); - this.target = Objects.requireNonNull(target); - this.anchor = Objects.requireNonNull(anchor); - this.hook = hook; + this.target = Objects.requireNonNull(target); + this.anchor = Objects.requireNonNull(anchor); + this.hook = hook; + this.arguments = List.copyOf(arguments); } @Override @@ -43,16 +49,9 @@ public abstract class HookInjectionPatch implements ClassPatch @Override public final void apply(ClassNode node) { - MethodInsnNode call = this.anchor.resolve(node); + MethodNode method = this.anchor.in().resolve(node); + MethodInsnNode call = this.anchor.resolve(node); - this.anchor.in().resolve(node).instructions.insert( - call, new MethodInsnNode( - Opcodes.INVOKESTATIC, - this.hook.owner(), - this.hook.name(), - this.hook.desc(), - false - ) - ); + method.instructions.insert(call, HookCall.invoke(this.hook, this.arguments, Type.VOID_TYPE, node, method, call)); } } diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java new file mode 100644 index 0000000..43065db --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/CancellableHookPatchTest.java @@ -0,0 +1,196 @@ +package dev.overlord.zomboidforge.patcher; + +import dev.overlord.zomboidforge.patcher.Patches.CancellableHookPatch; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; + +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.LLOAD; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class CancellableHookPatchTest +{ + private static final String CALLS = Type.getInternalName(CancellableHookPatchTest.Calls.class); + private static final String CALLS_DESC = Type.getDescriptor(CancellableHookPatchTest.Calls.class); + + @TempDir + Path dir; + + /** Stands in for the anchor calls and the hooks, and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + /** What the hooks return. */ + public static boolean cancel; + + public static void staticCall(long number, String text) { Calls.LOG.add("call " + number + " " + text); } + + public void virtualCall(String text) { Calls.LOG.add("virtual " + text); } + + public static void after() { Calls.LOG.add("after"); } + + public static boolean staticHook(String text, long number) + { + Calls.LOG.add("hook " + text + " " + number); + + return Calls.cancel; + } + + public static boolean virtualHook(String text) + { + Calls.LOG.add("virtual hook " + text); + + return Calls.cancel; + } + } + + /** Skips {@code Calls.staticCall(number, text)} in {@code runStatic}; the hook gets {@code text} and {@code number}. */ + private static final class StaticCallPatch extends CancellableHookPatch + { + StaticCallPatch() { + super( + "t/Target", + new Anchor.Call(new Anchor.Method("runStatic", "(JLjava/lang/String;)V"), CancellableHookPatchTest.CALLS, "staticCall", "(JLjava/lang/String;)V"), + new Hook(CancellableHookPatchTest.CALLS, "staticHook", "(Ljava/lang/String;J)Z"), + List.of(new HookArgument.Parameter(1), new HookArgument.Parameter(0)) + ); + } + } + + /** Skips {@code calls.virtualCall(text)} in {@code runVirtual}; the hook gets {@code text}. */ + private static final class VirtualCallPatch extends CancellableHookPatch + { + VirtualCallPatch() { + super( + "t/Target", + new Anchor.Call(new Anchor.Method("runVirtual", "(" + CancellableHookPatchTest.CALLS_DESC + "Ljava/lang/String;)V"), CancellableHookPatchTest.CALLS, "virtualCall", "(Ljava/lang/String;)V"), + new Hook(CancellableHookPatchTest.CALLS, "virtualHook", "(Ljava/lang/String;)Z"), + List.of(new HookArgument.Parameter(1)) + ); + } + } + + /** + * {@code static runStatic(long number, String text)}: {@code Calls.staticCall(number, text); Calls.after();} + * and {@code static runVirtual(Calls calls, String text)}: {@code calls.virtualCall(text); Calls.after();}. + */ + private static byte[] target() + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + MethodVisitor runStatic = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "runStatic", "(JLjava/lang/String;)V", null, null); + runStatic.visitVarInsn(LLOAD, 0); + runStatic.visitVarInsn(ALOAD, 2); + runStatic.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "staticCall", "(JLjava/lang/String;)V", false); + runStatic.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "after", "()V", false); + runStatic.visitInsn(RETURN); + runStatic.visitMaxs(0, 0); + + MethodVisitor runVirtual = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "runVirtual", "(" + CancellableHookPatchTest.CALLS_DESC + "Ljava/lang/String;)V", null, null); + runVirtual.visitVarInsn(ALOAD, 0); + runVirtual.visitVarInsn(ALOAD, 1); + runVirtual.visitMethodInsn(INVOKEVIRTUAL, CancellableHookPatchTest.CALLS, "virtualCall", "(Ljava/lang/String;)V", false); + runVirtual.visitMethodInsn(INVOKESTATIC, CancellableHookPatchTest.CALLS, "after", "()V", false); + runVirtual.visitInsn(RETURN); + runVirtual.visitMaxs(0, 0); + + cw.visitEnd(); + return cw.toByteArray(); + } + + /** Patches {@link #target()} with both patches and runs {@code runStatic(7, "a")} and {@code runVirtual(new Calls(), "b")}. */ + private List runPatched(boolean cancel) throws Exception + { + Path in = this.dir.resolve("in.jar"); + Path out = this.dir.resolve("patched.jar"); + + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(in))) + { + zip.putNextEntry(new ZipEntry("t/Target.class")); + zip.write(CancellableHookPatchTest.target()); + zip.closeEntry(); + } + + assertEquals(1, new JarPatcher(List.of(new StaticCallPatch(), new VirtualCallPatch())).patch(in, out)); + + CancellableHookPatchTest.Calls.cancel = cancel; + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, CancellableHookPatchTest.class.getClassLoader())) + { + Class target = loader.loadClass("t.Target"); + + target.getMethod("runStatic", long.class, String.class).invoke(null, 7L, "a"); + target.getMethod("runVirtual", CancellableHookPatchTest.Calls.class, String.class).invoke(null, new CancellableHookPatchTest.Calls(), "b"); + } + + return CancellableHookPatchTest.Calls.LOG; + } + + @BeforeEach + void clearLog() { CancellableHookPatchTest.Calls.LOG.clear(); } + + @Test + void runsTheCallWhenTheHookReturnsFalse() throws Exception + { + assertEquals( + List.of("hook a 7", "call 7 a", "after", "virtual hook b", "virtual b", "after"), + this.runPatched(false) + ); + } + + @Test + void skipsTheCallWhenTheHookReturnsTrue() throws Exception + { + assertEquals( + List.of("hook a 7", "after", "virtual hook b", "after"), + this.runPatched(true) + ); + } + + @Test + void rejectsAnchorCallThatReturnsAValue() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "value", "()I"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()Z"), List.of()) {}); + } + + @Test + void rejectsConstructorAnchor() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "", "()V"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()Z"), List.of()) {}); + } + + @Test + void rejectsHookThatDoesNotReturnBoolean() + { + Anchor.Call anchor = new Anchor.Call(new Anchor.Method("run", "()V"), "t/Dep", "call", "()V"); + + assertThrows(IllegalArgumentException.class, () -> new CancellableHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {}); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java new file mode 100644 index 0000000..3ef308d --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookArgumentTest.java @@ -0,0 +1,117 @@ +package dev.overlord.zomboidforge.patcher; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LocalVariableNode; +import org.objectweb.asm.tree.MethodNode; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ASM9; +import static org.objectweb.asm.Opcodes.LLOAD; +import static org.objectweb.asm.Opcodes.NOP; +import static org.objectweb.asm.Opcodes.RETURN; + +class HookArgumentTest +{ + private static final String STRING = "Ljava/lang/String;"; + + private static ClassNode target() + { + ClassNode node = new ClassNode(); + node.name = "t/Target"; + + return node; + } + + @Test + void parameterSlotsSkipThisAndCountWideTypesTwice() + { + MethodNode staticMethod = new MethodNode(ASM9, ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null); + MethodNode instanceMethod = new MethodNode(ASM9, ACC_PUBLIC, "run", "(JLjava/lang/String;)V", null, null); + ClassNode node = HookArgumentTest.target(); + + assertEquals(new HookArgument.Slot(0, Type.LONG_TYPE), new HookArgument.Parameter(0).resolve(node, staticMethod, new InsnNode(RETURN))); + assertEquals(new HookArgument.Slot(2, Type.getType(HookArgumentTest.STRING)), new HookArgument.Parameter(1).resolve(node, staticMethod, new InsnNode(RETURN))); + assertEquals(new HookArgument.Slot(3, Type.getType(HookArgumentTest.STRING)), new HookArgument.Parameter(1).resolve(node, instanceMethod, new InsnNode(RETURN))); + } + + @Test + void slotLoadsWithTheOpcodeOfItsType() + { + assertEquals(LLOAD, new HookArgument.Slot(0, Type.LONG_TYPE).load().getOpcode()); + assertEquals(ALOAD, new HookArgument.Slot(2, Type.getType(HookArgumentTest.STRING)).load().getOpcode()); + } + + @Test + void reportsMissingParameter() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "(I)V", null, null); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new HookArgument.Parameter(1).resolve(HookArgumentTest.target(), method, new InsnNode(RETURN)) + ); + + assertEquals("'t/Target.run(I)V' has no parameter 1.", e.getMessage()); + } + + @Test + void rejectsNegativeParameterIndex() + { + assertThrows(IllegalArgumentException.class, () -> new HookArgument.Parameter(-1)); + } + + /** {@code run()}: {@code nop} (before), label, {@code nop} (inside), label, {@code return}; {@code name} is in scope only inside. */ + @Test + void localResolvesOnlyWhereItIsInScope() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "()V", null, null); + InsnNode before = new InsnNode(NOP); + InsnNode inside = new InsnNode(NOP); + LabelNode start = new LabelNode(); + LabelNode end = new LabelNode(); + + method.instructions.add(before); + method.instructions.add(start); + method.instructions.add(inside); + method.instructions.add(end); + method.instructions.add(new InsnNode(RETURN)); + method.localVariables.add(new LocalVariableNode("name", HookArgumentTest.STRING, null, start, end, 4)); + + HookArgument.Local name = new HookArgument.Local("name"); + + assertEquals(new HookArgument.Slot(4, Type.getType(HookArgumentTest.STRING)), name.resolve(HookArgumentTest.target(), method, inside)); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> name.resolve(HookArgumentTest.target(), method, before)); + assertEquals("Expected exactly one local variable 'name' in scope at the anchor in 't/Target.run()V', found 0", e.getMessage()); + } + + @Test + void localRejectsTwoVariablesOfTheSameNameInScope() + { + MethodNode method = new MethodNode(ASM9, ACC_STATIC, "run", "()V", null, null); + InsnNode inside = new InsnNode(NOP); + LabelNode start = new LabelNode(); + LabelNode end = new LabelNode(); + + method.instructions.add(start); + method.instructions.add(inside); + method.instructions.add(end); + method.localVariables.add(new LocalVariableNode("name", HookArgumentTest.STRING, null, start, end, 0)); + method.localVariables.add(new LocalVariableNode("name", "I", null, start, end, 1)); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new HookArgument.Local("name").resolve(HookArgumentTest.target(), method, inside) + ); + + assertEquals("Expected exactly one local variable 'name' in scope at the anchor in 't/Target.run()V', found 2", e.getMessage()); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java index e17c6cd..8c97a4f 100644 --- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java @@ -2,15 +2,19 @@ package dev.overlord.zomboidforge.patcher; import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; @@ -20,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ASTORE; import static org.objectweb.asm.Opcodes.DUP; import static org.objectweb.asm.Opcodes.GETSTATIC; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; @@ -171,4 +176,105 @@ class HookInjectionPatchTest "t/Target", HookInjectionPatchTest.ANCHOR, new Hook("t/Hooks", "hook", "(I)V") ) {}); } + + @Test + void rejectsHookThatReturnsAValue() + { + assertThrows(IllegalArgumentException.class, () -> new HookInjectionPatch( + "t/Target", HookInjectionPatchTest.ANCHOR, new Hook("t/Hooks", "hook", "()Z") + ) {}); + } + + // Hooks with arguments + + private static final String CALLS = Type.getInternalName(HookInjectionPatchTest.Calls.class); + + private static final Anchor.Call ARGUMENTS_ANCHOR = new Anchor.Call( + new Anchor.Method("run", "(JLjava/lang/String;)V"), HookInjectionPatchTest.CALLS, "anchor", "()V" + ); + + private static final List ARGUMENTS = List.of( + new HookArgument.Parameter(1), + new HookArgument.Parameter(0), + new HookArgument.Local("word") + ); + + /** Stands in for the anchor call and the hook of {@link ArgumentPatch} and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + private Calls() {} + + public static void anchor() { Calls.LOG.add("anchor"); } + + public static void hook(String text, long number, String word) { Calls.LOG.add("hook " + text + " " + number + " " + word); } + } + + private static final class ArgumentPatch extends HookInjectionPatch + { + ArgumentPatch(String hookDesc) { + super("t/Target", HookInjectionPatchTest.ARGUMENTS_ANCHOR, new Hook(HookInjectionPatchTest.CALLS, "hook", hookDesc), HookInjectionPatchTest.ARGUMENTS); + } + } + + /** {@code static run(long number, String text)}: {@code String word = "local"; Calls.anchor();}. */ + private static byte[] argumentsTarget() + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + Label start = new Label(); + Label end = new Label(); + + MethodVisitor run = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null); + run.visitLdcInsn("local"); + run.visitVarInsn(ASTORE, 3); + run.visitLabel(start); + run.visitMethodInsn(INVOKESTATIC, HookInjectionPatchTest.CALLS, "anchor", "()V", false); + run.visitInsn(RETURN); + run.visitLabel(end); + run.visitLocalVariable("word", "Ljava/lang/String;", null, start, end, 3); + run.visitMaxs(0, 0); + + cw.visitEnd(); + return cw.toByteArray(); + } + + @BeforeEach + void clearLog() { HookInjectionPatchTest.Calls.LOG.clear(); } + + @Test + void passesParametersAndLocalsToHook() throws Exception + { + Path in = this.jar(Map.of("t/Target.class", HookInjectionPatchTest.argumentsTarget())); + Path out = this.dir.resolve("patched.jar"); + + new JarPatcher(List.of(new ArgumentPatch("(Ljava/lang/String;JLjava/lang/String;)V"))).patch(in, out); + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, HookInjectionPatchTest.class.getClassLoader())) + { + loader.loadClass("t.Target").getMethod("run", long.class, String.class).invoke(null, 7L, "text"); + } + + assertEquals(List.of("anchor", "hook text 7 local"), HookInjectionPatchTest.Calls.LOG); + } + + @Test + void reportsHookWhoseParametersDoNotMatchTheArguments() throws Exception + { + Path in = this.jar(Map.of("t/Target.class", HookInjectionPatchTest.argumentsTarget())); + ArgumentPatch patch = new ArgumentPatch("(Ljava/lang/String;ILjava/lang/String;)V"); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new JarPatcher(List.of(patch)).patch(in, this.dir.resolve("out.jar")) + ); + + assertEquals( + "'ArgumentPatch': Hook '" + patch.hook() + "' must have descriptor '(Ljava/lang/String;JLjava/lang/String;)V'" + + " for the arguments [parameter 1, parameter 0, local 'word'].", + e.getMessage() + ); + } }