Merge branch 'release/v0.2.0'
ci / image (42.21, public) (push) Successful in 18s

This commit is contained in:
Overlord committed 2026-10-02 08:25:57 +02:00
commit 1b4e153898
15 files changed
+1055 -32

No files matched your search

+3 -3
View File
@@ -21,7 +21,7 @@
ARG PZ_BRANCH=public
ARG PZ_VERSION=""
ARG STEAMCLIENT=bundled
ARG FORGE_VERSION=""
ARG FORGE_VERSION="0.0.0-prerelease"
ARG STEAM_BUILDID=""
# --- Stage 1: vanilla dedicated server -----------------------------------------
@@ -53,8 +53,8 @@ COPY agent agent
COPY patcher patcher
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
# An empty PZ_VERSION keeps pz.version from gradle.properties; an empty FORGE_VERSION gives
# the build the fallback version 0.0.0-prerelease (the image has no git history).
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
# value (default 0.0.0-prerelease): this stage has no git, so the version cannot come from a tag.
ARG PZ_VERSION
ARG FORGE_VERSION
ARG DISABLED_PATCHES=""
+2
View File
@@ -19,6 +19,8 @@ podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable),
`<forge>-pz<pz>`, and `latest`.
@@ -1,7 +1,9 @@
package dev.overlord.zomboidforge.compat.b42;
import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch;
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
@@ -16,7 +18,9 @@ public final class B42PatchSet implements PatchSet
private static final List<ClassPatch> PATCHES = List.of(
new ServerStartedPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch()
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch()
);
@Override
@@ -0,0 +1,172 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
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.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
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 org.objectweb.asm.tree.VarInsnNode;
import java.util.Arrays;
import java.util.List;
/**
* Stores the {@code StateMachineComponent} of an {@code IsoGameCharacter} in a field, so that
* {@code getStateMachineComponent()} does not look it up in the entity's component map on every
* call. The lookup walks the class hierarchy of the component class and reads a {@code HashMap}.
*
* <p>The method is {@code final} and its whole body is the lookup. Every access to the component
* goes through it: the 12 call sites in {@code IsoGameCharacter}, among them
* {@code getStateMachine()}, {@code getActionContext()} and {@code getAdvancedAnimator()}, which
* zombies, players and animals call every frame.
* The patched method returns the stored component only while the component's owner is this
* character. {@code ECSEntity.setECSComponent} and {@code removeECSComponent} set the owner of a
* replaced or removed component to {@code null}, and adding the component to another entity
* changes its owner. In every other case the original lookup runs (and throws when the component
* is missing, as before), and its result is stored.
*/
public final class IsoGameCharacterStateMachinePerformancePatch extends PerformancePatch
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String FIELD_NAME = "zomboidForge$stateMachineComponent";
private static final String FIELD_DESC = "L" + IsoGameCharacterStateMachinePerformancePatch.COMPONENT + ";";
private static final Anchor.Method GETTER = new Anchor.Method("getStateMachineComponent", "()" + IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC);
/** {@code return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);} */
private static final Anchor.Sequence LOOKUP = new Anchor.Sequence(
IsoGameCharacterStateMachinePerformancePatch.GETTER,
new Anchor.Instruction.Opcode(Opcodes.ALOAD),
new Anchor.Instruction.Constant(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatch.COMPONENT)),
new Anchor.Instruction.Invoke(
IsoGameCharacterStateMachinePerformancePatch.CHARACTER, "getECSComponent",
"(Ljava/lang/Class;)L" + IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT + ";"
),
new Anchor.Instruction.Opcode(Opcodes.CHECKCAST),
new Anchor.Instruction.Opcode(Opcodes.ARETURN)
);
public IsoGameCharacterStateMachinePerformancePatch() {
super(IsoGameCharacterStateMachinePerformancePatch.CHARACTER, IsoGameCharacterStateMachinePerformancePatch.LOOKUP, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
IsoGameCharacterStateMachinePerformancePatch.requireNoFieldNamed(node);
MethodNode method = IsoGameCharacterStateMachinePerformancePatch.GETTER.resolve(node);
List<AbstractInsnNode> lookup = IsoGameCharacterStateMachinePerformancePatch.LOOKUP.resolve(node);
long instructions = Arrays.stream(method.instructions.toArray())
.filter(instruction -> instruction.getOpcode() != -1)
.count();
if (instructions != lookup.size())
throw new IllegalStateException("'" + node.name + ".getStateMachineComponent' does more than the component lookup.");
node.fields.add(new FieldNode(
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC,
null, null
));
method.instructions.insertBefore(lookup.getLast(), IsoGameCharacterStateMachinePerformancePatch.store());
// The body is only the lookup, so the first slot after 'this' and the arguments is free.
int stored = Type.getArgumentsAndReturnSizes(method.desc) >> 2;
method.instructions.insert(IsoGameCharacterStateMachinePerformancePatch.returnStored(stored));
}
/** The patch must not collide with a field of the game class, e.g. after an update. */
private static void requireNoFieldNamed(ClassNode node)
{
boolean exists = node.fields.stream()
.anyMatch(field -> field.name.equals(IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME));
if (exists) throw new IllegalStateException("'" + node.name + "' already has a field named '" + IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME + "'.");
}
/**
* Placed at the start of the method:
*
* <pre>{@code
* StateMachineComponent stored = this.zomboidForge$stateMachineComponent;
* if (stored != null && stored.getECSOwnerEntity() == this) return stored;
* }</pre>
*/
private static InsnList returnStored(int stored)
{
LabelNode lookup = new LabelNode();
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.GETFIELD));
code.add(new VarInsnNode(Opcodes.ASTORE, stored));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new JumpInsnNode(Opcodes.IFNULL, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
IsoGameCharacterStateMachinePerformancePatch.ECS_COMPONENT,
"getECSOwnerEntity",
"()Lzombie/characters/ecs/ECSEntity;",
false
));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new JumpInsnNode(Opcodes.IF_ACMPNE, lookup));
code.add(new VarInsnNode(Opcodes.ALOAD, stored));
code.add(new InsnNode(Opcodes.ARETURN));
code.add(lookup);
return code;
}
/**
* Placed before the {@code areturn} of the lookup, with the component on the operand stack:
* {@code this.zomboidForge$stateMachineComponent = component}, leaving the component on the stack.
*/
private static InsnList store()
{
InsnList code = new InsnList();
code.add(new InsnNode(Opcodes.DUP));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new InsnNode(Opcodes.SWAP));
code.add(IsoGameCharacterStateMachinePerformancePatch.field(Opcodes.PUTFIELD));
return code;
}
private static FieldInsnNode field(int opcode)
{
return new FieldInsnNode(
opcode,
IsoGameCharacterStateMachinePerformancePatch.CHARACTER,
IsoGameCharacterStateMachinePerformancePatch.FIELD_NAME,
IsoGameCharacterStateMachinePerformancePatch.FIELD_DESC
);
}
}
@@ -0,0 +1,126 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
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.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
/**
* Skips the spot-chance modifiers in {@code IsoZombie.spottedNew} when the chance is already 0.
*
* <p>Between {@code if (bForced) chance = 1000000F} and {@code chance = (float)
* PZMath.fastfloor(chance)} the method only multiplies or divides {@code chance}: bonus spot
* time, sight, inactivity, traits of the player, shelter ({@code getObstacleMod}),
* {@code isVehicleBetween}, worn items, eating. A chance of 0 stays 0, or becomes NaN when divided
* by 0, and the roll {@code Rand.Next(10000) / 100F < chance} fails for both. The chance is 0 when
* the player is outside the zombie's vision radius or behind it, and is never 0 for a forced spot.
*
* <p>The patch inserts {@code if (chance == 0F) goto rounding} after the forced-spot assignment.
* The rounding, the roll (with its {@code Rand.Next} draw) and the failed-roll branch run as in
* vanilla. The early return for a nearer current target comes before the jump. The skipped code
* writes no field or local that is read after the jump; it writes the shared scratch vector
* {@code IsoGameCharacter.tempo}, which other code sets before reading, except client debug drawing.
*/
public final class IsoZombieSpotChancePerformancePatch extends PerformancePatch
{
private static final Anchor.Method SPOTTED_NEW = new Anchor.Method("spottedNew", "(Lzombie/iso/IsoMovingObject;Z)V");
/** {@code if (bForced) chance = 1000000F;}: the store of the forced chance. */
private static final Anchor.Sequence FORCED_CHANCE = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Constant(1000000.0F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
/** {@code chance = (float) PZMath.fastfloor(chance);}: the rounding before the roll. */
private static final Anchor.Sequence ROUNDING = new Anchor.Sequence(
IsoZombieSpotChancePerformancePatch.SPOTTED_NEW,
new Anchor.Instruction.Opcode(Opcodes.FLOAD),
new Anchor.Instruction.Invoke("zombie/core/math/PZMath", "fastfloor", "(F)I"),
new Anchor.Instruction.Opcode(Opcodes.I2F),
new Anchor.Instruction.Opcode(Opcodes.FSTORE)
);
public IsoZombieSpotChancePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieSpotChancePerformancePatch.FORCED_CHANCE, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieSpotChancePerformancePatch.SPOTTED_NEW.resolve(node);
List<AbstractInsnNode> forced = IsoZombieSpotChancePerformancePatch.FORCED_CHANCE.resolve(node);
List<AbstractInsnNode> rounding = IsoZombieSpotChancePerformancePatch.ROUNDING.resolve(node);
AbstractInsnNode forcedStore = forced.getLast();
AbstractInsnNode roundingLoad = rounding.getFirst();
int chance = ((VarInsnNode) forcedStore).var;
IsoZombieSpotChancePerformancePatch.requireVariable(roundingLoad, chance);
IsoZombieSpotChancePerformancePatch.requireVariable(rounding.getLast(), chance);
if (method.instructions.indexOf(roundingLoad) < method.instructions.indexOf(forcedStore))
throw new IllegalStateException("'" + node.name + ".spottedNew': the rounding of 'chance' comes before the forced-spot assignment.");
// The check goes after the label that the 'if (bForced)' jump targets, so both paths run it.
// Inserting it before the new label keeps it ahead of that label if both precede the same instruction.
LabelNode roundingLabel = new LabelNode();
method.instructions.insertBefore(
IsoZombieSpotChancePerformancePatch.nextInstruction(forcedStore),
IsoZombieSpotChancePerformancePatch.jumpIfZero(chance, roundingLabel)
);
method.instructions.insertBefore(roundingLoad, roundingLabel);
}
/**
* {@code if (chance == 0F) goto target}. {@code fcmpl} pushes -1 for NaN, so NaN does not
* jump; -0F does.
*/
private static InsnList jumpIfZero(int chance, LabelNode target)
{
InsnList code = new InsnList();
code.add(new VarInsnNode(Opcodes.FLOAD, chance));
code.add(new InsnNode(Opcodes.FCONST_0));
code.add(new InsnNode(Opcodes.FCMPL));
code.add(new JumpInsnNode(Opcodes.IFEQ, target));
return code;
}
private static void requireVariable(AbstractInsnNode instruction, int chance)
{
int variable = ((VarInsnNode) instruction).var;
if (variable != chance)
throw new IllegalStateException("'IsoZombie.spottedNew': the rounding uses local " + variable + ", the forced-spot assignment local " + chance + ".");
}
/** The closest later instruction that is not a label, line number, or frame. */
private static AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode next = instruction.getNext();
while (next != null && next.getOpcode() == -1) next = next.getNext();
if (next == null) throw new IllegalStateException("'IsoZombie.spottedNew' ends after the forced-spot assignment.");
return next;
}
}
@@ -0,0 +1,30 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
/**
* Class loader that defines classes from {@link ClassNode}s, so patched test classes can be loaded
* and run. Lives in a subpackage so that the scanned packages do not contain it.
*/
public final class ClassDefiner extends ClassLoader
{
public ClassDefiner() { super(ClassDefiner.class.getClassLoader()); }
/**
* Writes {@code node} with computed frames and defines it. Classes that the frame computation
* needs (common superclasses) must be defined first.
*/
public Class<?> define(ClassNode node)
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES)
{
@Override
protected ClassLoader getClassLoader() { return ClassDefiner.this; }
};
node.accept(writer);
byte[] bytes = writer.toByteArray();
return this.defineClass(node.name.replace('/', '.'), bytes, 0, bytes.length);
}
}
@@ -0,0 +1,252 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.MethodNode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
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_FINAL;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
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.ARETURN;
import static org.objectweb.asm.Opcodes.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NOP;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoGameCharacterStateMachinePerformancePatchTest
{
private static final String CHARACTER = "zombie/characters/IsoGameCharacter";
private static final String COMPONENT = "zombie/characters/component/StateMachineComponent";
private static final String ECS_COMPONENT = "zombie/characters/ecs/ECSComponent";
private static final String ECS_ENTITY = "zombie/characters/ecs/ECSEntity";
private Class<?> characterClass = Object.class;
private Class<?> componentClass = Object.class;
/**
* {@code IsoGameCharacter} whose lookup counts its calls and returns the field {@code current}:
*
* <pre>{@code
* public static int lookups;
* public ECSComponent current;
*
* public ECSComponent getECSComponent(Class type) { lookups++; return this.current; }
*
* public final StateMachineComponent getStateMachineComponent() {
* return (StateMachineComponent) this.getECSComponent(StateMachineComponent.class);
* }
* }</pre>
*/
private static ClassNode character()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "java/lang/Object", IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY
);
String component = "L" + IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT + ";";
String ecsComponent = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT + ";";
node.visitField(ACC_PUBLIC | ACC_STATIC, "lookups", "I", null, null);
node.visitField(ACC_PUBLIC, "current", ecsComponent, null, null);
MethodVisitor lookup = node.visitMethod(ACC_PUBLIC, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, null, null);
lookup.visitFieldInsn(GETSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitInsn(ICONST_1);
lookup.visitInsn(IADD);
lookup.visitFieldInsn(PUTSTATIC, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "lookups", "I");
lookup.visitVarInsn(ALOAD, 0);
lookup.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "current", ecsComponent);
lookup.visitInsn(ARETURN);
lookup.visitMaxs(0, 0);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC | ACC_FINAL, "getStateMachineComponent", "()" + component, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitLdcInsn(Type.getObjectType(IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT));
getter.visitMethodInsn(INVOKEVIRTUAL, IsoGameCharacterStateMachinePerformancePatchTest.CHARACTER, "getECSComponent", "(Ljava/lang/Class;)" + ecsComponent, false);
getter.visitTypeInsn(CHECKCAST, IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
/** {@code ECSComponent} with a public field {@code owner} that {@code getECSOwnerEntity()} returns. */
private static ClassNode ecsComponent()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "java/lang/Object", null);
String owner = "L" + IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY + ";";
node.visitField(ACC_PUBLIC, "owner", owner, null, null);
MethodVisitor getter = node.visitMethod(ACC_PUBLIC, "getECSOwnerEntity", "()" + owner, null, null);
getter.visitVarInsn(ALOAD, 0);
getter.visitFieldInsn(GETFIELD, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, "owner", owner);
getter.visitInsn(ARETURN);
getter.visitMaxs(0, 0);
return node;
}
private static ClassNode ecsEntity()
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC | ACC_INTERFACE | ACC_ABSTRACT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_ENTITY, null, "java/lang/Object", null);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name, String superName, @Nullable String interfaceName)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, superName, interfaceName == null ? null : new String[] { interfaceName });
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
private static ClassNode patched()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
new IsoGameCharacterStateMachinePerformancePatch().apply(node);
return node;
}
@BeforeEach
void loadPatchedClasses()
{
ClassDefiner definer = new ClassDefiner();
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsEntity());
definer.define(IsoGameCharacterStateMachinePerformancePatchTest.ecsComponent());
this.componentClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.emptyClass(
IsoGameCharacterStateMachinePerformancePatchTest.COMPONENT, IsoGameCharacterStateMachinePerformancePatchTest.ECS_COMPONENT, null
));
this.characterClass = definer.define(IsoGameCharacterStateMachinePerformancePatchTest.patched());
}
private Object newCharacter() throws ReflectiveOperationException { return this.characterClass.getConstructor().newInstance(); }
/** A component owned by {@code owner} and registered as its {@code current} component. */
private Object addComponent(Object owner) throws ReflectiveOperationException
{
Object component = this.componentClass.getConstructor().newInstance();
this.componentClass.getField("owner").set(component, owner);
this.characterClass.getField("current").set(owner, component);
return component;
}
private Object stateMachineComponent(Object character) throws ReflectiveOperationException
{
return this.characterClass.getMethod("getStateMachineComponent").invoke(character);
}
private int lookups() throws ReflectiveOperationException { return this.characterClass.getField("lookups").getInt(null); }
@Test
void anchorMatchesTheTarget()
{
new IsoGameCharacterStateMachinePerformancePatch().anchor().verify(IsoGameCharacterStateMachinePerformancePatchTest.character());
}
@Test
void returnsTheStoredComponentWithoutALookup() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
assertSame(component, this.stateMachineComponent(character));
assertEquals(1, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentWasReplaced() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object first = this.addComponent(character);
assertSame(first, this.stateMachineComponent(character));
// ECSEntity.setECSComponent removes the old component, which sets its owner to null.
this.componentClass.getField("owner").set(first, null);
Object second = this.addComponent(character);
assertSame(second, this.stateMachineComponent(character));
assertSame(second, this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void looksUpAgainAfterTheComponentMovedToAnotherCharacter() throws ReflectiveOperationException
{
Object character = this.newCharacter();
Object component = this.addComponent(character);
assertSame(component, this.stateMachineComponent(character));
this.componentClass.getField("owner").set(component, this.newCharacter());
this.characterClass.getField("current").set(character, null);
assertNull(this.stateMachineComponent(character));
assertEquals(2, this.lookups());
}
@Test
void failsWhenTheGetterDoesMoreThanTheLookup()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.character();
MethodNode getter = node.methods.stream().filter(method -> method.name.equals("getStateMachineComponent")).findFirst().orElseThrow();
getter.instructions.insert(new InsnNode(NOP));
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void failsWhenTheGameClassAlreadyHasTheField()
{
ClassNode node = IsoGameCharacterStateMachinePerformancePatchTest.patched();
assertThrows(IllegalStateException.class, () -> new IsoGameCharacterStateMachinePerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoGameCharacterStateMachinePerformancePatch patch = new IsoGameCharacterStateMachinePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -0,0 +1,191 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
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.F2I;
import static org.objectweb.asm.Opcodes.FLOAD;
import static org.objectweb.asm.Opcodes.FMUL;
import static org.objectweb.asm.Opcodes.FSTORE;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.I2F;
import static org.objectweb.asm.Opcodes.IADD;
import static org.objectweb.asm.Opcodes.ICONST_1;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieSpotChancePerformancePatchTest
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String MOVING = "zombie/iso/IsoMovingObject";
private static final String MATH = "zombie/core/math/PZMath";
private static final int CHANCE = 5;
private record Result(int modifierRuns, float rounded) {}
/**
* {@code IsoZombie} with the shape of {@code spottedNew} around the patched range:
*
* <pre>{@code
* public static float input;
* public static int modifierRuns;
* public static float rounded;
*
* public void spottedNew(IsoMovingObject other, boolean bForced)
* {
* float chance = input; // local 5
* if (bForced) chance = 1000000F;
* modifierRuns++; // stands for the modifiers
* chance *= 2F;
* chance = (float) PZMath.fastfloor(chance); // local roundingLocal
* rounded = chance;
* }
* }</pre>
*/
private static ClassNode zombie(int roundingLocal)
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.ZOMBIE);
node.visitField(ACC_PUBLIC | ACC_STATIC, "input", "F", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "modifierRuns", "I", null, null);
node.visitField(ACC_PUBLIC | ACC_STATIC, "rounded", "F", null, null);
MethodVisitor method = node.visitMethod(ACC_PUBLIC, "spottedNew", "(L" + IsoZombieSpotChancePerformancePatchTest.MOVING + ";Z)V", null, null);
Label notForced = new Label();
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "input", "F");
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(ILOAD, 2);
method.visitJumpInsn(IFEQ, notForced);
method.visitLdcInsn(1000000.0F);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLabel(notForced);
method.visitFieldInsn(GETSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitInsn(ICONST_1);
method.visitInsn(IADD);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "modifierRuns", "I");
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitLdcInsn(2.0F);
method.visitInsn(FMUL);
method.visitVarInsn(FSTORE, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitVarInsn(FLOAD, roundingLocal);
method.visitMethodInsn(INVOKESTATIC, IsoZombieSpotChancePerformancePatchTest.MATH, "fastfloor", "(F)I", false);
method.visitInsn(I2F);
method.visitVarInsn(FSTORE, roundingLocal);
method.visitVarInsn(FLOAD, IsoZombieSpotChancePerformancePatchTest.CHANCE);
method.visitFieldInsn(PUTSTATIC, IsoZombieSpotChancePerformancePatchTest.ZOMBIE, "rounded", "F");
method.visitInsn(RETURN);
method.visitMaxs(0, 0);
return node;
}
/** {@code PZMath} with {@code fastfloor} as {@code (int) value}, which equals it for the values used here. */
private static ClassNode math()
{
ClassNode node = IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MATH);
MethodVisitor fastfloor = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "fastfloor", "(F)I", null, null);
fastfloor.visitVarInsn(FLOAD, 0);
fastfloor.visitInsn(F2I);
fastfloor.visitInsn(IRETURN);
fastfloor.visitMaxs(0, 0);
return node;
}
/** Public class with a public no-argument constructor. */
private static ClassNode emptyClass(String name)
{
ClassNode node = new ClassNode();
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** Loads the patched {@code IsoZombie} and runs {@code spottedNew(null, forced)} with {@code input} as the chance. */
private static Result run(float input, boolean forced) throws ReflectiveOperationException
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE);
new IsoZombieSpotChancePerformancePatch().apply(zombie);
ClassDefiner definer = new ClassDefiner();
definer.define(IsoZombieSpotChancePerformancePatchTest.math());
Class<?> moving = definer.define(IsoZombieSpotChancePerformancePatchTest.emptyClass(IsoZombieSpotChancePerformancePatchTest.MOVING));
Class<?> loaded = definer.define(zombie);
loaded.getField("input").setFloat(null, input);
loaded.getMethod("spottedNew", moving, boolean.class).invoke(loaded.getConstructor().newInstance(), null, forced);
return new Result(loaded.getField("modifierRuns").getInt(null), loaded.getField("rounded").getFloat(null));
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieSpotChancePerformancePatch().anchor().verify(IsoZombieSpotChancePerformancePatchTest.zombie(IsoZombieSpotChancePerformancePatchTest.CHANCE));
}
@Test
void zeroChanceSkipsTheModifiersAndStillRounds() throws ReflectiveOperationException
{
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, false));
assertEquals(new Result(0, 0.0F), IsoZombieSpotChancePerformancePatchTest.run(-0.0F, false));
}
@Test
void otherChancesRunTheModifiers() throws ReflectiveOperationException
{
assertEquals(new Result(1, 6.0F), IsoZombieSpotChancePerformancePatchTest.run(3.0F, false));
assertEquals(new Result(1, 2000000.0F), IsoZombieSpotChancePerformancePatchTest.run(0.0F, true));
assertEquals(1, IsoZombieSpotChancePerformancePatchTest.run(Float.NaN, false).modifierRuns());
}
@Test
void failsWhenTheRoundingUsesAnotherLocal()
{
ClassNode zombie = IsoZombieSpotChancePerformancePatchTest.zombie(6);
assertThrows(IllegalStateException.class, () -> new IsoZombieSpotChancePerformancePatch().apply(zombie));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieSpotChancePerformancePatch patch = new IsoZombieSpotChancePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
@@ -1,12 +1,19 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.Printer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* The landmark in the target class that a {@link ClassPatch} depends on. A patch can only
@@ -71,4 +78,134 @@ public sealed interface Anchor
&& call.desc.equals(this.desc);
}
}
/**
* Consecutive instructions inside the method {@code in}, one per element of {@code pattern}.
* Labels, line numbers and stack map frames between them are skipped, so a jump target or a
* new source line inside the sequence does not break a match. Overlapping matches count
* separately.
*/
record Sequence(Method in, List<Instruction> pattern) implements Anchor
{
public Sequence
{
if (pattern.isEmpty()) throw new IllegalArgumentException("A sequence anchor needs at least one instruction.");
pattern = List.copyOf(pattern);
}
public Sequence(Method in, Instruction... pattern) { this(in, List.of(pattern)); }
/** The matched instructions, one per element of {@link #pattern()}, in the same order. */
public List<AbstractInsnNode> resolve(ClassNode node)
{
List<AbstractInsnNode> instructions = Sequence.realInstructions(this.in.resolve(node));
List<List<AbstractInsnNode>> matches = new ArrayList<>();
for (int start = 0; start + this.pattern.size() <= instructions.size(); start++) {
List<AbstractInsnNode> candidate = instructions.subList(start, start + this.pattern.size());
if (this.matches(candidate)) matches.add(candidate);
}
if (matches.size() != 1) {
throw new IllegalStateException(
"Expected exactly one sequence " + this.pattern + " in '" + node.name + "." + this.in.name() + this.in.desc()
+ "', found " + matches.size()
);
}
return List.copyOf(matches.getFirst());
}
@Override
public void verify(ClassNode node) { this.resolve(node); }
private boolean matches(List<AbstractInsnNode> candidate)
{
for (int i = 0; i < candidate.size(); i++) {
if (!this.pattern.get(i).matches(candidate.get(i))) return false;
}
return true;
}
/** The instructions of {@code method} without labels, line numbers and frames (opcode -1). */
private static List<AbstractInsnNode> realInstructions(MethodNode method)
{
List<AbstractInsnNode> instructions = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) instructions.add(instruction);
}
return instructions;
}
}
/** One element of a {@link Sequence}: a test for a single instruction. */
sealed interface Instruction
{
boolean matches(AbstractInsnNode instruction);
/** Any instruction with this opcode, e.g. {@code Opcodes.FSTORE} for a store to any local variable. */
record Opcode(int opcode) implements Instruction
{
public Opcode
{
if (opcode < 0 || opcode >= Printer.OPCODES.length) throw new IllegalArgumentException("Not an opcode: " + opcode);
}
@Override
public boolean matches(AbstractInsnNode instruction) { return instruction.getOpcode() == this.opcode; }
@Override
public String toString() { return Printer.OPCODES[this.opcode].toLowerCase(Locale.ROOT); }
}
/**
* A constant push of {@code value}: {@code ldc}, or the shorter forms used for small
* values ({@code iconst_<n>}, {@code lconst_<n>}, {@code fconst_<n>}, {@code dconst_<n>},
* {@code bipush}, {@code sipush}). The boxed type has to match: {@code 0} (an
* {@code Integer}) does not match {@code fconst_0}. A class literal is an
* {@link org.objectweb.asm.Type}.
*/
record Constant(Object value) implements Instruction
{
@Override
public boolean matches(AbstractInsnNode instruction) { return this.value.equals(Constant.valueOf(instruction)); }
@Override
public String toString() { return "constant " + this.value; }
private static @Nullable Object valueOf(AbstractInsnNode instruction)
{
int opcode = instruction.getOpcode();
if (instruction instanceof LdcInsnNode ldc) return ldc.cst;
if (opcode == Opcodes.BIPUSH || opcode == Opcodes.SIPUSH) return ((IntInsnNode) instruction).operand;
if (opcode >= Opcodes.ICONST_M1 && opcode <= Opcodes.ICONST_5) return opcode - Opcodes.ICONST_0;
if (opcode >= Opcodes.LCONST_0 && opcode <= Opcodes.LCONST_1) return (long) (opcode - Opcodes.LCONST_0);
if (opcode >= Opcodes.FCONST_0 && opcode <= Opcodes.FCONST_2) return (float) (opcode - Opcodes.FCONST_0);
if (opcode >= Opcodes.DCONST_0 && opcode <= Opcodes.DCONST_1) return (double) (opcode - Opcodes.DCONST_0);
return null;
}
}
/** A static, virtual, special, or interface call to {@code owner.name desc}. */
record Invoke(String owner, String name, String desc) implements Instruction
{
@Override
public boolean matches(AbstractInsnNode instruction)
{
return instruction instanceof MethodInsnNode call
&& call.owner.equals(this.owner)
&& call.name.equals(this.name)
&& call.desc.equals(this.desc);
}
@Override
public String toString() { return "invoke '" + this.owner + "." + this.name + this.desc + "'"; }
}
}
}
@@ -7,6 +7,7 @@ import org.objectweb.asm.tree.ClassNode;
/** A build-time change to one class of the vanilla server jar. */
@Internal
@SuppressWarnings("NullableProblems")
public interface ClassPatch {
/** Internal name of the class to patch, e.g. {@code zombie/network/GameServer}. */
String target();
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
@@ -21,13 +23,13 @@ import java.util.function.Function;
final class HierarchyClassWriter extends ClassWriter {
private static final String OBJECT = "java/lang/Object";
private record Header(String superName, boolean isInterface) {}
private record Header(@Nullable String superName, boolean isInterface) {}
private final Function<String, byte[]> jarClasses;
private final Function<String, byte @Nullable []> jarClasses;
private final Map<String, Header> headers = new HashMap<>();
/** @param jarClasses bytes of a class in the jar being patched, or {@code null} */
HierarchyClassWriter(Function<String, byte[]> jarClasses) {
HierarchyClassWriter(Function<String, byte @Nullable []> jarClasses) {
super(COMPUTE_FRAMES);
this.jarClasses = jarClasses;
}
@@ -60,7 +62,7 @@ final class HierarchyClassWriter extends ClassWriter {
private byte[] bytes(String internalName)
{
byte[] bytes = jarClasses.apply(internalName);
byte @Nullable [] bytes = jarClasses.apply(internalName);
if (bytes != null) return bytes;
// JDK (or other non-jar) class.
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
@@ -7,15 +9,7 @@ import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@@ -84,7 +78,7 @@ public final class JarPatcher
{
try (ZipFile zip = new ZipFile(jar.toFile()))
{
byte[] core = read(zip, GameVersionReader.CORE_CLASS + ".class");
byte[] core = JarPatcher.read(zip, GameVersionReader.CORE_CLASS + ".class");
if (core == null) throw new IllegalStateException("'" + jar + "' contains no " + GameVersionReader.CORE_CLASS + ".class");
return GameVersionReader.read(core);
@@ -104,12 +98,8 @@ public final class JarPatcher
*/
public static List<ClassPatch> applicablePatches(PatchSet patchSet, GameVersion version, Set<String> disabled)
{
if (patchSet.build() != version.major()) {
throw new IllegalStateException(
"Patch set is for Build " + patchSet.build()
+ ", but the server jar is Project Zomboid " + version
);
}
if (patchSet.build() != version.major())
throw new IllegalStateException("Patch set is for Build " + patchSet.build() + ", but the server jar is Project Zomboid " + version + ".");
Set<String> unknown = new TreeSet<>(disabled);
patchSet.patches().forEach(patch -> unknown.remove(patch.getClass().getSimpleName()));
@@ -218,7 +208,7 @@ public final class JarPatcher
patch.apply(node);
}
HierarchyClassWriter writer = new HierarchyClassWriter(name -> read(jar, name + ".class"));
HierarchyClassWriter writer = new HierarchyClassWriter(name -> JarPatcher.read(jar, name + ".class"));
node.accept(writer);
return writer.toByteArray();
@@ -230,7 +220,7 @@ public final class JarPatcher
catch (IllegalStateException e) { throw new IllegalStateException("'" + patch.getClass().getSimpleName() + "': " + e.getMessage(), e); }
}
private static byte[] read(ZipFile jar, String entryName)
private static byte @Nullable [] read(ZipFile jar, String entryName)
{
ZipEntry entry = jar.getEntry(entryName);
if (entry == null) return null;
@@ -3,7 +3,6 @@ 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 org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
@@ -24,7 +23,7 @@ public abstract class HookInjectionPatch implements ClassPatch
private final Anchor.Call anchor;
private final Hook hook;
protected HookInjectionPatch(String target, Anchor.Call anchor, @NotNull Hook hook)
protected HookInjectionPatch(String target, Anchor.Call anchor, Hook hook)
{
if (!hook.desc().equals(HookInjectionPatch.HOOK_DESC))
throw new IllegalArgumentException("Hook '" + hook + "' must have descriptor '" + HookInjectionPatch.HOOK_DESC + "'.");
@@ -39,7 +38,7 @@ public abstract class HookInjectionPatch implements ClassPatch
@Override
public final Anchor.Call anchor() { return this.anchor; }
@Override
public final @NotNull Hook hook() { return this.hook; }
public final Hook hook() { return this.hook; }
@Override
public final void apply(ClassNode node)
@@ -4,7 +4,7 @@ import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Hook;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.tree.ClassNode;
@@ -24,13 +24,13 @@ public abstract class PerformancePatch implements ClassPatch
{
private final String target;
private final Anchor anchor;
private final Hook hook;
private final @Nullable Hook hook;
/**
* @param hook the runtime method the patched code calls, or {@code null} when the patch
* only changes the target class itself
*/
protected PerformancePatch(String target, @NotNull Anchor anchor, @Nullable Hook hook)
protected PerformancePatch(String target, Anchor anchor, @Nullable Hook hook)
{
this.target = Objects.requireNonNull(target);
this.anchor = Objects.requireNonNull(anchor);
@@ -2,15 +2,32 @@ package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.BIPUSH;
import static org.objectweb.asm.Opcodes.FCONST_0;
import static org.objectweb.asm.Opcodes.FSTORE;
import static org.objectweb.asm.Opcodes.ICONST_M1;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.LCONST_1;
import static org.objectweb.asm.Opcodes.RETURN;
class AnchorTest
@@ -18,6 +35,12 @@ class AnchorTest
private static final Anchor.Method RUN = new Anchor.Method("run", "()V");
private static final Anchor.Call CALL = new Anchor.Call(RUN, "t/Dep", "go", "()V");
private static final Anchor.Sequence FORCED_STORE = new Anchor.Sequence(
RUN,
new Anchor.Instruction.Constant(1000000.0F),
new Anchor.Instruction.Opcode(FSTORE)
);
private static ClassNode classWithRun(int callsToGo)
{
ClassNode node = new ClassNode();
@@ -75,4 +98,98 @@ class AnchorTest
assertDoesNotThrow(() -> AnchorTest.CALL.verify(node));
}
/** {@code run()V} with {@code ldc 1000000.0F; <label>; <line number>; fstore 5}, {@code stores} times. */
private static ClassNode classWithForcedStores(int stores)
{
InsnList code = new InsnList();
for (int i = 0; i < stores; i++) {
LabelNode label = new LabelNode();
code.add(new LdcInsnNode(1000000.0F));
code.add(label);
code.add(new LineNumberNode(100 + i, label));
code.add(new VarInsnNode(FSTORE, 5));
}
return AnchorTest.classWithRun(code);
}
private static ClassNode classWithRun(InsnList code)
{
ClassNode node = new ClassNode();
node.name = "t/Target";
MethodNode run = new MethodNode(ACC_STATIC, "run", "()V", null, null);
run.instructions.add(code);
run.visitInsn(RETURN);
node.methods.add(run);
return node;
}
@Test
void sequenceAnchorSkipsLabelsAndLineNumbers()
{
ClassNode node = AnchorTest.classWithForcedStores(1);
List<?> match = AnchorTest.FORCED_STORE.resolve(node);
assertEquals(2, match.size());
assertSame(node.methods.getFirst().instructions.get(0), match.get(0));
assertSame(node.methods.getFirst().instructions.get(3), match.get(1));
}
@Test
void sequenceAnchorMatchesExactlyOnce()
{
assertEquals(
"Expected exactly one sequence [constant 1000000.0, fstore] in 't/Target.run()V', found 0",
assertThrows(IllegalStateException.class, () -> AnchorTest.FORCED_STORE.verify(AnchorTest.classWithForcedStores(0))).getMessage()
);
assertTrue(
assertThrows(IllegalStateException.class, () -> AnchorTest.FORCED_STORE.verify(AnchorTest.classWithForcedStores(2)))
.getMessage().endsWith("found 2")
);
}
@Test
void sequenceAnchorNeedsAnInstruction()
{
assertThrows(IllegalArgumentException.class, () -> new Anchor.Sequence(AnchorTest.RUN));
}
@Test
void constantMatchesShortFormsOfTheSameType()
{
assertTrue(new Anchor.Instruction.Constant(0.0F).matches(new InsnNode(FCONST_0)));
assertTrue(new Anchor.Instruction.Constant(-1).matches(new InsnNode(ICONST_M1)));
assertTrue(new Anchor.Instruction.Constant(1L).matches(new InsnNode(LCONST_1)));
assertTrue(new Anchor.Instruction.Constant(100).matches(new IntInsnNode(BIPUSH, 100)));
assertTrue(new Anchor.Instruction.Constant("text").matches(new LdcInsnNode("text")));
assertFalse(new Anchor.Instruction.Constant(0).matches(new InsnNode(FCONST_0)));
assertFalse(new Anchor.Instruction.Constant(100L).matches(new IntInsnNode(BIPUSH, 100)));
assertFalse(new Anchor.Instruction.Constant(0.0F).matches(new InsnNode(RETURN)));
}
@Test
void invokeMatchesOwnerNameAndDescriptor()
{
Anchor.Instruction.Invoke go = new Anchor.Instruction.Invoke("t/Dep", "go", "()V");
assertTrue(go.matches(new MethodInsnNode(INVOKESTATIC, "t/Dep", "go", "()V", false)));
assertTrue(go.matches(new MethodInsnNode(INVOKEVIRTUAL, "t/Dep", "go", "()V", false)));
assertFalse(go.matches(new MethodInsnNode(INVOKESTATIC, "t/Other", "go", "()V", false)));
assertFalse(go.matches(new MethodInsnNode(INVOKESTATIC, "t/Dep", "go", "(I)V", false)));
}
@Test
void opcodeRejectsValuesOutsideTheInstructionSet()
{
assertThrows(IllegalArgumentException.class, () -> new Anchor.Instruction.Opcode(-1));
assertThrows(IllegalArgumentException.class, () -> new Anchor.Instruction.Opcode(200));
assertEquals("fstore", new Anchor.Instruction.Opcode(FSTORE).toString());
}
}