diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index eb38b01..9cb564c 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -1,6 +1,9 @@ package dev.overlord.zomboidforge.compat.b42; +import dev.overlord.zomboidforge.compat.b42.patches.ServerLoadPatch; import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch; +import dev.overlord.zomboidforge.compat.b42.patches.ServerStoppingPatch; +import dev.overlord.zomboidforge.compat.b42.patches.ServerTickPatch; import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch; import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch; import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch; @@ -16,7 +19,10 @@ import java.util.List; public final class B42PatchSet implements PatchSet { private static final List PATCHES = List.of( + new ServerLoadPatch(), new ServerStartedPatch(), + new ServerTickPatch(), + new ServerStoppingPatch(), new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatch.java new file mode 100644 index 0000000..2acc66b --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatch.java @@ -0,0 +1,100 @@ +package dev.overlord.zomboidforge.compat.b42.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.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; + +/** + * Calls {@code ServerHooks.onLoad()} in {@code GameServer.main}, directly after + * {@code ServerOptions.instance.init()}, and stops the server when it returns {@code false}: + * + *
{@code
+ * if (!ServerHooks.onLoad()) {
+ *     Runtime.getRuntime().removeShutdownHook(shutdownHook);
+ *     System.exit(1);
+ * }
+ * }
+ * + * The vanilla shutdown hook saves the map on every JVM exit; before the world is loaded that + * save fails with a {@code NullPointerException} in {@code IsoMetaGrid.save()}. The inserted + * code is part of {@code GameServer}, so it reads the private field {@code shutdownHook} + * directly. + */ +public final class ServerLoadPatch implements ClassPatch +{ + private static final String TARGET = "zombie/network/GameServer"; + + private static final String SHUTDOWN_HOOK = "shutdownHook"; + private static final String SHUTDOWN_HOOK_DESC = "Ljava/lang/Thread;"; + + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("main", "([Ljava/lang/String;)V"), + "zombie/network/ServerOptions", "init", "()V" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onLoad", "()Z" + ); + + @Override + public String target() { return ServerLoadPatch.TARGET; } + @Override + public Anchor.Call anchor() { return ServerLoadPatch.ANCHOR; } + @Override + public Hook hook() { return ServerLoadPatch.HOOK; } + + @Override + public void apply(ClassNode node) + { + ServerLoadPatch.requireShutdownHookField(node); + + MethodInsnNode init = ServerLoadPatch.ANCHOR.resolve(node); + ServerLoadPatch.ANCHOR.in().resolve(node).instructions.insert(init, ServerLoadPatch.abortUnlessLoaded()); + } + + /** The abort path runs only when a mod fails, so a missing field would otherwise go unnoticed until then. */ + private static void requireShutdownHookField(ClassNode node) + { + boolean found = node.fields.stream().anyMatch(ServerLoadPatch::isShutdownHook); + + if (!found) throw new IllegalStateException("Expected the static field '" + node.name + "." + ServerLoadPatch.SHUTDOWN_HOOK + " " + ServerLoadPatch.SHUTDOWN_HOOK_DESC + "'."); + } + + private static boolean isShutdownHook(FieldNode field) + { + return field.name.equals(ServerLoadPatch.SHUTDOWN_HOOK) + && field.desc.equals(ServerLoadPatch.SHUTDOWN_HOOK_DESC) + && (field.access & Opcodes.ACC_STATIC) != 0; + } + + private static InsnList abortUnlessLoaded() + { + InsnList code = new InsnList(); + LabelNode loaded = new LabelNode(); + + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ServerLoadPatch.HOOK.owner(), ServerLoadPatch.HOOK.name(), ServerLoadPatch.HOOK.desc(), false)); + code.add(new JumpInsnNode(Opcodes.IFNE, loaded)); + + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false)); + code.add(new FieldInsnNode(Opcodes.GETSTATIC, ServerLoadPatch.TARGET, ServerLoadPatch.SHUTDOWN_HOOK, ServerLoadPatch.SHUTDOWN_HOOK_DESC)); + code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Runtime", "removeShutdownHook", "(Ljava/lang/Thread;)Z", false)); + code.add(new InsnNode(Opcodes.POP)); + + code.add(new InsnNode(Opcodes.ICONST_1)); + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "exit", "(I)V", false)); + + code.add(loaded); + + return code; + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatch.java new file mode 100644 index 0000000..8bf722f --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatch.java @@ -0,0 +1,67 @@ +package dev.overlord.zomboidforge.compat.b42.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.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; + +import java.util.List; + +/** + * Calls {@code ServerHooks.onStopping()} in the vanilla shutdown hook {@code GameServer$1.run()}, + * between {@code GameServer.done = true} and {@code ServerMap.instance.QueuedQuit()}, which saves + * the world. + * + *

{@code GameServer$1} is the only caller of {@code QueuedQuit()}. The {@code quit} command + * only sets {@code ServerMap.queuedQuit}; {@code ServerMap.preupdate()} then calls + * {@code System.exit(0)}, so the save runs in the shutdown hook as it does for SIGTERM and SIGINT. + */ +public final class ServerStoppingPatch implements ClassPatch +{ + private static final String GAME_SERVER = "zombie/network/GameServer"; + + /** {@code GameServer.done = true; ServerMap.instance.QueuedQuit();} */ + private static final Anchor.Sequence ANCHOR = new Anchor.Sequence( + new Anchor.Method("run", "()V"), + new Anchor.Instruction.Constant(1), + new Anchor.Instruction.Opcode(Opcodes.PUTSTATIC), + new Anchor.Instruction.Opcode(Opcodes.GETSTATIC), + new Anchor.Instruction.Invoke("zombie/network/ServerMap", "QueuedQuit", "()V") + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onStopping", "()V" + ); + + @Override + public String target() { return ServerStoppingPatch.GAME_SERVER + "$1"; } + @Override + public Anchor.Sequence anchor() { return ServerStoppingPatch.ANCHOR; } + @Override + public Hook hook() { return ServerStoppingPatch.HOOK; } + + @Override + public void apply(ClassNode node) + { + List matched = ServerStoppingPatch.ANCHOR.resolve(node); + FieldInsnNode done = (FieldInsnNode) matched.get(1); + + if (!done.owner.equals(ServerStoppingPatch.GAME_SERVER) || !done.name.equals("done")) + throw new IllegalStateException("'" + node.name + ".run()V' sets '" + done.owner + "." + done.name + "' before 'QueuedQuit()', expected '" + ServerStoppingPatch.GAME_SERVER + ".done'."); + + ServerStoppingPatch.ANCHOR.in().resolve(node).instructions.insert( + done, new MethodInsnNode( + Opcodes.INVOKESTATIC, + ServerStoppingPatch.HOOK.owner(), + ServerStoppingPatch.HOOK.name(), + ServerStoppingPatch.HOOK.desc(), + false + ) + ); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerTickPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerTickPatch.java new file mode 100644 index 0000000..91ceaf6 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/ServerTickPatch.java @@ -0,0 +1,27 @@ +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.onTick()} in the main loop of {@code GameServer.main}, directly after + * {@code ServerMap.instance.preupdate()} at the start of the frame branch. The {@code while (!done)} + * loop itself also iterates while the update limiter skips a frame; the frame branch runs once + * per game frame. + */ +public final class ServerTickPatch extends HookInjectionPatch +{ + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("main", "([Ljava/lang/String;)V"), + "zombie/network/ServerMap", "preupdate", "()V" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onTick", "()V" + ); + + public ServerTickPatch() { + super("zombie/network/GameServer", ServerTickPatch.ANCHOR, ServerTickPatch.HOOK); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatchTest.java new file mode 100644 index 0000000..b050e85 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerLoadPatchTest.java @@ -0,0 +1,204 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; + +import java.lang.reflect.Field; +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.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +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.PUTSTATIC; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ServerLoadPatchTest +{ + private static final String GAME_SERVER = "zombie/network/GameServer"; + private static final String SERVER_OPTIONS = "zombie/network/ServerOptions"; + private static final String CALLS = Type.getInternalName(ServerLoadPatchTest.Calls.class); + + /** Stands in for {@code ServerHooks.onLoad()} and {@code System.exit}, and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + public static boolean loaded; + + private Calls() {} + + public static void record(String call) { Calls.LOG.add(call); } + + public static boolean onLoad() + { + Calls.LOG.add("onLoad"); + return Calls.loaded; + } + + public static void exit(int status) { Calls.LOG.add("exit " + status); } + } + + private record Run(List calls, Thread shutdownHook) {} + + /** + * {@code GameServer} with the parts of {@code main} the patch depends on: + * + *

{@code
+     * private static Thread shutdownHook = new Thread();      // only with withShutdownHook
+     *
+     * static { Runtime.getRuntime().addShutdownHook(shutdownHook); }
+     *
+     * public static void main(String[] args)
+     * {
+     *     ServerOptions.instance.init();
+     *     Calls.record("after");
+     * }
+     * }
+ */ + private static ClassNode gameServer(boolean withShutdownHook) + { + ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.GAME_SERVER); + + if (withShutdownHook) { + node.visitField(ACC_PRIVATE | ACC_STATIC, "shutdownHook", "Ljava/lang/Thread;", null, null); + + MethodVisitor init = node.visitMethod(ACC_STATIC, "", "()V", null, null); + init.visitTypeInsn(NEW, "java/lang/Thread"); + init.visitInsn(DUP); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/Thread", "", "()V", false); + init.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;"); + init.visitMethodInsn(INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false); + init.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;"); + init.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Runtime", "addShutdownHook", "(Ljava/lang/Thread;)V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + } + + MethodVisitor main = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); + main.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";"); + main.visitMethodInsn(INVOKEVIRTUAL, ServerLoadPatchTest.SERVER_OPTIONS, "init", "()V", false); + main.visitLdcInsn("after"); + main.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false); + main.visitInsn(RETURN); + main.visitMaxs(0, 0); + + return node; + } + + /** {@code ServerOptions} with {@code public static ServerOptions instance} and {@code init()} recording {@code "init"}. */ + private static ClassNode serverOptions() + { + ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.SERVER_OPTIONS); + String desc = "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";"; + + node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null); + + MethodVisitor clinit = node.visitMethod(ACC_STATIC, "", "()V", null, null); + clinit.visitTypeInsn(NEW, ServerLoadPatchTest.SERVER_OPTIONS); + clinit.visitInsn(DUP); + clinit.visitMethodInsn(INVOKESPECIAL, ServerLoadPatchTest.SERVER_OPTIONS, "", "()V", false); + clinit.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", desc); + clinit.visitInsn(RETURN); + clinit.visitMaxs(0, 0); + + MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null); + init.visitLdcInsn("init"); + init.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false); + init.visitInsn(RETURN); + init.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, "", "()V", null, null); + init.visitVarInsn(ALOAD, 0); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + + return node; + } + + /** Patches {@code GameServer}, points the hook and {@code System.exit} at {@link Calls}, and runs {@code main}. */ + private static Run run(boolean loaded) throws ReflectiveOperationException + { + ServerLoadPatch patch = new ServerLoadPatch(); + ClassNode gameServer = ServerLoadPatchTest.gameServer(true); + + patch.apply(gameServer); + CallRedirect.redirect(gameServer, patch.hook().owner(), patch.hook().name(), ServerLoadPatchTest.CALLS); + CallRedirect.redirect(gameServer, "java/lang/System", "exit", ServerLoadPatchTest.CALLS); + + ClassDefiner definer = new ClassDefiner(); + definer.define(ServerLoadPatchTest.serverOptions()); + Class loadedClass = definer.define(gameServer); + + ServerLoadPatchTest.Calls.LOG.clear(); + ServerLoadPatchTest.Calls.loaded = loaded; + + loadedClass.getMethod("main", String[].class).invoke(null, (Object) new String[0]); + + Field shutdownHook = loadedClass.getDeclaredField("shutdownHook"); + shutdownHook.setAccessible(true); + + return new Run(List.copyOf(ServerLoadPatchTest.Calls.LOG), (Thread) shutdownHook.get(null)); + } + + @Test + void anchorMatchesTheTarget() + { + new ServerLoadPatch().anchor().verify(ServerLoadPatchTest.gameServer(true)); + } + + @Test + void continuesWhenTheHookReturnsTrue() throws ReflectiveOperationException + { + Run run = ServerLoadPatchTest.run(true); + + assertEquals(List.of("init", "onLoad", "after"), run.calls()); + assertTrue(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook is still registered."); + } + + @Test + void removesTheShutdownHookAndExitsWhenTheHookReturnsFalse() throws ReflectiveOperationException + { + Run run = ServerLoadPatchTest.run(false); + + // The test double for System.exit returns, so "after" still runs. + assertEquals(List.of("init", "onLoad", "exit 1", "after"), run.calls()); + assertFalse(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook was not removed."); + } + + @Test + void failsWithoutTheShutdownHookField() + { + ClassNode gameServer = ServerLoadPatchTest.gameServer(false); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerLoadPatch().apply(gameServer)); + assertEquals("Expected the static field 'zombie/network/GameServer.shutdownHook Ljava/lang/Thread;'.", e.getMessage()); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatchTest.java new file mode 100644 index 0000000..2b09a04 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/ServerStoppingPatchTest.java @@ -0,0 +1,173 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +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.ALOAD; +import static org.objectweb.asm.Opcodes.DUP; +import static org.objectweb.asm.Opcodes.GETSTATIC; +import static org.objectweb.asm.Opcodes.ICONST_1; +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.PUTSTATIC; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ServerStoppingPatchTest +{ + private static final String GAME_SERVER = "zombie/network/GameServer"; + private static final String SHUTDOWN_HOOK = "zombie/network/GameServer$1"; + private static final String SERVER_MAP = "zombie/network/ServerMap"; + private static final String CALLS = Type.getInternalName(ServerStoppingPatchTest.Calls.class); + + /** Stands in for {@code ServerHooks.onStopping()} and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + /** {@code GameServer.done} of the class under test. */ + public static Field done; + + private Calls() {} + + public static void record(String call) { Calls.LOG.add(call); } + + public static void onStopping() throws IllegalAccessException { Calls.LOG.add("onStopping done=" + Calls.done.getBoolean(null)); } + } + + /** {@code GameServer} with {@code public static boolean done} and {@code other}. */ + private static ClassNode gameServer() + { + ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.GAME_SERVER); + + node.visitField(ACC_PUBLIC | ACC_STATIC, "done", "Z", null, null); + node.visitField(ACC_PUBLIC | ACC_STATIC, "other", "Z", null, null); + + return node; + } + + /** {@code ServerMap} with {@code public static ServerMap instance} and {@code QueuedQuit()} recording {@code "QueuedQuit"}. */ + private static ClassNode serverMap() + { + ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SERVER_MAP); + String desc = "L" + ServerStoppingPatchTest.SERVER_MAP + ";"; + + node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null); + + MethodVisitor clinit = node.visitMethod(ACC_STATIC, "", "()V", null, null); + clinit.visitTypeInsn(NEW, ServerStoppingPatchTest.SERVER_MAP); + clinit.visitInsn(DUP); + clinit.visitMethodInsn(INVOKESPECIAL, ServerStoppingPatchTest.SERVER_MAP, "", "()V", false); + clinit.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", desc); + clinit.visitInsn(RETURN); + clinit.visitMaxs(0, 0); + + MethodVisitor quit = node.visitMethod(ACC_PUBLIC, "QueuedQuit", "()V", null, null); + quit.visitLdcInsn("QueuedQuit"); + quit.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false); + quit.visitInsn(RETURN); + quit.visitMaxs(0, 0); + + return node; + } + + /** + * {@code GameServer$1} with the part of {@code run()} the patch depends on: + * + *
{@code
+     * public void run()
+     * {
+     *     GameServer. = true;
+     *     ServerMap.instance.QueuedQuit();
+     *     Calls.record("after");
+     * }
+     * }
+ */ + private static ClassNode shutdownHook(String field) + { + ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SHUTDOWN_HOOK); + MethodVisitor run = node.visitMethod(ACC_PUBLIC, "run", "()V", null, null); + + run.visitInsn(ICONST_1); + run.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.GAME_SERVER, field, "Z"); + run.visitFieldInsn(GETSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", "L" + ServerStoppingPatchTest.SERVER_MAP + ";"); + run.visitMethodInsn(INVOKEVIRTUAL, ServerStoppingPatchTest.SERVER_MAP, "QueuedQuit", "()V", false); + run.visitLdcInsn("after"); + run.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false); + run.visitInsn(RETURN); + run.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, "", "()V", null, null); + init.visitVarInsn(ALOAD, 0); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + + return node; + } + + @Test + void anchorMatchesTheTarget() + { + new ServerStoppingPatch().anchor().verify(ServerStoppingPatchTest.shutdownHook("done")); + } + + @Test + void callsTheHookAfterDoneIsSetAndBeforeTheSave() throws ReflectiveOperationException + { + ServerStoppingPatch patch = new ServerStoppingPatch(); + ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("done"); + + patch.apply(shutdownHook); + CallRedirect.redirect(shutdownHook, patch.hook().owner(), patch.hook().name(), ServerStoppingPatchTest.CALLS); + + ClassDefiner definer = new ClassDefiner(); + definer.define(ServerStoppingPatchTest.serverMap()); + + Class gameServer = definer.define(ServerStoppingPatchTest.gameServer()); + Class loaded = definer.define(shutdownHook); + + ServerStoppingPatchTest.Calls.LOG.clear(); + ServerStoppingPatchTest.Calls.done = gameServer.getField("done"); + + loaded.getMethod("run").invoke(loaded.getConstructor().newInstance()); + + assertEquals(List.of("onStopping done=true", "QueuedQuit", "after"), ServerStoppingPatchTest.Calls.LOG); + } + + @Test + void failsWhenAnotherFieldIsSetBeforeTheSave() + { + ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("other"); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerStoppingPatch().apply(shutdownHook)); + assertEquals( + "'zombie/network/GameServer$1.run()V' sets 'zombie/network/GameServer.other' before 'QueuedQuit()', expected 'zombie/network/GameServer.done'.", + e.getMessage() + ); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/CallRedirect.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/CallRedirect.java new file mode 100644 index 0000000..6b41709 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/support/CallRedirect.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.compat.b42.patches.support; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * Points calls in a patched test class at a test double, e.g. a hook or {@code System.exit}, so + * the patched code can run inside a test. + */ +public final class CallRedirect +{ + private CallRedirect() {} + + /** + * Changes the owner of every call to {@code owner.name} in {@code node} to {@code newOwner}. + * Fails when {@code node} contains no such call. + */ + public static void redirect(ClassNode node, String owner, String name, String newOwner) + { + int redirected = 0; + + for (MethodNode method : node.methods) { + for (AbstractInsnNode instruction : method.instructions) { + if (instruction instanceof MethodInsnNode call && call.owner.equals(owner) && call.name.equals(name)) { + call.owner = newOwner; + redirected++; + } + } + } + + if (redirected == 0) throw new IllegalStateException("No call to '" + owner + "." + name + "' in '" + node.name + "'."); + } +} 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 index 4b632c3..e640847 100644 --- 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 @@ -1,17 +1,84 @@ package dev.overlord.zomboidforge.compat.b42.hooks; import dev.overlord.zomboidforge.api.ZomboidForge; +import dev.overlord.zomboidforge.core.Lifecycle; -/** Hooks called by patched {@code zombie.network.GameServer} code. */ +/** + * Hooks called by patched {@code zombie.network.GameServer} code and its shutdown hook + * {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only + * a limited number of times, and an exception in the shutdown hook would skip the world save. + */ +@SuppressWarnings("CallToPrintStackTrace") public final class ServerHooks { + private static final Lifecycle LIFECYCLE = new Lifecycle(); + private ServerHooks() {} + /** + * Called once on the main thread in {@code GameServer.main}, directly after + * {@code ServerOptions.instance.init()}: logging is set up, and the server name and cache + * directory are known. The Workshop download, the server database, Lua, and the world come + * later. + * + * @return {@code false} to stop the server; the patched code then removes the vanilla + * shutdown hook and exits with code 1 + */ + public static boolean onLoad() + { + try + { + ServerHooks.LIFECYCLE.loaded(); + System.out.println("[ZomboidForge] " + ZomboidForge.VERSION + " load phase."); + + return true; + } + catch (Throwable t) + { + System.out.println("[ZomboidForge] Startup failed, stopping the server."); + t.printStackTrace(); + + return false; + } + } + /** * 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 + ")."); + public static void onServerStarted() + { + try + { + ServerHooks.LIFECYCLE.started(); + System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ")."); + } + catch (RuntimeException e) { e.printStackTrace(); } + } + + /** + * Called on the main thread for every frame of the main loop, directly after + * {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not + * called while the update limiter skips a frame. + */ + public static void onTick() {} + + /** + * Called once on the shutdown hook thread ({@code GameServer$1}), after + * {@code GameServer.done = true} and before {@code ServerMap.instance.QueuedQuit()} saves the + * world. Both ways the server stops lead here: the {@code quit} command makes + * {@code ServerMap.preupdate()} call {@code System.exit(0)}, and SIGTERM or SIGINT start the + * JVM shutdown directly. In the second case the main thread may still be inside a frame. Not + * called in soft-reset mode. + */ + public static void onStopping() + { + try + { + if (!ServerHooks.LIFECYCLE.stopping()) return; + + System.out.println("[ZomboidForge] Server stopping."); + } + catch (RuntimeException e) { e.printStackTrace(); } } } diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 611e340..15e24ff 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -6,4 +6,8 @@ plugins { dependencies { implementation(project(":api")) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.junit.jupiter) + testRuntimeOnly(libs.junit.platform.launcher) } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Lifecycle.java b/core/src/main/java/dev/overlord/zomboidforge/core/Lifecycle.java new file mode 100644 index 0000000..22a681e --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Lifecycle.java @@ -0,0 +1,47 @@ +package dev.overlord.zomboidforge.core; + +import java.util.concurrent.atomic.AtomicReference; + +/** + * Phase of a server run, advanced by the hooks in the patched game code. {@link #loaded()} and + * {@link #started()} each happen once and in this order; {@link #stopping()} can follow any phase, + * because the JVM can be stopped at any time. + */ +public final class Lifecycle +{ + public enum Phase + { + /** The JVM runs; mods are not loaded yet. */ + BOOTING, + /** Mods are loaded; the game still loads the world and opens the network port. */ + LOADED, + /** The main loop runs. */ + RUNNING, + /** The shutdown started; the world is about to be saved. */ + STOPPING + } + + private final AtomicReference phase = new AtomicReference<>(Phase.BOOTING); + + public Phase phase() { return this.phase.get(); } + + /** {@link Phase#BOOTING} to {@link Phase#LOADED}. */ + public void loaded() { this.advance(Phase.BOOTING, Phase.LOADED); } + + /** {@link Phase#LOADED} to {@link Phase#RUNNING}. */ + public void started() { this.advance(Phase.LOADED, Phase.RUNNING); } + + /** + * Any phase to {@link Phase#STOPPING}. + * + * @return {@code false} when the phase already was {@link Phase#STOPPING} + */ + public boolean stopping() { return this.phase.getAndSet(Phase.STOPPING) != Phase.STOPPING; } + + private void advance(Phase from, Phase to) + { + Phase current = this.phase.compareAndExchange(from, to); + + if (current != from) throw new IllegalStateException("Cannot enter phase '" + to + "' from '" + current + "', only from '" + from + "'."); + } +} diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/LifecycleTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/LifecycleTest.java new file mode 100644 index 0000000..27dae8e --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/LifecycleTest.java @@ -0,0 +1,54 @@ +package dev.overlord.zomboidforge.core; + +import org.junit.jupiter.api.Test; + +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; + +class LifecycleTest +{ + @Test + void advancesInOrder() + { + Lifecycle lifecycle = new Lifecycle(); + assertEquals(Lifecycle.Phase.BOOTING, lifecycle.phase()); + + lifecycle.loaded(); + assertEquals(Lifecycle.Phase.LOADED, lifecycle.phase()); + + lifecycle.started(); + assertEquals(Lifecycle.Phase.RUNNING, lifecycle.phase()); + + assertTrue(lifecycle.stopping()); + assertEquals(Lifecycle.Phase.STOPPING, lifecycle.phase()); + } + + @Test + void rejectsSkippedOrRepeatedPhases() + { + Lifecycle lifecycle = new Lifecycle(); + + IllegalStateException e = assertThrows(IllegalStateException.class, lifecycle::started); + assertEquals("Cannot enter phase 'RUNNING' from 'BOOTING', only from 'LOADED'.", e.getMessage()); + assertEquals(Lifecycle.Phase.BOOTING, lifecycle.phase()); + + lifecycle.loaded(); + assertThrows(IllegalStateException.class, lifecycle::loaded); + assertEquals(Lifecycle.Phase.LOADED, lifecycle.phase()); + } + + @Test + void stopsFromAnyPhaseOnce() + { + Lifecycle booting = new Lifecycle(); + assertTrue(booting.stopping()); + assertFalse(booting.stopping()); + + Lifecycle loaded = new Lifecycle(); + loaded.loaded(); + assertTrue(loaded.stopping()); + assertThrows(IllegalStateException.class, loaded::started); + } +}