Add MethodBody implementation for method delegation and TileRules utility for optimised tile rule matching and caching. Include patches for WorldGenChunk performance and corresponding tests.

This commit is contained in:
Overlord committed 2026-10-04 23:19:08 +02:00
1 parent e932c7401a
commit 2081235433
10 files changed
+1029 -1

No files matched your search

@@ -0,0 +1,68 @@
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.InsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.Arrays;
/** Replaces the body of a method of the target class with a call to a {@link Hook}. */
public final class MethodBody
{
private MethodBody() {}
/**
* Replaces the body of {@code method} with {@code return hook(arguments);}: the hook receives
* the method's arguments, without {@code this}, and has the method's parameter and return
* types. Fails when the method has no body, when the types differ, or when an instance
* method's old body uses {@code this}, which the hook would not receive.
*/
public static void delegate(ClassNode node, MethodNode method, Hook hook)
{
String name = "'" + node.name + "." + method.name + method.desc + "'";
Type type = Type.getMethodType(method.desc);
Type hookType = Type.getMethodType(hook.desc());
boolean isStatic = (method.access & Opcodes.ACC_STATIC) != 0;
if ((method.access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0)
throw new IllegalStateException(name + " has no body.");
if (!Arrays.equals(type.getArgumentTypes(), hookType.getArgumentTypes()) || !type.getReturnType().equals(hookType.getReturnType()))
throw new IllegalStateException(name + " and its hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' have different types.");
if (!isStatic && MethodBody.usesThis(method))
throw new IllegalStateException(name + " uses 'this', which the hook does not receive.");
// The local variable table and annotations refer to labels of the old body.
method.instructions.clear();
method.tryCatchBlocks.clear();
method.localVariables = null;
method.visibleLocalVariableAnnotations = null;
method.invisibleLocalVariableAnnotations = null;
int slot = isStatic ? 0 : 1;
for (Type argument : type.getArgumentTypes())
{
method.instructions.add(new VarInsnNode(argument.getOpcode(Opcodes.ILOAD), slot));
slot += argument.getSize();
}
method.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false));
method.instructions.add(new InsnNode(type.getReturnType().getOpcode(Opcodes.IRETURN)));
}
/** Whether the method reads or writes local variable 0, which holds {@code this}. */
private static boolean usesThis(MethodNode method)
{
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof VarInsnNode variable && variable.var == 0) return true;
}
return false;
}
}
@@ -0,0 +1,180 @@
package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
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.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.LCONST_0;
import static org.objectweb.asm.Opcodes.LRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
/** Runs methods whose bodies {@link MethodBody#delegate} replaced with calls to the hooks below. */
public class MethodBodyTest
{
private static final String TARGET = "t/Target";
private static final String HOOKS = "dev/overlord/zomboidforge/patcher/MethodBodyTest";
public static String recorded;
public static int sum(int a, int b) { return a + b; }
/** Two-slot arguments around a one-slot one, so wrong slot numbers show. */
public static long combine(long a, String b, double c) { return a * 1000 + b.length() * 100 + (long) c; }
public static void record(String value) { MethodBodyTest.recorded = value; }
/** Defines classes from nodes, with the test classes as parent so the hooks resolve. */
private static final class Definer extends ClassLoader
{
Definer() { super(MethodBodyTest.class.getClassLoader()); }
Class<?> define(ClassNode node)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
node.accept(writer);
byte[] bytes = writer.toByteArray();
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
}
}
/**
* {@code t/Target} with a constructor and one method whose body returns a constant (or uses
* {@code this} when {@code usesThis}).
*/
private static ClassNode target(int access, String name, String desc, boolean usesThis)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ((access & ACC_ABSTRACT) != 0 ? ACC_ABSTRACT : 0), MethodBodyTest.TARGET, null, "java/lang/Object", null);
MethodVisitor constructor = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructor.visitVarInsn(ALOAD, 0);
constructor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
constructor.visitInsn(RETURN);
constructor.visitMaxs(0, 0);
MethodVisitor method = node.visitMethod(access, name, desc, null, null);
if ((access & ACC_ABSTRACT) == 0)
{
if (usesThis)
{
method.visitVarInsn(ALOAD, 0);
method.visitInsn(POP);
}
switch (desc.charAt(desc.length() - 1))
{
case 'I' -> { method.visitInsn(ICONST_0); method.visitInsn(IRETURN); }
case 'J' -> { method.visitInsn(LCONST_0); method.visitInsn(LRETURN); }
default -> method.visitInsn(RETURN);
}
method.visitMaxs(0, 0);
}
return node;
}
private static MethodNode method(ClassNode node, String name)
{
return node.methods.stream().filter(method -> method.name.equals(name)).findFirst().orElseThrow();
}
private static Object run(ClassNode node, String name, Class<?>[] types, Object... arguments) throws ReflectiveOperationException
{
Class<?> loaded = new Definer().define(node);
Method method = loaded.getMethod(name, types);
Object self = (method.getModifiers() & ACC_STATIC) != 0 ? null : loaded.getConstructor().newInstance();
return method.invoke(self, arguments);
}
@Test
void staticMethodReturnsWhatTheHookReturns() throws ReflectiveOperationException
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"));
assertEquals(7, MethodBodyTest.run(node, "add", new Class<?>[] { int.class, int.class }, 3, 4));
}
@Test
void instanceMethodPassesItsArgumentsWithoutThis() throws ReflectiveOperationException
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "mix", "(JLjava/lang/String;D)J", false);
MethodBody.delegate(node, MethodBodyTest.method(node, "mix"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J"));
assertEquals(5_327L, MethodBodyTest.run(node, "mix", new Class<?>[] { long.class, String.class, double.class }, 5L, "abc", 27.9));
}
@Test
void voidMethodCallsTheHook() throws ReflectiveOperationException
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(Ljava/lang/String;)V", false);
MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "record", "(Ljava/lang/String;)V"));
MethodBodyTest.recorded = null;
assertNull(MethodBodyTest.run(node, "save", new Class<?>[] { String.class }, "saved"));
assertEquals("saved", MethodBodyTest.recorded);
}
@Test
void dropsTheLocalVariablesOfTheOldBody()
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
MethodNode method = MethodBodyTest.method(node, "add");
method.localVariables = new ArrayList<>();
MethodBody.delegate(node, method, new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"));
assertNull(method.localVariables);
}
@Test
void failsWhenTheTypesDiffer()
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "add", "(II)I", false);
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "combine", "(JLjava/lang/String;D)J"))
);
assertTrue(e.getMessage().contains("different types"), e.getMessage());
}
@Test
void failsWhenTheOldBodyUsesThis()
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC, "add", "(II)I", true);
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"))
);
assertTrue(e.getMessage().contains("uses 'this'"), e.getMessage());
}
@Test
void failsForAMethodWithoutBody()
{
ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_ABSTRACT, "add", "(II)I", false);
IllegalStateException e = assertThrows(IllegalStateException.class, () ->
MethodBody.delegate(node, MethodBodyTest.method(node, "add"), new Hook(MethodBodyTest.HOOKS, "sum", "(II)I"))
);
assertTrue(e.getMessage().contains("has no body"), e.getMessage());
}
}