Add ServerLoadPatch, ServerStoppingPatch, and ServerTickPatch to enhance server lifecycle handling in GameServer. Include tests, update B42PatchSet, and integrate lifecycle management utilities.

This commit is contained in:
Overlord committed 2026-10-01 20:03:10 +02:00
1 parent 600373dc61
commit 837367047c
11 files changed
+787 -3

No files matched your search

@@ -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<ClassPatch> PATCHES = List.of(
new ServerLoadPatch(),
new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
new IsoZombieVehiclePerformancePatch(),
new IsoZombieNetworkComponentPerformancePatch(),
new IsoZombieSpotChancePerformancePatch(),
@@ -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}:
*
* <pre>{@code
* if (!ServerHooks.onLoad()) {
* Runtime.getRuntime().removeShutdownHook(shutdownHook);
* System.exit(1);
* }
* }</pre>
*
* 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;
}
}
@@ -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.
*
* <p>{@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<AbstractInsnNode> 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
)
);
}
}
@@ -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);
}
}
@@ -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<String> 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<String> calls, Thread shutdownHook) {}
/**
* {@code GameServer} with the parts of {@code main} the patch depends on:
*
* <pre>{@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");
* }
* }</pre>
*/
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, "<clinit>", "()V", null, null);
init.visitTypeInsn(NEW, "java/lang/Thread");
init.visitInsn(DUP);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Thread", "<init>", "()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, "<clinit>", "()V", null, null);
clinit.visitTypeInsn(NEW, ServerLoadPatchTest.SERVER_OPTIONS);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, ServerLoadPatchTest.SERVER_OPTIONS, "<init>", "()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, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
/** 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());
}
}
@@ -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<String> 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, "<clinit>", "()V", null, null);
clinit.visitTypeInsn(NEW, ServerStoppingPatchTest.SERVER_MAP);
clinit.visitInsn(DUP);
clinit.visitMethodInsn(INVOKESPECIAL, ServerStoppingPatchTest.SERVER_MAP, "<init>", "()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:
*
* <pre>{@code
* public void run()
* {
* GameServer.<field> = true;
* ServerMap.instance.QueuedQuit();
* Calls.record("after");
* }
* }</pre>
*/
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, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
return node;
}
@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()
);
}
}
@@ -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 + "'.");
}
}
@@ -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(); }
}
}