Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation.

This commit is contained in:
Overlord committed 2026-10-03 11:27:06 +02:00
1 parent 22077514fe
commit af7174e128
26 files changed
+1117 -30

No files matched your search

@@ -11,18 +11,27 @@ import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
/** The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. */
/**
* The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. A
* hook may also take values that are already on the operand stack where it is called; those
* come first in its parameter list, followed by one parameter per argument.
*/
final class HookCall
{
private HookCall() {}
/** {@link #checkShape(Hook, List, List, Type)} without values on the stack. */
static void checkShape(Hook hook, List<HookArgument> arguments, Type returnType) { HookCall.checkShape(hook, List.of(), arguments, returnType); }
/**
* 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.
* Fails unless {@code hook} returns {@code returnType}, takes the types {@code onStack} first,
* and then one parameter per argument. The types of those parameters are checked by
* {@link #invoke}, once the arguments are resolved.
*/
static void checkShape(Hook hook, List<HookArgument> arguments, Type returnType)
static void checkShape(Hook hook, List<Type> onStack, List<HookArgument> arguments, Type returnType)
{
Type actualReturn = Type.getReturnType(hook.desc());
Type[] parameters = Type.getArgumentTypes(hook.desc());
@@ -30,34 +39,55 @@ final class HookCall
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 + ".");
if (parameters.length != onStack.size() + arguments.size())
throw new IllegalArgumentException("Hook '" + hook + "' must take " + (onStack.size() + arguments.size()) + " parameter(s): " + HookCall.describe(onStack, arguments) + ".");
for (int i = 0; i < onStack.size(); i++)
{
if (!parameters[i].equals(onStack.get(i)))
throw new IllegalArgumentException("Parameter " + i + " of hook '" + hook + "' must be '" + onStack.get(i).getDescriptor() + "'.");
}
}
/** {@link #invoke(Hook, List, List, Type, ClassNode, MethodNode, AbstractInsnNode)} without values on the stack. */
static InsnList invoke(Hook hook, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
{
return HookCall.invoke(hook, List.of(), arguments, returnType, node, method, at);
}
/**
* 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.
* before or after {@code at} in {@code method}, where the values of the types {@code onStack}
* are on top of the operand stack. Fails when the hook's descriptor does not match.
*/
static InsnList invoke(Hook hook, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
static InsnList invoke(Hook hook, List<Type> onStack, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
{
InsnList code = new InsnList();
Type[] types = new Type[arguments.size()];
InsnList code = new InsnList();
List<Type> types = new ArrayList<>(onStack);
for (int i = 0; i < arguments.size(); i++)
for (HookArgument argument : arguments)
{
HookArgument.Slot slot = arguments.get(i).resolve(node, method, at);
HookArgument.Slot slot = argument.resolve(node, method, at);
types[i] = slot.type();
types.add(slot.type());
code.add(slot.load());
}
String expected = Type.getMethodDescriptor(returnType, types);
String expected = Type.getMethodDescriptor(returnType, types.toArray(Type[]::new));
if (!hook.desc().equals(expected))
throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for the arguments " + arguments + ".");
throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for " + HookCall.describe(onStack, arguments) + ".");
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false));
return code;
}
/** E.g. {@code the arguments [parameter 0]} or {@code the stack value(s) [Ljava/lang/Class;] and the arguments [parameter 0]}. */
private static String describe(List<Type> onStack, List<HookArgument> arguments)
{
String argumentsText = "the arguments " + arguments;
if (onStack.isEmpty()) return argumentsText;
return "the stack value(s) " + onStack.stream().map(Type::getDescriptor).toList() + " and " + argumentsText;
}
}
@@ -0,0 +1,75 @@
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.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.Printer;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* Passes the value that one return instruction of a method is about to return to a
* {@link Hook}, which returns the value to return instead:
*
* <pre>{@code
* return Hooks.hook(value, arguments);
* }</pre>
*
* The anchor is a {@link Anchor.Sequence} whose last instruction is that return instruction;
* the instructions before it identify which return of the method is meant. The hook's first
* parameter and its return type are the method's return type, followed by one parameter per
* {@link HookArgument}. Other returns of the method are unchanged.
*/
public abstract class ReturnHookPatch implements ClassPatch
{
private final String target;
private final Anchor.Sequence anchor;
private final Hook hook;
private final List<HookArgument> arguments;
private final Type returned;
protected ReturnHookPatch(String target, Anchor.Sequence anchor, Hook hook, List<HookArgument> arguments)
{
Type returned = Type.getReturnType(anchor.in().desc());
if (returned.equals(Type.VOID_TYPE))
throw new IllegalArgumentException("Method '" + anchor.in().name() + anchor.in().desc() + "' returns no value.");
HookCall.checkShape(hook, List.of(returned), arguments, returned);
this.target = Objects.requireNonNull(target);
this.anchor = anchor;
this.hook = hook;
this.arguments = List.copyOf(arguments);
this.returned = returned;
}
@Override
public final String target() { return this.target; }
@Override
public final Anchor.Sequence 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);
AbstractInsnNode instruction = this.anchor.resolve(node).getLast();
int returnOpcode = this.returned.getOpcode(Opcodes.IRETURN);
if (instruction.getOpcode() != returnOpcode)
throw new IllegalStateException("The last instruction of the anchor must be '" + Printer.OPCODES[returnOpcode].toLowerCase(Locale.ROOT) + "'.");
method.instructions.insertBefore(instruction, HookCall.invoke(this.hook, List.of(this.returned), this.arguments, this.returned, node, method, instruction));
}
}
@@ -0,0 +1,185 @@
package dev.overlord.zomboidforge.patcher;
import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch;
import org.jetbrains.annotations.Nullable;
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.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.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.LRETURN;
import static org.objectweb.asm.Opcodes.V25;
class ReturnHookPatchTest
{
private static final String CALLS = Type.getInternalName(ReturnHookPatchTest.Calls.class);
private static final Anchor.Method PICK = new Anchor.Method("pick", "(Ljava/lang/String;Z)Ljava/lang/String;");
private static final Anchor.Method WIDE = new Anchor.Method("wide", "()J");
@TempDir
Path dir;
/** The hooks. */
public static final class Calls
{
private Calls() {}
public static String replaceNull(@Nullable String value, String input) { return "hook " + value + " " + input; }
public static long doubled(long value) { return value * 2; }
}
/** Replaces the {@code null} that {@code pick} returns; the hook gets {@code input}. */
private static final class NullPatch extends ReturnHookPatch
{
NullPatch() {
super(
"t/Target",
new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL), new Anchor.Instruction.Opcode(ARETURN)),
new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
List.of(new HookArgument.Parameter(0))
);
}
}
/** Doubles the {@code long} that {@code wide} returns. */
private static final class WidePatch extends ReturnHookPatch
{
WidePatch() {
super(
"t/Target",
new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Constant(5L), new Anchor.Instruction.Opcode(LRETURN)),
new Hook(ReturnHookPatchTest.CALLS, "doubled", "(J)J"),
List.of()
);
}
}
/** Anchored on {@code aconst_null} alone, not on a return instruction. */
private static final class NoReturnPatch extends ReturnHookPatch
{
NoReturnPatch() {
super(
"t/Target",
new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL)),
new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"),
List.of(new HookArgument.Parameter(0))
);
}
}
/**
* {@code static pick(String input, boolean keep)}: {@code return keep ? input : null;} and
* {@code static wide()}: {@code return 5L;}.
*/
private Path target() throws Exception
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null);
Label returnNull = new Label();
MethodVisitor pick = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "pick", ReturnHookPatchTest.PICK.desc(), null, null);
pick.visitVarInsn(ILOAD, 1);
pick.visitJumpInsn(IFEQ, returnNull);
pick.visitVarInsn(ALOAD, 0);
pick.visitInsn(ARETURN);
pick.visitLabel(returnNull);
pick.visitInsn(ACONST_NULL);
pick.visitInsn(ARETURN);
pick.visitMaxs(0, 0);
MethodVisitor wide = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "wide", ReturnHookPatchTest.WIDE.desc(), null, null);
wide.visitLdcInsn(5L);
wide.visitInsn(LRETURN);
wide.visitMaxs(0, 0);
cw.visitEnd();
Path jar = this.dir.resolve("in.jar");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar)))
{
zip.putNextEntry(new ZipEntry("t/Target.class"));
zip.write(cw.toByteArray());
zip.closeEntry();
}
return jar;
}
@Test
void replacesTheAnchoredReturnValueOnly() throws Exception
{
Path out = this.dir.resolve("patched.jar");
new JarPatcher(List.of(new NullPatch(), new WidePatch())).patch(this.target(), out);
try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, ReturnHookPatchTest.class.getClassLoader()))
{
Class<?> target = loader.loadClass("t.Target");
assertEquals("kept", target.getMethod("pick", String.class, boolean.class).invoke(null, "kept", true));
assertEquals("hook null input", target.getMethod("pick", String.class, boolean.class).invoke(null, "input", false));
assertEquals(10L, target.getMethod("wide").invoke(null));
}
}
@Test
void reportsAnchorThatDoesNotEndInAReturn() throws Exception
{
Path in = this.target();
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(new NoReturnPatch())).patch(in, this.dir.resolve("out.jar"))
);
assertEquals("'NoReturnPatch': The last instruction of the anchor must be 'areturn'.", e.getMessage());
}
@Test
void rejectsMethodWithoutReturnValue()
{
Anchor.Sequence anchor = new Anchor.Sequence(new Anchor.Method("run", "()V"), new Anchor.Instruction.Opcode(ARETURN));
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {});
}
@Test
void rejectsHookWhoseFirstParameterIsNotTheReturnType()
{
Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN));
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(I)J"), List.of()) {});
}
@Test
void rejectsHookThatReturnsAnotherType()
{
Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN));
assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(J)I"), List.of()) {});
}
}