Author SHA1 Message Date
Overlord 1b4e153898 Merge branch 'release/v0.2.0'
ci / image (42.21, public) (push) Successful in 18s
2026-10-02 08:25:57 +02:00
Overlord 0966cdba89 Refine nullability annotations in HierarchyClassWriter and JarPatcher for consistency and clarity. 2026-10-01 18:11:55 +02:00
Overlord 30b0b0572f Annotate with @SuppressWarnings("NullableProblems"), clean up imports, and adjust nullability annotations for improved clarity and consistency. 2026-10-01 18:05:32 +02:00
Overlord c22aa29c88 Add new performance patches for IsoGameCharacter and IsoZombie, including caching and early-exit optimizations. Added corresponding tests. 2026-10-01 15:44:18 +02:00
Overlord 1a53f833e3 Add and test Anchor.Sequence to match instruction patterns, skipping labels and line numbers. Document sequence matching behavior and integrate new matchers (constant, opcode, invoke). 2026-10-01 14:16:44 +02:00
Overlord c9e41e2c91 Document FORGE_VERSION default and new DISABLED_PATCHES option in README, update Dockerfile to reflect default FORGE_VERSION. 2026-10-01 14:00:23 +02:00
Overlord 28c36c7eae Merge branch 'release/v0.2.0-performance'
ci / image (42.21, public) (push) Successful in 21s
2026-10-01 13:16:25 +02:00
Overlord 94a026093c Merge tag 'v0.2.0-performance' into develop
ci / image (42.21, public) (push) Successful in 1m44s
Tagging version v0.2.0-performance v0.2.0-performance
2026-10-01 13:16:25 +02:00
Overlord 134901098c Add IsoZombieNetworkComponentPerformancePatch for efficient component access by caching NetworkZombieComponent lookups. Update B42PatchSet to include the new patch and adjust related test cases. 2026-10-01 12:52:31 +02:00
Overlord acef6fd81f refactored package structure 2026-10-01 12:36:41 +02:00
Overlord 981445a797 Annotate all packages with @NotNullByDefault and suppress warnings for unstable API usage. 2026-10-01 12:29:07 +02:00
Overlord da7ae49618 Optimize IsoZombie.isVehicleBetween performance: implement IsoZombieVehiclePerformancePatch. Add SegmentReach class for efficient distance checks and ZombieVehicleHooks for targeted vehicle intersection. Include tests for new functionality and integrate patch into B42PatchSet. 2026-10-01 10:09:54 +02:00
Overlord d7151f60e8 Refactor patching structure: introduce PerformancePatch class and relocate HookInjectionPatch to Patches package. 2026-10-01 09:26:06 +02:00
Overlord abc6c6c53e Annotate interfaces and methods with proper nullability and internal use annotations, and clean up formatting. 2026-10-01 09:22:43 +02:00
Overlord 2b94a49352 Add support for anchors, hooks, and hook injection in patching logic with comprehensive tests.
ci / image (42.21, public) (push) Successful in 1m43s
Added onServerStarted Hook and Patch.
2026-09-30 21:59:22 +02:00
Overlord e13132c202 Introduce versioning from git tags and improve CI/CD workflows 2026-09-30 20:32:14 +02:00
Overlord 989cb88e0a Merge tag 'v0.1.0-SNAPSHOT' into develop
ci / image (42.21, public) (push) Successful in 20s
Tagging version v0.1.0-SNAPSHOT v0.1.0-SNAPSHOT
2026-09-30 16:38:18 +02:00
53 changed files with 3103 additions and 105 deletions

No files matched your search

+3
View File
@@ -19,6 +19,9 @@ jobs:
steam_branch: public
steps:
- uses: actions/checkout@v4
with:
# release.sh derives the version from the newest v* tag
fetch-depth: 0
- name: Build and verify
env:
+3
View File
@@ -21,6 +21,9 @@ jobs:
latest: "true"
steps:
- uses: actions/checkout@v4
with:
# release.sh derives the version from the newest v* tag
fetch-depth: 0
- name: Log in to the registry
env:
+11 -3
View File
@@ -12,13 +12,16 @@
# server reports another one. Default: pz.version in gradle.properties
# STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so
# files with steamcmd's newer copies
# FORGE_VERSION Image label only; set by ci/release.sh
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
# Default: 0.0.0-prerelease
# STEAM_BUILDID Image label only; set by ci/release.sh
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
# (debug builds only; ci/release.sh never sets it)
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 -----------------------------------------
@@ -50,11 +53,16 @@ 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 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=""
RUN ./gradlew --no-daemon \
-Ppz.jar=/pz/projectzomboid.jar \
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
build :patcher:patchServerJar
# --- Stage 3: runtime ------------------------------------------------------------
+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`.
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.agent;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.api;
import org.jetbrains.annotations.NotNullByDefault;
@@ -2,6 +2,22 @@ plugins {
java
}
// Version: -Pversion if given, else the newest v* git tag, else 0.0.0-prerelease.
if (version == Project.DEFAULT_VERSION)
{
val latestTag = providers.exec {
workingDir = layout.settingsDirectory.asFile
commandLine("git", "describe", "--tags", "--abbrev=0", "--match", "v*")
isIgnoreExitValue = true
}
version = latestTag.standardOutput.asText
.map { it.trim().removePrefix("v") }
.orElse("")
.get()
.ifEmpty { "0.0.0-prerelease" }
}
val projectZomboid = extensions.create<ProjectZomboidExtension>("projectZomboid")
projectZomboid.serverJar.convention(
layout.settingsDirectory.file(
+30 -6
View File
@@ -7,13 +7,17 @@
# <forge>-pz<pz> moves to the newest Steam build of that version
# latest only with LATEST=true
#
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
# published. Without any v* tag the version is "0.0.0-prerelease".
#
# Nothing is built when the immutable tag already exists in the registry.
#
# Environment:
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
# PZ_BRANCH Steam branch. Default: public
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
# PUBLISH true: push the tags. Default: false (build and verify only)
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
# LATEST true: also push "latest". Default: false
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
@@ -26,7 +30,7 @@ readonly REPO_ROOT
readonly IMAGE="${IMAGE:?IMAGE is required}"
readonly PZ_BRANCH="${PZ_BRANCH:-public}"
readonly PUBLISH="${PUBLISH:-false}"
readonly REQUESTED_PUBLISH="${PUBLISH:-false}"
readonly LATEST="${LATEST:-false}"
log() {
@@ -59,6 +63,16 @@ gradle_property() {
exit 1
}
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
# or nothing when the repository has no such tag.
release_tag_version() {
local tag
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
echo "${tag#v}"
fi
}
image_exists() {
local reference="$1"
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
@@ -104,10 +118,20 @@ push_as() {
main() {
local forge_version
local publish="${REQUESTED_PUBLISH}"
local pz_version
local build_id
forge_version="$(gradle_property version)"
forge_version="$(release_tag_version)"
if [[ -z "${forge_version}" ]]; then
forge_version="0.0.0-prerelease"
log "No v* git tag found (shallow clone without tags?); using version ${forge_version}."
fi
if [[ "${forge_version}" == *-* ]]; then
publish=false
log "${forge_version} is a pre-release version; nothing will be published."
fi
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
@@ -115,7 +139,7 @@ main() {
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
if [[ "${PUBLISH}" == true ]] && image_exists "${immutable_tag}"; then
if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then
log "${immutable_tag} is already published; nothing to do."
return
fi
@@ -123,8 +147,8 @@ main() {
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
verify_build_id "${immutable_tag}" "${build_id}"
if [[ "${PUBLISH}" != true ]]; then
log "Built ${immutable_tag} (PUBLISH is not true; nothing pushed)"
if [[ "${publish}" != true ]]; then
log "Built ${immutable_tag} (not published)"
return
fi
+6
View File
@@ -7,4 +7,10 @@ plugins {
dependencies {
implementation(project(":patcher"))
implementation(libs.bundles.asm)
// Hook classes are read as class files to check that the patches' hooks exist.
testImplementation(project(":compat:b42:runtime"))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
}
@@ -0,0 +1,31 @@
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;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/** Every build-time patch for Build 42, in application order. */
public final class B42PatchSet implements PatchSet
{
private static final List<ClassPatch> PATCHES = List.of(
new ServerStartedPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
new IsoGameCharacterStateMachinePerformancePatch()
);
@Override
public int build() { return 42; }
@Override
public @NotNull List<ClassPatch> patches() { return B42PatchSet.PATCHES; }
}
@@ -1,21 +0,0 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
import java.util.List;
/** Every build-time patch for Build 42, in application order. */
public final class B42PatchSet implements PatchSet {
private static final List<ClassPatch> PATCHES = List.of();
@Override
public int build() {
return 42;
}
@Override
public List<ClassPatch> patches() {
return PATCHES;
}
}
@@ -0,0 +1,26 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
/**
* Calls {@code ServerHooks.onServerStarted()} in {@code GameServer.main}, directly after
* {@code UnitTests.runIfEnabled()} and before the {@code while (!done)} main loop: the world is
* loaded, the network port is open, and RCON is initialized.
*/
public final class ServerStartedPatch extends HookInjectionPatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("main", "([Ljava/lang/String;)V"),
"zombie/UnitTests", "runIfEnabled", "()V"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onServerStarted", "()V"
);
public ServerStartedPatch() {
super("zombie/network/GameServer", ServerStartedPatch.ANCHOR, ServerStartedPatch.HOOK);
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.patches;
import org.jetbrains.annotations.NotNullByDefault;
@@ -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,236 @@
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.jetbrains.annotations.Nullable;
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.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
/**
* Stores the {@code NetworkZombieComponent} of an {@code IsoZombie} in a field instead of
* looking it up in the entity's component map on every call.
*
* <p>Every call site in {@code IsoZombie} has the same shape:
* {@code (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class)}. The
* lookup walks the class hierarchy of the component class and reads a {@code HashMap}. The
* component is registered once by the {@code IsoObject} constructor and is never replaced or
* removed, so a value read once stays valid for the life of the zombie.
*
* <p>The patch adds the field and a private method that fills it on first use, and replaces the
* three instructions of each call site with a call to that method. A missing component is not
* stored: the method then returns {@code null} like the lookup does.
*/
public final class IsoZombieNetworkComponentPerformancePatch extends PerformancePatch
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
private static final String LOOKUP_NAME = "tryGetECSComponent";
private static final String LOOKUP_DESC = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
private static final String FIELD_NAME = "zomboidForge$networkComponent";
private static final String FIELD_DESC = "L" + IsoZombieNetworkComponentPerformancePatch.COMPONENT + ";";
private static final String ACCESSOR_NAME = "zomboidForge$networkComponent";
private static final String ACCESSOR_DESC = "()" + IsoZombieNetworkComponentPerformancePatch.FIELD_DESC;
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("getOwner", "()Lzombie/core/raknet/UdpConnection;"),
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC
);
public IsoZombieNetworkComponentPerformancePatch() {
super(IsoZombieNetworkComponentPerformancePatch.ZOMBIE, IsoZombieNetworkComponentPerformancePatch.ANCHOR, null);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
IsoZombieNetworkComponentPerformancePatch.requireNoMemberNamed(node);
node.fields.add(new FieldNode(Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, IsoZombieNetworkComponentPerformancePatch.FIELD_NAME, IsoZombieNetworkComponentPerformancePatch.FIELD_DESC, null, null));
node.methods.add(IsoZombieNetworkComponentPerformancePatch.accessor());
for (MethodNode method : node.methods) {
IsoZombieNetworkComponentPerformancePatch.replaceLookups(method);
}
}
/** The patch must not collide with a member of the game class, e.g. after an update. */
private static void requireNoMemberNamed(ClassNode node)
{
boolean fieldExists = node.fields.stream()
.anyMatch(field -> field.name.equals(IsoZombieNetworkComponentPerformancePatch.FIELD_NAME));
boolean methodExists = node.methods.stream()
.anyMatch(method -> method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME));
if (fieldExists || methodExists)
throw new IllegalStateException("'" + node.name + "' already has a member named '" + IsoZombieNetworkComponentPerformancePatch.FIELD_NAME + "'.");
}
/**
* <pre>{@code
* private NetworkZombieComponent zomboidForge$networkComponent()
* {
* NetworkZombieComponent component = this.zomboidForge$networkComponent;
*
* if (component == null) {
* component = (NetworkZombieComponent) this.tryGetECSComponent(NetworkZombieComponent.class);
* this.zomboidForge$networkComponent = component;
* }
*
* return component;
* }
* }</pre>
*/
private static MethodNode accessor()
{
MethodNode method = new MethodNode(
Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
null, null
);
LabelNode filled = new LabelNode();
InsnList code = method.instructions;
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new FieldInsnNode(
Opcodes.GETFIELD,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
));
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new JumpInsnNode(Opcodes.IFNONNULL, filled));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new LdcInsnNode(Type.getObjectType(IsoZombieNetworkComponentPerformancePatch.COMPONENT)));
code.add(new MethodInsnNode(
Opcodes.INVOKEVIRTUAL,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME,
IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC,
false
));
code.add(new TypeInsnNode(Opcodes.CHECKCAST, IsoZombieNetworkComponentPerformancePatch.COMPONENT));
code.add(new VarInsnNode(Opcodes.ASTORE, 1));
code.add(new VarInsnNode(Opcodes.ALOAD, 0));
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new FieldInsnNode(
Opcodes.PUTFIELD,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.FIELD_NAME,
IsoZombieNetworkComponentPerformancePatch.FIELD_DESC
));
code.add(filled);
code.add(new VarInsnNode(Opcodes.ALOAD, 1));
code.add(new InsnNode(Opcodes.ARETURN));
return method;
}
/**
* Replaces {@code ldc NetworkZombieComponent; invokevirtual tryGetECSComponent; checkcast
* NetworkZombieComponent} with {@code invokespecial zomboidForge$networkComponent}. The
* receiver is on the operand stack before and after, and the component instead of the
* {@code Class} leaves it, so the stack stays the same. The accessor itself is skipped: it
* contains the same three instructions.
*/
private static void replaceLookups(MethodNode method)
{
if (method.name.equals(IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME)) return;
for (AbstractInsnNode instruction : method.instructions.toArray())
{
if (!IsoZombieNetworkComponentPerformancePatch.isLookup(instruction)) continue;
@Nullable AbstractInsnNode load = IsoZombieNetworkComponentPerformancePatch.previousInstruction(instruction);
@Nullable AbstractInsnNode cast = IsoZombieNetworkComponentPerformancePatch.nextInstruction(instruction);
if (!IsoZombieNetworkComponentPerformancePatch.isComponentClassLiteral(load)) continue;
if (!IsoZombieNetworkComponentPerformancePatch.isComponentCast(cast)) continue;
method.instructions.remove(load);
method.instructions.remove(cast);
method.instructions.set(
instruction, new MethodInsnNode(
Opcodes.INVOKESPECIAL,
IsoZombieNetworkComponentPerformancePatch.ZOMBIE,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_NAME,
IsoZombieNetworkComponentPerformancePatch.ACCESSOR_DESC,
false
)
);
}
}
//
private static boolean isLookup(AbstractInsnNode instruction)
{
return instruction instanceof MethodInsnNode call
&& call.getOpcode() == Opcodes.INVOKEVIRTUAL
&& call.owner.equals(IsoZombieNetworkComponentPerformancePatch.ZOMBIE)
&& call.name.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_NAME)
&& call.desc.equals(IsoZombieNetworkComponentPerformancePatch.LOOKUP_DESC);
}
private static boolean isComponentClassLiteral(@Nullable AbstractInsnNode instruction)
{
return instruction instanceof LdcInsnNode ldc
&& ldc.cst instanceof Type type
&& type.getInternalName().equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
}
private static boolean isComponentCast(@Nullable AbstractInsnNode instruction)
{
return instruction instanceof TypeInsnNode cast
&& cast.getOpcode() == Opcodes.CHECKCAST
&& cast.desc.equals(IsoZombieNetworkComponentPerformancePatch.COMPONENT);
}
/** The closest earlier instruction that is not a label, line number, or frame; {@code null} at the start of the method. */
private static @Nullable AbstractInsnNode previousInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode previous = instruction.getPrevious();
while (previous != null && previous.getOpcode() == -1) previous = previous.getPrevious();
return previous;
}
/** The closest later instruction that is not a label, line number, or frame; {@code null} at the end of the method. */
private static @Nullable AbstractInsnNode nextInstruction(AbstractInsnNode instruction)
{
AbstractInsnNode next = instruction.getNext();
while (next != null && next.getOpcode() == -1) next = next.getNext();
return next;
}
}
@@ -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,92 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.Anchor;
import dev.overlord.zomboidforge.patcher.GameVersion;
import dev.overlord.zomboidforge.patcher.Hook;
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
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;
/**
* Makes {@code IsoZombie.isVehicleBetween} cheaper without changing its result, in two steps:
*
* <ul>
* <li>Returns {@code false} at the start of the method when the cell has no vehicles. The
* loop would not run, but the three pooled vectors are allocated and released first.</li>
* <li>Replaces the call to {@code BaseVehicle.getIntersectPoint} with
* {@code ZombieVehicleHooks.getIntersectPoint}, which skips vehicles that the segment
* cannot reach.</li>
* </ul>
*/
public final class IsoZombieVehiclePerformancePatch extends PerformancePatch
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("isVehicleBetween", "(FFF)Z"),
"zombie/vehicles/BaseVehicle", "getIntersectPoint",
"(Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
private static final Hook HOOK = new Hook(
"dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", "getIntersectPoint",
"(Lzombie/vehicles/BaseVehicle;Lorg/joml/Vector3f;Lorg/joml/Vector3f;Lorg/joml/Vector3f;)Lorg/joml/Vector3f;"
);
public IsoZombieVehiclePerformancePatch() {
super("zombie/characters/IsoZombie", IsoZombieVehiclePerformancePatch.ANCHOR, IsoZombieVehiclePerformancePatch.HOOK);
}
//
@Override
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
@Override
public void apply(ClassNode node)
{
MethodNode method = IsoZombieVehiclePerformancePatch.ANCHOR.in().resolve(node);
MethodInsnNode call = IsoZombieVehiclePerformancePatch.ANCHOR.resolve(node);
// The hook takes the receiver as its first argument, so the operand stack is the same
// as for the virtual call it replaces: vehicle, start, end, result -> Vector3f.
method.instructions.set(call, new MethodInsnNode(
Opcodes.INVOKESTATIC,
IsoZombieVehiclePerformancePatch.HOOK.owner(),
IsoZombieVehiclePerformancePatch.HOOK.name(),
IsoZombieVehiclePerformancePatch.HOOK.desc(),
false
));
method.instructions.insert(IsoZombieVehiclePerformancePatch.returnFalseWithoutVehicles());
}
/**
* {@code if (IsoWorld.instance.currentCell.getVehicles().isEmpty()) return false;}, the same
* expression the method iterates over. The method starts with an empty operand stack, so the
* stack map frame at the jump target is the one of the method entry; the class writer
* computes it.
*/
private static InsnList returnFalseWithoutVehicles()
{
LabelNode hasVehicles = new LabelNode();
InsnList code = new InsnList();
code.add(new FieldInsnNode(Opcodes.GETSTATIC, "zombie/iso/IsoWorld", "instance", "Lzombie/iso/IsoWorld;"));
code.add(new FieldInsnNode(Opcodes.GETFIELD, "zombie/iso/IsoWorld", "currentCell", "Lzombie/iso/IsoCell;"));
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "zombie/iso/IsoCell", "getVehicles", "()Ljava/util/Set;", false));
code.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "java/util/Set", "isEmpty", "()Z", true));
code.add(new JumpInsnNode(Opcodes.IFEQ, hasVehicles));
code.add(new InsnNode(Opcodes.ICONST_0));
code.add(new InsnNode(Opcodes.IRETURN));
code.add(hasVehicles);
return code;
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.perf;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1 +1 @@
dev.overlord.zomboidforge.compat.b42.patches.B42PatchSet
dev.overlord.zomboidforge.compat.b42.B42PatchSet
@@ -0,0 +1,105 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.Hook;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The patcher does not check that a hook exists; a missing one fails only when the patched
* game code runs, with a {@code NoSuchMethodError}. The hook classes are read as class files
* because their signatures may mention game classes, which are not on this class path.
*/
class HookExistenceTest
{
@Test
void everyHookOfThePatchSetExistsAsPublicStaticMethod() throws IOException
{
List<String> problems = new ArrayList<>();
for (ClassPatch patch : new B42PatchSet().patches())
{
Hook hook = patch.hook();
if (hook == null) continue;
String problem = HookExistenceTest.problemWith(hook);
if (problem != null) problems.add("'" + patch.getClass().getSimpleName() + "': " + problem);
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
@Test
void acceptsAnExistingPublicStaticMethod() throws IOException
{
assertNull(HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(I)Ljava/lang/String;")));
}
@Test
void reportsMissingClass() throws IOException
{
assertEquals(
"Hook class 't/Missing' not found on the class path",
HookExistenceTest.problemWith(new Hook("t/Missing", "hook", "()V"))
);
}
@Test
void reportsMissingMethodOrDescriptor() throws IOException
{
assertEquals(
"Hook method 'java/lang/String.nope()V' not found",
HookExistenceTest.problemWith(new Hook("java/lang/String", "nope", "()V"))
);
assertEquals(
"Hook method 'java/lang/String.valueOf(Z)V' not found",
HookExistenceTest.problemWith(new Hook("java/lang/String", "valueOf", "(Z)V"))
);
}
@Test
void reportsMethodThatIsNotPublicStatic() throws IOException
{
assertEquals(
"Hook method 'java/lang/String.length()I' is not public static",
HookExistenceTest.problemWith(new Hook("java/lang/String", "length", "()I"))
);
}
/** @return a description of what is wrong with {@code hook}, or {@code null} if it is usable */
private static String problemWith(Hook hook) throws IOException
{
try (InputStream in = ClassLoader.getSystemResourceAsStream(hook.owner() + ".class"))
{
if (in == null) return "Hook class '" + hook.owner() + "' not found on the class path";
ClassNode node = new ClassNode();
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
String description = "Hook method '" + hook.owner() + "." + hook.name() + hook.desc() + "'";
for (MethodNode method : node.methods)
{
if (!method.name.equals(hook.name()) || !method.desc.equals(hook.desc())) continue;
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
return publicStatic ? null : description + " is not public static";
}
return description + " not found";
}
}
}
@@ -0,0 +1,80 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Structure rules for Build 42 patches and hooks. Class names end in {@code Patch} and
* {@code Hooks}, so a class is recognizable as one or the other from its name alone.
*/
class NamingRulesTest
{
private static final List<String> PATCH_PACKAGES = List.of(
"dev/overlord/zomboidforge/compat/b42/patches",
"dev/overlord/zomboidforge/compat/b42/perf"
);
private static final String HOOKS_PACKAGE = "dev/overlord/zomboidforge/compat/b42/hooks";
@Test
void patchClassesEndInPatch() throws Exception
{
List<String> problems = new ArrayList<>();
for (String patchPackage : NamingRulesTest.PATCH_PACKAGES)
{
List<String> names = PackageScan.topLevelClassNames(patchPackage);
assertFalse(names.isEmpty(), "No classes found in '" + patchPackage + "'.");
for (String name : names)
{
if (!name.endsWith("Patch")) problems.add("'" + patchPackage + "/" + name + "' must end in 'Patch'.");
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
@Test
void hookClassesEndInHooksAndExposeOnlyPublicStaticMethods() throws Exception
{
List<String> problems = new ArrayList<>();
List<String> names = PackageScan.topLevelClassNames(NamingRulesTest.HOOKS_PACKAGE);
assertFalse(names.isEmpty(), "No classes found in '" + NamingRulesTest.HOOKS_PACKAGE + "'");
for (String name : names)
{
if (!name.endsWith("Hooks")) problems.add("'" + name + "' must end in 'Hooks'");
ClassNode node = PackageScan.read(NamingRulesTest.HOOKS_PACKAGE + "/" + name);
if ((node.access & Opcodes.ACC_FINAL) == 0) problems.add("'" + name + "' must be final");
for (MethodNode method : node.methods)
{
if ((method.access & Opcodes.ACC_SYNTHETIC) != 0 || method.name.equals("<clinit>")) continue;
if (method.name.equals("<init>"))
{
if ((method.access & Opcodes.ACC_PRIVATE) == 0) problems.add("'" + name + "' constructor must be private");
continue;
}
boolean publicStatic = (method.access & Opcodes.ACC_PUBLIC) != 0 && (method.access & Opcodes.ACC_STATIC) != 0;
if (!publicStatic) problems.add("'" + name + "." + method.name + method.desc + "' must be public static");
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
}
@@ -0,0 +1,54 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A patch class that is not in {@link B42PatchSet} is never applied. Patches are switched off
* for debug builds with the {@code zf.disabledPatches} Gradle property, not by removing them
* from the patch set.
*/
class PatchSetRegistrationTest
{
private static final List<String> PATCH_PACKAGES = List.of(
"dev/overlord/zomboidforge/compat/b42/patches",
"dev/overlord/zomboidforge/compat/b42/perf"
);
@Test
void everyPatchClassIsRegisteredExactlyOnce() throws Exception
{
List<String> problems = new ArrayList<>();
Set<String> registered = new TreeSet<>();
for (ClassPatch patch : new B42PatchSet().patches())
{
String name = patch.getClass().getSimpleName();
if (!registered.add(name)) problems.add("'" + name + "' is registered more than once.");
}
for (String patchPackage : PatchSetRegistrationTest.PATCH_PACKAGES)
{
for (String name : PackageScan.topLevelClassNames(patchPackage))
{
boolean abstractClass = (PackageScan.read(patchPackage + "/" + name).access & Opcodes.ACC_ABSTRACT) != 0;
if (name.endsWith("Patch") && !abstractClass && !registered.contains(name)) {
problems.add("'" + name + "' is not registered in 'B42PatchSet'.");
}
}
}
assertTrue(problems.isEmpty(), () -> String.join("\n", problems));
}
}
@@ -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,68 @@
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/**
* Lists and reads the classes of a package on the test class path, without loading them. Lives in
* a subpackage so that the scanned packages do not contain it.
*/
public final class PackageScan
{
private PackageScan() {}
/** Simple names of the top-level non-test classes in {@code packagePath}, from a directory or a jar on the class path. */
public static List<String> topLevelClassNames(String packagePath) throws IOException, URISyntaxException
{
List<String> names = new ArrayList<>();
for (URL url : Collections.list(ClassLoader.getSystemResources(packagePath)))
{
if (url.getProtocol().equals("file"))
{
try (Stream<Path> files = Files.list(Path.of(url.toURI()))) {
files.map(file -> file.getFileName().toString()).forEach(names::add);
}
}
else if (url.getProtocol().equals("jar"))
{
JarURLConnection connection = (JarURLConnection) url.openConnection();
connection.getJarFile().stream()
.map(entry -> entry.getName())
.filter(entry -> entry.startsWith(packagePath + "/") && entry.indexOf('/', packagePath.length() + 1) < 0)
.map(entry -> entry.substring(packagePath.length() + 1))
.forEach(names::add);
}
}
return names.stream()
.filter(file -> file.endsWith(".class") && !file.contains("$") && !file.equals("package-info.class"))
.filter(file -> !file.endsWith("Test.class"))
.map(file -> file.substring(0, file.length() - ".class".length()))
.sorted()
.toList();
}
public static ClassNode read(String internalName) throws IOException
{
try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class"))
{
ClassNode node = new ClassNode();
new ClassReader(in).accept(node, ClassReader.SKIP_CODE);
return node;
}
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.patches.support;
import org.jetbrains.annotations.NotNullByDefault;
@@ -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,209 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
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.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
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_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
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.CHECKCAST;
import static org.objectweb.asm.Opcodes.GETFIELD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.PUTFIELD;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieNetworkComponentPerformancePatchTest
{
private static final String ZOMBIE = "zombie/characters/IsoZombie";
private static final String COMPONENT = "zombie/characters/component/NetworkZombieComponent";
private static final String OTHER = "zombie/characters/component/OtherComponent";
private static final String LOOKUP = "(Ljava/lang/Class;)Lzombie/characters/ecs/ECSComponent;";
/** {@code this.tryGetECSComponent(component.class)} cast to {@code component}, result dropped. */
private static void lookup(MethodVisitor method, String component)
{
method.visitVarInsn(ALOAD, 0);
method.visitLdcInsn(Type.getObjectType(component));
method.visitMethodInsn(INVOKEVIRTUAL, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, "tryGetECSComponent", IsoZombieNetworkComponentPerformancePatchTest.LOOKUP, false);
method.visitTypeInsn(CHECKCAST, component);
method.visitInsn(POP);
}
/**
* {@code IsoZombie} with {@code getOwner()} and {@code setOwner()}, each looking up the
* network component, and {@code other()}, which looks up an unrelated component.
*/
private static ClassNode target()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, IsoZombieNetworkComponentPerformancePatchTest.ZOMBIE, null, "java/lang/Object", null);
MethodVisitor getOwner = cw.visitMethod(ACC_PUBLIC, "getOwner", "()Lzombie/core/raknet/UdpConnection;", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(getOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
getOwner.visitInsn(ACONST_NULL);
getOwner.visitInsn(ARETURN);
getOwner.visitMaxs(0, 0);
MethodVisitor setOwner = cw.visitMethod(ACC_PUBLIC, "setOwner", "()V", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(setOwner, IsoZombieNetworkComponentPerformancePatchTest.COMPONENT);
setOwner.visitInsn(RETURN);
setOwner.visitMaxs(0, 0);
MethodVisitor other = cw.visitMethod(ACC_PUBLIC, "other", "()V", null, null);
IsoZombieNetworkComponentPerformancePatchTest.lookup(other, IsoZombieNetworkComponentPerformancePatchTest.OTHER);
other.visitInsn(RETURN);
other.visitMaxs(0, 0);
cw.visitEnd();
ClassNode node = new ClassNode();
new ClassReader(cw.toByteArray()).accept(node, 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 List<MethodInsnNode> calls(MethodNode method, String name)
{
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction instanceof MethodInsnNode call && call.name.equals(name)) calls.add(call);
}
return calls;
}
private static ClassNode patched()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.target();
new IsoZombieNetworkComponentPerformancePatch().apply(node);
return node;
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieNetworkComponentPerformancePatch().anchor().verify(IsoZombieNetworkComponentPerformancePatchTest.target());
}
@Test
void addsAPrivateFieldAndAnAccessor()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
assertEquals(1, node.fields.size());
assertEquals("zomboidForge$networkComponent", node.fields.getFirst().name);
assertEquals("L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", node.fields.getFirst().desc);
assertTrue((node.fields.getFirst().access & ACC_PRIVATE) != 0);
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(node, "zomboidForge$networkComponent");
assertTrue((accessor.access & ACC_PRIVATE) != 0);
assertEquals("()L" + IsoZombieNetworkComponentPerformancePatchTest.COMPONENT + ";", accessor.desc);
}
@Test
void accessorFillsTheFieldOnceFromTheLookup()
{
MethodNode accessor = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "zomboidForge$networkComponent");
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(accessor, "tryGetECSComponent").size());
int reads = 0;
int writes = 0;
for (AbstractInsnNode instruction : accessor.instructions)
{
if (instruction instanceof FieldInsnNode field && field.getOpcode() == GETFIELD) reads++;
if (instruction instanceof FieldInsnNode field && field.getOpcode() == PUTFIELD) writes++;
}
assertEquals(1, reads);
assertEquals(1, writes);
}
@Test
void replacesEveryLookupOfTheNetworkComponentWithTheAccessor()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
for (String name : List.of("getOwner", "setOwner"))
{
MethodNode method = IsoZombieNetworkComponentPerformancePatchTest.method(node, name);
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(method, "tryGetECSComponent").isEmpty(), name);
List<MethodInsnNode> accessors = IsoZombieNetworkComponentPerformancePatchTest.calls(method, "zomboidForge$networkComponent");
assertEquals(1, accessors.size(), name);
assertEquals(INVOKESPECIAL, accessors.getFirst().getOpcode(), name);
// No class literal and no cast remain: the accessor returns the component itself.
for (AbstractInsnNode instruction : method.instructions)
{
assertFalse(instruction instanceof LdcInsnNode, name);
assertFalse(instruction.getOpcode() == CHECKCAST, name);
}
}
}
@Test
void leavesLookupsOfOtherComponentsAlone()
{
MethodNode other = IsoZombieNetworkComponentPerformancePatchTest.method(IsoZombieNetworkComponentPerformancePatchTest.patched(), "other");
assertEquals(1, IsoZombieNetworkComponentPerformancePatchTest.calls(other, "tryGetECSComponent").size());
assertTrue(IsoZombieNetworkComponentPerformancePatchTest.calls(other, "zomboidForge$networkComponent").isEmpty());
}
@Test
void patchedClassIsWrittenWithComputedFrames()
{
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
IsoZombieNetworkComponentPerformancePatchTest.patched().accept(writer);
assertTrue(writer.toByteArray().length > 0);
}
@Test
void failsWhenTheGameClassAlreadyHasTheMember()
{
ClassNode node = IsoZombieNetworkComponentPerformancePatchTest.patched();
assertThrows(IllegalStateException.class, () -> new IsoZombieNetworkComponentPerformancePatch().apply(node));
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieNetworkComponentPerformancePatch patch = new IsoZombieNetworkComponentPerformancePatch();
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")));
}
}
@@ -0,0 +1,162 @@
package dev.overlord.zomboidforge.compat.b42.perf;
import dev.overlord.zomboidforge.patcher.GameVersion;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
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.ICONST_0;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.ISTORE;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.V25;
class IsoZombieVehiclePerformancePatchTest
{
private static final String VECTOR = "org/joml/Vector3f";
private static final String CALL = "(L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";";
/**
* {@code IsoZombie} with a reduced {@code isVehicleBetween}: one call to
* {@code BaseVehicle.getIntersectPoint}, result ignored, then {@code return intersect}.
*/
private static ClassNode target()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, "zombie/characters/IsoZombie", null, "java/lang/Object", null);
MethodVisitor m = cw.visitMethod(ACC_PRIVATE, "isVehicleBetween", "(FFF)Z", null, null);
m.visitInsn(ICONST_0);
m.visitVarInsn(ISTORE, 4);
m.visitInsn(ACONST_NULL);
m.visitTypeInsn(CHECKCAST, "zombie/vehicles/BaseVehicle");
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitInsn(ACONST_NULL);
m.visitMethodInsn(INVOKEVIRTUAL, "zombie/vehicles/BaseVehicle", "getIntersectPoint", IsoZombieVehiclePerformancePatchTest.CALL, false);
m.visitInsn(POP);
m.visitVarInsn(ILOAD, 4);
m.visitInsn(IRETURN);
m.visitMaxs(0, 0);
cw.visitEnd();
ClassNode node = new ClassNode();
new ClassReader(cw.toByteArray()).accept(node, 0);
return node;
}
private static MethodNode isVehicleBetween(ClassNode node)
{
return node.methods.stream().filter(method -> method.name.equals("isVehicleBetween")).findFirst().orElseThrow();
}
/** Opcodes of the real instructions: no labels, line numbers, or frames. */
private static List<Integer> opcodes(MethodNode method)
{
List<Integer> opcodes = new ArrayList<>();
for (AbstractInsnNode instruction : method.instructions) {
if (instruction.getOpcode() != -1) opcodes.add(instruction.getOpcode());
}
return opcodes;
}
@Test
void anchorMatchesTheTarget()
{
new IsoZombieVehiclePerformancePatch().anchor().verify(IsoZombieVehiclePerformancePatchTest.target());
}
@Test
void returnsFalseFirstWhenTheCellHasNoVehicles()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<Integer> opcodes = IsoZombieVehiclePerformancePatchTest.opcodes(IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node));
assertEquals(
List.of(GETSTATIC, GETFIELD, INVOKEVIRTUAL, INVOKEINTERFACE, IFEQ, ICONST_0, IRETURN),
opcodes.subList(0, 7)
);
}
@Test
void jumpsOverTheEarlyReturnToTheOriginalCode()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
MethodNode method = IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node);
JumpInsnNode jump = Arrays.stream(method.instructions.toArray())
.filter(JumpInsnNode.class::isInstance)
.map(JumpInsnNode.class::cast)
.findFirst()
.orElseThrow();
// The label sits directly before the original first instruction, iconst_0 of "intersectVision = false".
AbstractInsnNode firstOriginal = jump.label.getNext();
while (firstOriginal.getOpcode() == -1) firstOriginal = firstOriginal.getNext();
assertEquals(ICONST_0, firstOriginal.getOpcode());
assertEquals(ISTORE, firstOriginal.getNext().getOpcode());
}
@Test
void replacesTheVirtualCallWithTheHook()
{
ClassNode node = IsoZombieVehiclePerformancePatchTest.target();
new IsoZombieVehiclePerformancePatch().apply(node);
List<MethodInsnNode> calls = new ArrayList<>();
for (AbstractInsnNode instruction : IsoZombieVehiclePerformancePatchTest.isVehicleBetween(node).instructions) {
if (instruction instanceof MethodInsnNode call && call.name.equals("getIntersectPoint")) calls.add(call);
}
assertEquals(1, calls.size());
MethodInsnNode call = calls.getFirst();
assertEquals(INVOKESTATIC, call.getOpcode());
assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks", call.owner);
assertEquals("(Lzombie/vehicles/BaseVehicle;L" + VECTOR + ";L" + VECTOR + ";L" + VECTOR + ";)L" + VECTOR + ";", call.desc);
assertFalse(call.itf);
}
@Test
void appliesOnlyToVerifiedVersions()
{
IsoZombieVehiclePerformancePatch patch = new IsoZombieVehiclePerformancePatch();
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
}
}
+4
View File
@@ -9,4 +9,8 @@ dependencies {
implementation(project(":core"))
implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
}
@@ -0,0 +1,17 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.api.ZomboidForge;
/** Hooks called by patched {@code zombie.network.GameServer} code. */
public final class ServerHooks
{
private ServerHooks() {}
/**
* Called once on the main thread, after the world is loaded, the network port is open, and
* RCON is initialized; directly before the main loop starts.
*/
public static void onServerStarted() {
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
}
}
@@ -0,0 +1,57 @@
package dev.overlord.zomboidforge.compat.b42.hooks;
import dev.overlord.zomboidforge.compat.b42.util.SegmentReach;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import zombie.core.physics.WorldSimulation;
import zombie.scripting.objects.VehicleScript;
import zombie.vehicles.BaseVehicle;
/** Hooks called by patched {@code zombie.characters.IsoZombie} code. */
public final class ZombieVehicleHooks
{
/**
* World units added to the bounding radius. Float resolution near the world coordinates
* (about 10000) is 0.001, so this covers rounding differences to the vanilla test.
*/
private static final float MARGIN = 0.1F;
private ZombieVehicleHooks() {}
/**
* Replaces the call {@code vehicle.getIntersectPoint(start, end, result)} in
* {@code IsoZombie.isVehicleBetween}. Returns what that call returns.
*
* <p>The vanilla test is 2-dimensional: {@code getLocalPos} drops the height of both
* points, and the vehicle's box is centered on its physics origin with the half extents
* {@code extents * 0.5 + centerOfMassOffset}. Whatever its rotation, the box lies inside
* the circle around that origin with the radius of its half diagonal. A segment that stays
* outside the circle cannot hit the box, so the vanilla call returns {@code null} for it
* and is skipped here.
*/
public static @Nullable Vector3f getIntersectPoint(
@NotNull BaseVehicle vehicle,
@NotNull Vector3f start,
@NotNull Vector3f end,
@Nullable Vector3f result
) {
VehicleScript script = vehicle.getScript();
Vector3f extents = script.getExtents();
Vector3f centerOfMass = script.getCenterOfMassOffset();
float halfX = extents.x * 0.5F + centerOfMass.x;
float halfZ = extents.z * 0.5F + centerOfMass.z;
float radius = (float) Math.sqrt(halfX * halfX + halfZ * halfZ) + ZombieVehicleHooks.MARGIN;
// Same position that BaseVehicle.getWorldPos and getLocalPos use for the physics origin.
float centerX = vehicle.jniTransform.origin.x + WorldSimulation.instance.offsetX;
float centerY = vehicle.jniTransform.origin.z + WorldSimulation.instance.offsetY;
if (SegmentReach.missesCircle(start.x, start.y, end.x, end.y, centerX, centerY, radius)) return null;
return vehicle.getIntersectPoint(start, end, result);
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.hooks;
import org.jetbrains.annotations.NotNullByDefault;
@@ -1,5 +1,10 @@
/**
* Build 42 runtime code: hooks that patched game classes call, and adapters between
* game classes and the version-independent {@code core} and {@code api}.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,38 @@
package dev.overlord.zomboidforge.compat.b42.util;
/** Distance checks in the XY plane. Uses no game classes, so it can be tested on its own. */
public final class SegmentReach
{
private SegmentReach() {}
/**
* Whether every point of the segment from ({@code startX}, {@code startY}) to
* ({@code endX}, {@code endY}) is farther than {@code radius} from
* ({@code centerX}, {@code centerY}).
*
* <p>False when any input is NaN. A caller that skips work only on {@code true} therefore
* still runs the full computation for such input.
*/
public static boolean missesCircle(
float startX, float startY, float endX, float endY,
float centerX, float centerY, float radius
) {
float directionX = endX - startX;
float directionY = endY - startY;
float lengthSquared = directionX * directionX + directionY * directionY;
// Position of the point on the segment closest to the center, from 0 (start) to 1 (end).
// A segment of length 0 is its start. NaN passes through every comparison unchanged.
float along = lengthSquared == 0.0F
? 0.0F
: ((centerX - startX) * directionX + (centerY - startY) * directionY) / lengthSquared;
if (along < 0.0F) along = 0.0F;
else if (along > 1.0F) along = 1.0F;
float offsetX = startX + along * directionX - centerX;
float offsetY = startY + along * directionY - centerY;
return offsetX * offsetX + offsetY * offsetY > radius * radius;
}
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.compat.b42.util;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,88 @@
package dev.overlord.zomboidforge.compat.b42.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SegmentReachTest
{
@Test
void segmentFarFromTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 10, 20, 10, 10, 0, 5));
}
@Test
void segmentThroughTheCenterDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 0, 1));
}
@Test
void segmentThatEndsBeforeTheCircleMissesEvenWhenItsLineWouldHit()
{
// The line y = 0 passes through the circle at (10, 0); the segment stops at x = 5.
assertTrue(SegmentReach.missesCircle(0, 0, 5, 0, 10, 0, 2));
}
@Test
void segmentThatStartsAfterTheCircleMissesEvenWhenItsLineWouldHit()
{
assertTrue(SegmentReach.missesCircle(15, 0, 30, 0, 10, 0, 2));
}
@Test
void segmentThatTouchesTheCircleEdgeDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(0, 5, 20, 5, 10, 0, 5));
}
@Test
void segmentJustOutsideTheCircleMisses()
{
assertTrue(SegmentReach.missesCircle(0, 5.001F, 20, 5.001F, 10, 0, 5));
}
@Test
void segmentStartingInsideTheCircleDoesNotMiss()
{
assertFalse(SegmentReach.missesCircle(10, 1, 100, 100, 10, 0, 2));
}
@Test
void segmentOfLengthZeroIsItsStart()
{
assertFalse(SegmentReach.missesCircle(10, 1, 10, 1, 10, 0, 2));
assertTrue(SegmentReach.missesCircle(50, 50, 50, 50, 10, 0, 2));
}
@Test
void diagonalSegmentIsMeasuredToItsClosestPoint()
{
// Closest point of (0,0)-(10,10) to (10,0) is (5,5), distance sqrt(50) = 7.07.
assertTrue(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.0F));
assertFalse(SegmentReach.missesCircle(0, 0, 10, 10, 10, 0, 7.2F));
}
@Test
void worksAtWorldCoordinates()
{
assertFalse(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10196, 2));
assertTrue(SegmentReach.missesCircle(10720, 10195, 10760, 10195, 10740, 10210, 2));
}
@Test
void neverMissesOnNaN()
{
float nan = Float.NaN;
assertFalse(SegmentReach.missesCircle(nan, 0, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, nan, 20, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, nan, 0, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, nan, 10, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, nan, 100, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, nan, 1));
assertFalse(SegmentReach.missesCircle(0, 0, 20, 0, 10, 100, nan));
}
}
@@ -1,5 +1,10 @@
/**
* Version-independent runtime: mod loading, events, configuration. Contains no
* references to game classes; game-specific code is in the compat modules.
*
* @noinspection UnstableApiUsage, RedundantSuppression
*/
@NotNullByDefault
package dev.overlord.zomboidforge.core;
import org.jetbrains.annotations.NotNullByDefault;
-1
View File
@@ -1,5 +1,4 @@
group=dev.overlord.zomboidforge
version=0.1.0-SNAPSHOT
# Project Zomboid version the build targets. Selects compat/b<major>/, and
# :patcher:patchServerJar fails when the server jar reports another version.
+6
View File
@@ -39,12 +39,18 @@ tasks.register<JavaExec>("patchServerJar") {
val vanillaJar = projectZomboid.serverJar
val patchedJar = layout.buildDirectory.file("server/projectzomboid.jar")
val expectedVersion = projectZomboid.version
// Simple class names of patches to skip, e.g. -Pzf.disabledPatches=ServerStartedPatch (debug builds).
val disabledPatches = providers.gradleProperty("zf.disabledPatches").orElse("")
inputs.property("disabledPatches", disabledPatches)
inputs.file(vanillaJar).withPropertyName("vanillaJar")
inputs.property("expectedVersion", expectedVersion)
outputs.file(patchedJar).withPropertyName("patchedJar")
classpath = sourceSets.main.get().runtimeClasspath + serverPatches
mainClass = "dev.overlord.zomboidforge.patcher.JarPatcher"
jvmArgumentProviders.add(CommandLineArgumentProvider {
listOf("-Dzomboidforge.disabledPatches=${disabledPatches.get()}")
})
argumentProviders.add(CommandLineArgumentProvider {
listOf(
vanillaJar.get().asFile.absolutePath,
@@ -0,0 +1,211 @@
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
* apply when its anchor matches exactly once; otherwise the build fails, e.g. after a
* Project Zomboid update changed the surrounding code.
*/
public sealed interface Anchor
{
/**
* Fails with an {@link IllegalStateException} unless this anchor matches exactly once in
* {@code node}.
*/
void verify(ClassNode node);
/** A method of the target class, identified by name and descriptor. */
record Method(String name, String desc) implements Anchor
{
public MethodNode resolve(ClassNode node)
{
List<MethodNode> matches = node.methods.stream()
.filter(method -> method.name.equals(this.name) && method.desc.equals(this.desc))
.toList();
if (matches.size() != 1) throw new IllegalStateException("Expected exactly one method '" + node.name + "." + this.name + this.desc + "', found " + matches.size());
return matches.getFirst();
}
@Override
public void verify(ClassNode node) { this.resolve(node); }
}
/** A static or instance call to {@code owner.name desc} inside the method {@code in}. */
record Call(Method in, String owner, String name, String desc) implements Anchor
{
public MethodInsnNode resolve(ClassNode node)
{
List<MethodInsnNode> matches = new ArrayList<>();
for (AbstractInsnNode instruction : this.in.resolve(node).instructions) {
if (this.isCall(instruction)) matches.add((MethodInsnNode) instruction);
}
if (matches.size() != 1) {
throw new IllegalStateException(
"Expected exactly one call to '" + this.owner + "." + this.name + this.desc
+ "' in '" + node.name + "." + this.in.name() + this.in.desc() + "', found " + matches.size()
);
}
return matches.getFirst();
}
@Override
public void verify(ClassNode node) { this.resolve(node); }
private boolean isCall(AbstractInsnNode instruction)
{
return instruction instanceof MethodInsnNode call
&& call.owner.equals(this.owner)
&& call.name.equals(this.name)
&& 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 + "'"; }
}
}
}
@@ -1,12 +1,26 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ApiStatus.Internal;
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();
/**
* The landmark in {@link #target()} that the patch depends on. {@link JarPatcher} verifies
* it before calling {@link #apply}, so the build fails when a game update removed it.
*/
Anchor anchor();
/** The runtime method the patched code calls, or {@code null} when the patch calls none. */
@Nullable Hook hook();
/**
* Whether the patch applies to the given game version. Patches that differ
* between minor versions of the same Build provide one implementation per
@@ -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.
@@ -0,0 +1,7 @@
package dev.overlord.zomboidforge.patcher;
/**
* A {@code public static} method of the runtime module that a patched game class calls.
* {@code owner} is an internal name, e.g. {@code dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks}.
*/
public record Hook(String owner, String name, String desc) {}
@@ -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,13 +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.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@@ -26,6 +22,9 @@ public final class JarPatcher
{
private static final String VERSIONED_PREFIX = "META-INF/versions/";
/** System property: comma-separated simple class names of patches to skip, e.g. {@code ServerStartedPatch}. */
static final String DISABLED_PATCHES_PROPERTY = "zomboidforge.disabledPatches";
private final Map<String, List<ClassPatch>> patchesByEntry = new LinkedHashMap<>();
public JarPatcher(Collection<? extends ClassPatch> patches) {
@@ -39,7 +38,8 @@ public final class JarPatcher
/**
* Usage: {@code JarPatcher <vanilla.jar> <patched.jar> <expected-version>}. Loads the
* single {@link PatchSet} on the class path and applies every patch that applies to
* the jar's game version.
* the jar's game version, except those named in the system property
* {@value #DISABLED_PATCHES_PROPERTY} (for debug builds).
*/
static void main(String[] args) throws IOException
{
@@ -52,7 +52,7 @@ public final class JarPatcher
Path patchedJar = Path.of(args[1]);
String expectedVersion = args[2];
GameVersion version = readGameVersion(vanillaJar);
GameVersion version = JarPatcher.readGameVersion(vanillaJar);
if (!version.matches(expectedVersion)) {
throw new IllegalStateException(
"Server jar is Project Zomboid " + version +
@@ -61,14 +61,16 @@ public final class JarPatcher
);
}
PatchSet patchSet = loadPatchSet();
List<ClassPatch> applicable = applicablePatches(patchSet, version);
Set<String> disabled = JarPatcher.parseNames(System.getProperty(JarPatcher.DISABLED_PATCHES_PROPERTY, ""));
PatchSet patchSet = JarPatcher.loadPatchSet();
List<ClassPatch> applicable = JarPatcher.applicablePatches(patchSet, version, disabled);
int patchedClasses = new JarPatcher(applicable).patch(vanillaJar, patchedJar);
int patchedClasses = new JarPatcher(applicable).patch(vanillaJar, patchedJar);
System.out.println(
"Project Zomboid " + version + ": patched " + patchedClasses + " class(es) with "
+ applicable.size() + " of " + patchSet.patches().size() + " patch(es) -> " + patchedJar
"Project Zomboid " + version + ": patched " + patchedClasses + " class(es) with "
+ applicable.size() + " of " + patchSet.patches().size() + " patch(es) -> " + patchedJar
);
if (!disabled.isEmpty()) System.out.println("Disabled patches: " + JarPatcher.quoted(disabled));
}
/** Reads the game version from zombie/core/Core.class in the jar. */
@@ -76,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);
@@ -86,18 +88,48 @@ public final class JarPatcher
/** Patches of {@code patchSet} that apply to {@code version}, in application order. */
public static List<ClassPatch> applicablePatches(PatchSet patchSet, GameVersion version)
{
if (patchSet.build() != version.major()) {
throw new IllegalStateException(
"Patch set is for Build " + patchSet.build()
+ ", but the server jar is Project Zomboid " + version
);
return JarPatcher.applicablePatches(patchSet, version, Set.of());
}
/**
* Patches of {@code patchSet} that apply to {@code version} and are not named in
* {@code disabled} (simple class names), in application order. Fails when a name in
* {@code disabled} matches no patch of the set, so a typo does not silently keep a patch.
*/
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 + ".");
Set<String> unknown = new TreeSet<>(disabled);
patchSet.patches().forEach(patch -> unknown.remove(patch.getClass().getSimpleName()));
if (!unknown.isEmpty()) {
throw new IllegalStateException("Cannot disable unknown patch(es) " + JarPatcher.quoted(unknown));
}
return patchSet.patches().stream()
.filter(patch -> !disabled.contains(patch.getClass().getSimpleName()))
.filter(patch -> patch.appliesTo(version))
.toList();
}
/** Splits a comma-separated list of names; blank entries are ignored. */
static Set<String> parseNames(String list)
{
Set<String> names = new TreeSet<>();
for (String name : list.split(","))
{
if (!name.isBlank()) names.add(name.trim());
}
return names;
}
private static String quoted(Set<String> names) {
return String.join(", ", names.stream().map(name -> "'" + name + "'").toList());
}
private static PatchSet loadPatchSet()
{
List<PatchSet> patchSets = ServiceLoader.load(PatchSet.class)
@@ -120,7 +152,7 @@ public final class JarPatcher
ZipFile jar = new ZipFile(in.toFile());
ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(out))
) {
checkTargets(jar);
this.checkTargets(jar);
int patched = 0;
for (Enumeration<? extends ZipEntry> entries = jar.entries(); entries.hasMoreElements();)
@@ -163,9 +195,7 @@ public final class JarPatcher
.filter(n -> patchesByEntry.containsKey(n.substring(n.indexOf('/', VERSIONED_PREFIX.length()) + 1)))
.forEach(n -> problems.add("'" + n + "' overrides a patched class."));
if (!problems.isEmpty()) {
throw new IllegalStateException("Cannot patch '" + jar.getName() + "':\n " + String.join("\n ", problems));
}
if (!problems.isEmpty()) throw new IllegalStateException("Cannot patch '" + jar.getName() + "':\n " + String.join("\n ", problems));
}
private static byte[] transform(ZipFile jar, byte[] bytes, List<ClassPatch> patches)
@@ -174,16 +204,23 @@ public final class JarPatcher
new ClassReader(bytes).accept(node, 0);
for (ClassPatch patch : patches) {
JarPatcher.verifyAnchor(patch, node);
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();
}
private static byte[] read(ZipFile jar, String entryName)
private static void verifyAnchor(ClassPatch patch, ClassNode node)
{
try { patch.anchor().verify(node); }
catch (IllegalStateException e) { throw new IllegalStateException("'" + patch.getClass().getSimpleName() + "': " + e.getMessage(), e); }
}
private static byte @Nullable [] read(ZipFile jar, String entryName)
{
ZipEntry entry = jar.getEntry(entryName);
if (entry == null) return null;
@@ -0,0 +1,58 @@
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.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
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.
*/
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;
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 + "'.");
this.target = Objects.requireNonNull(target);
this.anchor = Objects.requireNonNull(anchor);
this.hook = hook;
}
@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)
{
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
)
);
}
}
@@ -0,0 +1,52 @@
package dev.overlord.zomboidforge.patcher.Patches;
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.Nullable;
import org.objectweb.asm.tree.ClassNode;
import java.util.Objects;
/**
* Base class for patches that make a vanilla method cheaper without changing what it returns
* or does. Unlike {@link HookInjectionPatch}, which only inserts a call, a performance patch
* may rewrite instructions of the anchor method or add fields to the target class, so
* {@link #apply} is left to the subclass.
*
* <p>{@link #appliesTo} has no default: every performance patch names the game versions it was
* verified on.
*/
public abstract class PerformancePatch implements ClassPatch
{
private final String target;
private final Anchor anchor;
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, Anchor anchor, @Nullable Hook hook)
{
this.target = Objects.requireNonNull(target);
this.anchor = Objects.requireNonNull(anchor);
this.hook = hook;
}
@Override
public final String target() { return this.target; }
@Override
public final Anchor anchor() { return this.anchor; }
@Override
public final @Nullable Hook hook() { return this.hook; }
@Override
public abstract boolean appliesTo(GameVersion version);
@Override
public abstract void apply(ClassNode node);
}
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.patcher.Patches;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,5 @@
/** @noinspection UnstableApiUsage, RedundantSuppression */
@NotNullByDefault
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.NotNullByDefault;
@@ -0,0 +1,195 @@
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
{
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();
node.name = "t/Target";
MethodNode run = new MethodNode(ACC_STATIC, "run", "()V", null, null);
for (int i = 0; i < callsToGo; i++) {
run.instructions.add(new MethodInsnNode(INVOKESTATIC, "t/Dep", "go", "()V", false));
}
run.visitInsn(RETURN);
node.methods.add(run);
return node;
}
@Test
void methodAnchorMatchesExactlyOnce()
{
assertDoesNotThrow(() -> AnchorTest.RUN.verify(AnchorTest.classWithRun(0)));
ClassNode duplicate = AnchorTest.classWithRun(0);
duplicate.methods.add(new MethodNode(ACC_STATIC, "run", "()V", null, null));
assertEquals(
"Expected exactly one method 't/Target.run()V', found 2",
assertThrows(IllegalStateException.class, () -> AnchorTest.RUN.verify(duplicate)).getMessage()
);
assertThrows(IllegalStateException.class, () -> new Anchor.Method("run", "(I)V").verify(AnchorTest.classWithRun(0)));
}
@Test
void callAnchorMatchesExactlyOnce()
{
assertDoesNotThrow(() -> AnchorTest.CALL.verify(AnchorTest.classWithRun(1)));
assertTrue(
assertThrows(IllegalStateException.class, () -> AnchorTest.CALL.verify(AnchorTest.classWithRun(0)))
.getMessage().contains("call to 't/Dep.go()V' in 't/Target.run()V', found 0")
);
assertTrue(
assertThrows(IllegalStateException.class, () -> AnchorTest.CALL.verify(AnchorTest.classWithRun(2)))
.getMessage().contains("found 2")
);
}
@Test
void callAnchorIgnoresOtherMethods()
{
ClassNode node = AnchorTest.classWithRun(1);
MethodNode other = new MethodNode(ACC_STATIC, "other", "()V", null, null);
other.instructions.add(new MethodInsnNode(INVOKESTATIC, "t/Dep", "go", "()V", false));
other.visitInsn(RETURN);
node.methods.add(other);
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());
}
}
@@ -4,58 +4,127 @@ import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ApplicablePatchesTest {
private static ClassPatch patch(String name, int sinceMinor) {
return new ClassPatch() {
class ApplicablePatchesTest
{
private static final class FirstPatch implements ClassPatch
{
@Override
public String target() { return "t/First"; }
@Override
public Anchor anchor() { return new Anchor.Method("m", "()V"); }
@Override
public Hook hook() { return null; }
@Override
public void apply(ClassNode node) {}
}
private static final class SecondPatch implements ClassPatch
{
@Override
public String target() { return "t/Second"; }
@Override
public Anchor anchor() { return new Anchor.Method("m", "()V"); }
@Override
public Hook hook() { return null; }
@Override
public void apply(ClassNode node) {}
}
private static ClassPatch patch(String name, int sinceMinor)
{
return new ClassPatch()
{
@Override
public String target() {
return name;
}
public String target() { return name; }
@Override
public boolean appliesTo(GameVersion version) {
return version.isAtLeast(42, sinceMinor);
}
public Anchor anchor() { return new Anchor.Method("m", "()V"); }
@Override
public void apply(ClassNode node) {
}
public Hook hook() { return null; }
@Override
public boolean appliesTo(GameVersion version) { return version.isAtLeast(42, sinceMinor); }
@Override
public void apply(ClassNode node) {}
};
}
private static PatchSet build42(List<ClassPatch> patches) {
private static PatchSet build42(List<ClassPatch> patches)
{
return new PatchSet() {
@Override
public int build() {
return 42;
}
public int build() { return 42; }
@Override
public List<ClassPatch> patches() {
return patches;
}
public List<ClassPatch> patches() { return patches; }
};
}
@Test
void keepsOrderAndSkipsPatchesForOtherVersions() {
ClassPatch old = patch("t/Old", 0);
ClassPatch fromTwenty = patch("t/New", 20);
ClassPatch fromTwentyTwo = patch("t/Newer", 22);
PatchSet patchSet = build42(List.of(old, fromTwenty, fromTwentyTwo));
void keepsOrderAndSkipsPatchesForOtherVersions()
{
ClassPatch old = ApplicablePatchesTest.patch("t/Old", 0);
ClassPatch fromTwenty = ApplicablePatchesTest.patch("t/New", 20);
ClassPatch fromTwentyTwo = ApplicablePatchesTest.patch("t/Newer", 22);
PatchSet patchSet = ApplicablePatchesTest.build42(List.of(old, fromTwenty, fromTwentyTwo));
assertEquals(List.of(old, fromTwenty), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 21, 0)));
assertEquals(List.of(old), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 19, 2)));
}
@Test
void rejectsPatchSetOfAnotherBuild() {
PatchSet patchSet = build42(List.of());
assertThrows(IllegalStateException.class,
() -> JarPatcher.applicablePatches(patchSet, new GameVersion(43, 0, 0)));
void rejectsPatchSetOfAnotherBuild()
{
PatchSet patchSet = ApplicablePatchesTest.build42(List.of());
assertThrows(
IllegalStateException.class,
() -> JarPatcher.applicablePatches(patchSet, new GameVersion(43, 0, 0))
);
}
@Test
void skipsDisabledPatchesByClassName()
{
ClassPatch first = new FirstPatch();
ClassPatch second = new SecondPatch();
PatchSet patchSet = ApplicablePatchesTest.build42(List.of(first, second));
assertEquals(List.of(second), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 21, 0), Set.of("FirstPatch")));
assertEquals(List.of(), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 21, 0), Set.of("FirstPatch", "SecondPatch")));
}
@Test
void rejectsDisabledNameThatMatchesNoPatch()
{
PatchSet patchSet = ApplicablePatchesTest.build42(List.of(new FirstPatch()));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> JarPatcher.applicablePatches(patchSet, new GameVersion(42, 21, 0), Set.of("FirstPatch", "TypoPatch"))
);
assertEquals("Cannot disable unknown patch(es) 'TypoPatch'", e.getMessage());
}
@Test
void parsesCommaSeparatedNames()
{
assertEquals(Set.of("A", "B"), JarPatcher.parseNames(" A, B ,,"));
assertTrue(JarPatcher.parseNames("").isEmpty());
}
}
@@ -0,0 +1,174 @@
package dev.overlord.zomboidforge.patcher;
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
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.Map;
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.DUP;
import static org.objectweb.asm.Opcodes.GETSTATIC;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class HookInjectionPatchTest
{
private static final Anchor.Call ANCHOR = new Anchor.Call(
new Anchor.Method("run", "()V"), "t/Dep", "anchor", "()V"
);
private static final Hook HOOK = new Hook("t/Hooks", "hook", "()V");
@TempDir
Path dir;
/** Target class with {@code run()}: {@code Dep.anchor(); Dep.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 run = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "()V", null, null);
run.visitMethodInsn(INVOKESTATIC, "t/Dep", "anchor", "()V", false);
run.visitMethodInsn(INVOKESTATIC, "t/Dep", "after", "()V", false);
run.visitInsn(RETURN);
run.visitMaxs(0, 0);
cw.visitEnd();
return cw.toByteArray();
}
/** Class with static methods {@code names}, each appending its own name to {@code log}. */
private static byte[] recorder(String className, List<String> names)
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, className, null, "java/lang/Object", null);
for (String name : names)
{
MethodVisitor m = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, name, "()V", null, null);
m.visitFieldInsn(GETSTATIC, "t/Log", "log", "Ljava/lang/StringBuilder;");
m.visitLdcInsn(name + ";");
m.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
m.visitInsn(POP);
m.visitInsn(RETURN);
m.visitMaxs(0, 0);
}
cw.visitEnd();
return cw.toByteArray();
}
private static byte[] log()
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
cw.visit(V25, ACC_PUBLIC, "t/Log", null, "java/lang/Object", null);
cw.visitField(ACC_PUBLIC | ACC_STATIC, "log", "Ljava/lang/StringBuilder;", null, null).visitEnd();
MethodVisitor init = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
init.visitTypeInsn(NEW, "java/lang/StringBuilder");
init.visitInsn(DUP);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
init.visitFieldInsn(PUTSTATIC, "t/Log", "log", "Ljava/lang/StringBuilder;");
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
cw.visitEnd();
return cw.toByteArray();
}
private Path jar(Map<String, byte[]> entries) throws Exception
{
Path jar = Files.createTempFile(this.dir, "in", ".jar");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar)))
{
for (Map.Entry<String, byte[]> e : entries.entrySet()) {
zip.putNextEntry(new ZipEntry(e.getKey()));
zip.write(e.getValue());
zip.closeEntry();
}
}
return jar;
}
private static final class TestPatch extends HookInjectionPatch
{
TestPatch() {
super("t/Target", HookInjectionPatchTest.ANCHOR, HookInjectionPatchTest.HOOK);
}
}
@Test
void callsHookDirectlyAfterAnchor() throws Exception
{
Path in = this.jar(Map.of(
"t/Target.class", HookInjectionPatchTest.target(),
"t/Dep.class", recorder("t/Dep", List.of("anchor", "after")),
"t/Hooks.class", recorder("t/Hooks", List.of("hook")),
"t/Log.class", log()
));
Path out = this.dir.resolve("patched.jar");
assertEquals(1, new JarPatcher(List.of(new TestPatch())).patch(in, out));
try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, null))
{
loader.loadClass("t.Target").getMethod("run").invoke(null);
Object log = loader.loadClass("t.Log").getField("log").get(null);
assertEquals("anchor;hook;after;", log.toString());
}
}
@Test
void reportsPatchAndAnchorWhenAnchorIsMissing() throws Exception
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null);
MethodVisitor run = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "()V", null, null);
run.visitInsn(RETURN);
run.visitMaxs(0, 0);
cw.visitEnd();
Path in = this.jar(Map.of("t/Target.class", cw.toByteArray()));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(new TestPatch())).patch(in, this.dir.resolve("out.jar"))
);
assertEquals(
"'TestPatch': Expected exactly one call to 't/Dep.anchor()V' in 't/Target.run()V', found 0",
e.getMessage()
);
}
@Test
void rejectsHookWithArguments()
{
assertThrows(IllegalArgumentException.class, () -> new HookInjectionPatch(
"t/Target", HookInjectionPatchTest.ANCHOR, new Hook("t/Hooks", "hook", "(I)V")
) {});
}
}
@@ -45,9 +45,13 @@ class JarPatcherTest
private static final ClassPatch ADD_PICK = new ClassPatch()
{
@Override
public String target() {
return "t/Target";
}
public String target() { return "t/Target"; }
@Override
public Anchor anchor() { return new Anchor.Method("<init>", "()V"); }
@Override
public Hook hook() { return null; }
@Override
public void apply(ClassNode node)
@@ -59,12 +63,12 @@ class JarPatcherTest
m.visitVarInsn(ILOAD, 0);
m.visitJumpInsn(IFEQ, elseBranch);
newInstance(m, "t/A");
JarPatcherTest.newInstance(m, "t/A");
m.visitJumpInsn(GOTO, end);
m.visitLabel(elseBranch);
newInstance(m, "t/B");
JarPatcherTest.newInstance(m, "t/B");
m.visitLabel(end);
m.visitInsn(ARETURN);
@@ -78,7 +82,7 @@ class JarPatcherTest
@Test
void patchesTargetAndCopiesEverythingElse() throws Exception
{
Path in = jar(Map.of(
Path in = this.jar(Map.of(
"t/Base.class", classBytes("t/Base", "java/lang/Object"),
"t/A.class", classBytes("t/A", "t/Base"),
"t/B.class", classBytes("t/B", "t/Base"),
@@ -86,17 +90,17 @@ class JarPatcherTest
"media/readme.txt", "untouched".getBytes()
));
Path out = dir.resolve("out/patched.jar");
Path out = this.dir.resolve("out/patched.jar");
assertEquals(1, new JarPatcher(List.of(ADD_PICK)).patch(in, out));
assertEquals(1, new JarPatcher(List.of(JarPatcherTest.ADD_PICK)).patch(in, out));
try (JarFile original = new JarFile(in.toFile()); JarFile patched = new JarFile(out.toFile()))
{
for (String name : List.of("t/Base.class", "t/A.class", "t/B.class", "media/readme.txt"))
{
assertArrayEquals(
read(original, name),
read(patched, name),
JarPatcherTest.read(original, name),
JarPatcherTest.read(patched, name),
name
);
}
@@ -114,11 +118,11 @@ class JarPatcherTest
@Test
void failsWhenTargetIsMissing() throws IOException
{
Path in = jar(Map.of("t/Other.class", classBytes("t/Other", "java/lang/Object")));
Path in = this.jar(Map.of("t/Other.class", JarPatcherTest.classBytes("t/Other", "java/lang/Object")));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(ADD_PICK)).patch(in, dir.resolve("out.jar"))
() -> new JarPatcher(List.of(JarPatcherTest.ADD_PICK)).patch(in, this.dir.resolve("out.jar"))
);
assertTrue(e.getMessage().contains("'t/Target.class' not found"), e.getMessage());
@@ -127,17 +131,53 @@ class JarPatcherTest
@Test
void failsWhenTargetHasMultiReleaseOverride() throws IOException
{
byte[] target = classBytes("t/Target", "java/lang/Object");
Path in = jar(Map.of("t/Target.class", target, "META-INF/versions/21/t/Target.class", target));
byte[] target = JarPatcherTest.classBytes("t/Target", "java/lang/Object");
Path in = this.jar(Map.of("t/Target.class", target, "META-INF/versions/21/t/Target.class", target));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(ADD_PICK)).patch(in, dir.resolve("out.jar"))
() -> new JarPatcher(List.of(JarPatcherTest.ADD_PICK)).patch(in, this.dir.resolve("out.jar"))
);
assertTrue(e.getMessage().contains("overrides a patched class"), e.getMessage());
}
@Test
void failsWhenAnchorIsMissing() throws IOException
{
ClassPatch missingAnchor = new ClassPatch()
{
@Override
public String target() {
return "t/Target";
}
@Override
public Anchor anchor() {
return new Anchor.Method("gone", "()V");
}
@Override
public Hook hook() {
return null;
}
@Override
public void apply(ClassNode node) {
throw new AssertionError("apply must not run when the anchor is missing");
}
};
Path in = this.jar(Map.of("t/Target.class", JarPatcherTest.classBytes("t/Target", "java/lang/Object")));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(missingAnchor)).patch(in, this.dir.resolve("out.jar"))
);
assertTrue(e.getMessage().contains("Expected exactly one method 't/Target.gone()V', found 0"), e.getMessage());
}
private static void newInstance(MethodVisitor m, String type) {
m.visitTypeInsn(NEW, type);
m.visitInsn(DUP);
@@ -161,7 +201,7 @@ class JarPatcherTest
private Path jar(Map<String, byte[]> entries) throws IOException
{
Path jar = Files.createTempFile(dir, "in", ".jar");
Path jar = Files.createTempFile(this.dir, "in", ".jar");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar)))
{