Add support for anchors, hooks, and hook injection in patching logic with comprehensive tests.
ci / image (42.21, public) (push) Successful in 1m43s
ci / image (42.21, public) (push) Successful in 1m43s
Added onServerStarted Hook and Patch.
This commit is contained in:
1 parent
e13132c202
commit
2b94a49352
19 files changed
+972
-62
No files matched your search
@@ -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,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<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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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) {}
|
||||
@@ -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
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<String, List<ClassPatch>> patchesByEntry = new LinkedHashMap<>();
|
||||
|
||||
public JarPatcher(Collection<? extends ClassPatch> patches) {
|
||||
@@ -39,7 +44,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 +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<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. */
|
||||
@@ -85,6 +93,16 @@ 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)
|
||||
{
|
||||
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(
|
||||
@@ -93,11 +111,35 @@ public final class JarPatcher
|
||||
);
|
||||
}
|
||||
|
||||
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 +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<? extends ZipEntry> 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<ClassPatch> 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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+96
-27
@@ -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,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<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)))
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user