From 2b94a493527aa7bb0f6d796648068aec33a5e7ac Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 30 Sep 2026 21:59:22 +0200 Subject: [PATCH] Add support for anchors, hooks, and hook injection in patching logic with comprehensive tests. Added onServerStarted Hook and Patch. --- Dockerfile | 4 + compat/b42/patches/build.gradle.kts | 6 + .../compat/b42/patches/B42PatchSet.java | 15 +- .../b42/patches/ServerStartedPatch.java | 26 +++ .../compat/b42/patches/HookExistenceTest.java | 104 +++++++++++ .../compat/b42/patches/NamingRulesTest.java | 80 ++++++++ .../b42/patches/PatchSetRegistrationTest.java | 47 +++++ .../b42/patches/support/PackageScan.java | 68 +++++++ .../compat/b42/hooks/ServerHooks.java | 17 ++ patcher/build.gradle.kts | 6 + .../overlord/zomboidforge/patcher/Anchor.java | 76 ++++++++ .../zomboidforge/patcher/ClassPatch.java | 10 + .../overlord/zomboidforge/patcher/Hook.java | 7 + .../patcher/HookInjectionPatch.java | 54 ++++++ .../zomboidforge/patcher/JarPatcher.java | 69 +++++-- .../zomboidforge/patcher/AnchorTest.java | 78 ++++++++ .../patcher/ApplicablePatchesTest.java | 123 ++++++++++--- .../patcher/HookInjectionPatchTest.java | 172 ++++++++++++++++++ .../zomboidforge/patcher/JarPatcherTest.java | 72 ++++++-- 19 files changed, 972 insertions(+), 62 deletions(-) create mode 100644 compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStartedPatch.java create mode 100644 compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/HookExistenceTest.java create mode 100644 compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/NamingRulesTest.java create mode 100644 compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/PatchSetRegistrationTest.java create mode 100644 compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/PackageScan.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/Anchor.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/Hook.java create mode 100644 patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookInjectionPatch.java create mode 100644 patcher/src/test/java/dev/overlord/zomboidforge/patcher/AnchorTest.java create mode 100644 patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java diff --git a/Dockerfile b/Dockerfile index c9571b1..6ea2e67 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,6 +15,8 @@ # 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="" @@ -55,10 +57,12 @@ COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar # the build the fallback version 0.0.0-prerelease (the image has no git history). 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 ------------------------------------------------------------ diff --git a/compat/b42/patches/build.gradle.kts b/compat/b42/patches/build.gradle.kts index 0a309a5..482cdf7 100644 --- a/compat/b42/patches/build.gradle.kts +++ b/compat/b42/patches/build.gradle.kts @@ -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) } diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java index fa85aac..87afbc7 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/B42PatchSet.java @@ -6,16 +6,15 @@ 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 PATCHES = List.of(); +public final class B42PatchSet implements PatchSet +{ + private static final List PATCHES = List.of( + new ServerStartedPatch() + ); @Override - public int build() { - return 42; - } + public int build() { return 42; } @Override - public List patches() { - return PATCHES; - } + public List patches() { return B42PatchSet.PATCHES; } } diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStartedPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStartedPatch.java new file mode 100644 index 0000000..95e1539 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStartedPatch.java @@ -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.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); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/HookExistenceTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/HookExistenceTest.java new file mode 100644 index 0000000..6583035 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/HookExistenceTest.java @@ -0,0 +1,104 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +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 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"; + } + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/NamingRulesTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/NamingRulesTest.java new file mode 100644 index 0000000..8ce223b --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/NamingRulesTest.java @@ -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.Type; +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 String PATCHES_PACKAGE = "dev/overlord/zomboidforge/compat/b42/patches"; + private static final String HOOKS_PACKAGE = "dev/overlord/zomboidforge/compat/b42/hooks"; + + private static final String PATCH_SET = "B42PatchSet"; + + @Test + void patchClassesEndInPatch() throws Exception + { + List problems = new ArrayList<>(); + List names = PackageScan.topLevelClassNames(NamingRulesTest.PATCHES_PACKAGE); + + assertFalse(names.isEmpty(), "No classes found in '" + NamingRulesTest.PATCHES_PACKAGE + "'"); + + for (String name : names) + { + if (!name.equals(NamingRulesTest.PATCH_SET) && !name.endsWith("Patch")) { + problems.add("'" + name + "' must end in 'Patch' (or be '" + NamingRulesTest.PATCH_SET + "')"); + } + } + + assertTrue(problems.isEmpty(), () -> String.join("\n", problems)); + } + + @Test + void hookClassesEndInHooksAndExposeOnlyPublicStaticVoidMethods() throws Exception + { + List problems = new ArrayList<>(); + List 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("")) continue; + + if (method.name.equals("")) + { + 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 || Type.getReturnType(method.desc) != Type.VOID_TYPE) { + problems.add("'" + name + "." + method.name + method.desc + "' must be public static and return void"); + } + } + } + + assertTrue(problems.isEmpty(), () -> String.join("\n", problems)); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/PatchSetRegistrationTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/PatchSetRegistrationTest.java new file mode 100644 index 0000000..3b5cd47 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/PatchSetRegistrationTest.java @@ -0,0 +1,47 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +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 String PATCHES_PACKAGE = "dev/overlord/zomboidforge/compat/b42/patches"; + + @Test + void everyPatchClassIsRegisteredExactlyOnce() throws Exception + { + List problems = new ArrayList<>(); + Set 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 name : PackageScan.topLevelClassNames(PatchSetRegistrationTest.PATCHES_PACKAGE)) + { + boolean abstractClass = (PackageScan.read(PatchSetRegistrationTest.PATCHES_PACKAGE + "/" + 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)); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/PackageScan.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/PackageScan.java new file mode 100644 index 0000000..7429f29 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/PackageScan.java @@ -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 topLevelClassNames(String packagePath) throws IOException, URISyntaxException + { + List names = new ArrayList<>(); + + for (URL url : Collections.list(ClassLoader.getSystemResources(packagePath))) + { + if (url.getProtocol().equals("file")) + { + try (Stream 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; + } + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java new file mode 100644 index 0000000..4b632c3 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java @@ -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 + ")."); + } +} diff --git a/patcher/build.gradle.kts b/patcher/build.gradle.kts index c07396b..dac0a09 100644 --- a/patcher/build.gradle.kts +++ b/patcher/build.gradle.kts @@ -39,12 +39,18 @@ tasks.register("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, diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Anchor.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Anchor.java new file mode 100644 index 0000000..a6be202 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Anchor.java @@ -0,0 +1,76 @@ +package dev.overlord.zomboidforge.patcher; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * 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 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 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); + } + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java index 2092099..3f2735b 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/ClassPatch.java @@ -1,5 +1,6 @@ package dev.overlord.zomboidforge.patcher; +import org.jetbrains.annotations.Nullable; import org.objectweb.asm.tree.ClassNode; /** A build-time change to one class of the vanilla server jar. */ @@ -7,6 +8,15 @@ 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 diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Hook.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Hook.java new file mode 100644 index 0000000..90d9eb5 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Hook.java @@ -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) {} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookInjectionPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookInjectionPatch.java new file mode 100644 index 0000000..e2779fd --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/HookInjectionPatch.java @@ -0,0 +1,54 @@ +package dev.overlord.zomboidforge.patcher; + +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 + ) + ); + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java index 09ed8a7..01212d2 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java @@ -14,6 +14,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; +import java.util.Set; +import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; @@ -26,6 +28,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> patchesByEntry = new LinkedHashMap<>(); public JarPatcher(Collection patches) { @@ -39,7 +44,8 @@ public final class JarPatcher /** * Usage: {@code JarPatcher }. 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 +58,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 +67,16 @@ public final class JarPatcher ); } - PatchSet patchSet = loadPatchSet(); - List applicable = applicablePatches(patchSet, version); + Set disabled = JarPatcher.parseNames(System.getProperty(JarPatcher.DISABLED_PATCHES_PROPERTY, "")); + PatchSet patchSet = JarPatcher.loadPatchSet(); + List 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. */ @@ -85,6 +93,16 @@ public final class JarPatcher /** Patches of {@code patchSet} that apply to {@code version}, in application order. */ public static List applicablePatches(PatchSet patchSet, GameVersion 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 applicablePatches(PatchSet patchSet, GameVersion version, Set disabled) { if (patchSet.build() != version.major()) { throw new IllegalStateException( @@ -93,11 +111,35 @@ public final class JarPatcher ); } + Set 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 parseNames(String list) + { + Set names = new TreeSet<>(); + + for (String name : list.split(",")) + { + if (!name.isBlank()) names.add(name.trim()); + } + + return names; + } + + private static String quoted(Set names) { + return String.join(", ", names.stream().map(name -> "'" + name + "'").toList()); + } + private static PatchSet loadPatchSet() { List patchSets = ServiceLoader.load(PatchSet.class) @@ -120,7 +162,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 entries = jar.entries(); entries.hasMoreElements();) @@ -163,9 +205,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 patches) @@ -174,6 +214,7 @@ public final class JarPatcher new ClassReader(bytes).accept(node, 0); for (ClassPatch patch : patches) { + JarPatcher.verifyAnchor(patch, node); patch.apply(node); } @@ -183,6 +224,12 @@ public final class JarPatcher return writer.toByteArray(); } + 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[] read(ZipFile jar, String entryName) { ZipEntry entry = jar.getEntry(entryName); diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/AnchorTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/AnchorTest.java new file mode 100644 index 0000000..ca30463 --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/AnchorTest.java @@ -0,0 +1,78 @@ +package dev.overlord.zomboidforge.patcher; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +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.INVOKESTATIC; +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 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)); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ApplicablePatchesTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ApplicablePatchesTest.java index b40cd6f..fc61ffe 100644 --- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ApplicablePatchesTest.java +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ApplicablePatchesTest.java @@ -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 patches) { + private static PatchSet build42(List patches) + { return new PatchSet() { @Override - public int build() { - return 42; - } + public int build() { return 42; } @Override - public List patches() { - return patches; - } + public List 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()); } } diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java new file mode 100644 index 0000000..4fd4317 --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/HookInjectionPatchTest.java @@ -0,0 +1,172 @@ +package dev.overlord.zomboidforge.patcher; + +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 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, "", "()V", null, null); + init.visitTypeInsn(NEW, "java/lang/StringBuilder"); + init.visitInsn(DUP); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "", "()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 entries) throws Exception + { + Path jar = Files.createTempFile(this.dir, "in", ".jar"); + + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar))) + { + for (Map.Entry 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") + ) {}); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/JarPatcherTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/JarPatcherTest.java index 7b08b98..10d30db 100644 --- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/JarPatcherTest.java +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/JarPatcherTest.java @@ -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("", "()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 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))) {