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 fc8dd30..25c8a14 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 @@ -31,7 +31,8 @@ public final class B42PatchSet implements PatchSet new WorldGenUtilsPlacementPerformancePatch(), new WorldGenChunkRulesPerformancePatch(), new BitHeaderPoolPerformancePatch(), - new IsoChunkSaveDirectoryPerformancePatch() + new IsoChunkSaveDirectoryPerformancePatch(), + new RolesSavePerformancePatch() ); @Override diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatch.java new file mode 100644 index 0000000..c3a51f6 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatch.java @@ -0,0 +1,58 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.MethodBody; +import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch; + +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.MethodNode; + +/** + * Saves the roles in one SQLite transaction. {@code Roles.save()} is renamed to + * {@code zomboidForge$save} and wrapped: + * + *
{@code
+ * public static void save()
+ * {
+ * RolesHooks.beginSave();
+ * try { zomboidForge$save(); }
+ * finally { RolesHooks.endSave(); }
+ * }
+ * }
+ *
+ * The vanilla method writes every role and capability with its own autocommitted statement
+ * ({@code ServerWorldDatabase.saveRole}, {@code saveDefaultRole}): about 250 transactions and
+ * 1,000 {@code fsync}s, 1.3 s of every shutdown on a fast disk.
+ */
+public final class RolesSavePerformancePatch extends PerformancePatch
+{
+ private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
+ private static final String RENAMED = "zomboidForge$save";
+
+ private static final Anchor.Call ANCHOR = new Anchor.Call(
+ new Anchor.Method("save", "()V"),
+ "zombie/network/ServerWorldDatabase", "saveRole", "(Lzombie/characters/Role;)V"
+ );
+
+ private static final Hook HOOK = new Hook(RolesSavePerformancePatch.HOOKS, "beginSave", "()V");
+ private static final Hook END = new Hook(RolesSavePerformancePatch.HOOKS, "endSave", "()V");
+
+ public RolesSavePerformancePatch() {
+ super("zombie/characters/Roles", RolesSavePerformancePatch.ANCHOR, RolesSavePerformancePatch.HOOK);
+ }
+
+ //
+
+ @Override
+ public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
+
+ @Override
+ public void apply(ClassNode node)
+ {
+ MethodNode save = RolesSavePerformancePatch.ANCHOR.in().resolve(node);
+
+ MethodBody.wrap(node, save, RolesSavePerformancePatch.RENAMED, RolesSavePerformancePatch.HOOK, RolesSavePerformancePatch.END);
+ }
+}
diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatchTest.java
new file mode 100644
index 0000000..5539db2
--- /dev/null
+++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/RolesSavePerformancePatchTest.java
@@ -0,0 +1,119 @@
+package dev.overlord.zomboidforge.compat.b42.perf;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
+import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
+
+import org.junit.jupiter.api.Test;
+import org.objectweb.asm.MethodVisitor;
+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.io.IOException;
+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.assertTrue;
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
+import static org.objectweb.asm.Opcodes.ACC_STATIC;
+import static org.objectweb.asm.Opcodes.ACONST_NULL;
+import static org.objectweb.asm.Opcodes.CHECKCAST;
+import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
+import static org.objectweb.asm.Opcodes.RETURN;
+import static org.objectweb.asm.Opcodes.V25;
+
+class RolesSavePerformancePatchTest
+{
+ private static final String ROLES = "zombie/characters/Roles";
+ private static final String DATABASE = "zombie/network/ServerWorldDatabase";
+ private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
+
+ /** {@code Roles} with a reduced {@code save()}: {@code ((ServerWorldDatabase) null).saveRole(null);} */
+ private static ClassNode roles()
+ {
+ ClassNode node = new ClassNode();
+ node.visit(V25, ACC_PUBLIC, RolesSavePerformancePatchTest.ROLES, null, "java/lang/Object", null);
+
+ MethodVisitor save = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "save", "()V", null, null);
+ save.visitInsn(ACONST_NULL);
+ save.visitTypeInsn(CHECKCAST, RolesSavePerformancePatchTest.DATABASE);
+ save.visitInsn(ACONST_NULL);
+ save.visitTypeInsn(CHECKCAST, "zombie/characters/Role");
+ save.visitMethodInsn(INVOKEVIRTUAL, RolesSavePerformancePatchTest.DATABASE, "saveRole", "(Lzombie/characters/Role;)V", false);
+ save.visitInsn(RETURN);
+ save.visitMaxs(0, 0);
+
+ return node;
+ }
+
+ private static List{@code Roles.save()} writes every role and capability with its own statement, each in its + * own transaction on the autocommitting connection of {@code ServerWorldDatabase}: about 250 + * transactions and 1,000 {@code fsync}s at every shutdown. In one transaction the same + * statements write the same rows. The hooks never fail the save: when the connection cannot be + * reached or switched, the save runs in autocommit mode as in vanilla. + */ +public final class RolesHooks +{ + /** {@code ServerWorldDatabase.conn}, package-private; {@code null} when it cannot be reached. */ + private static final @Nullable VarHandle CONNECTION; + + static + { + VarHandle connection = null; + try + { + connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup()) + .findVarHandle(ServerWorldDatabase.class, "conn", Connection.class); + } + catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: 'ServerWorldDatabase.conn' not found: " + e); } + + CONNECTION = connection; + } + + /** The connection of the running save while it is in a transaction of these hooks. */ + private static @Nullable Connection transaction; + + private RolesHooks() {} + + /** Called before {@code Roles.save()}: switches the database connection to one transaction. */ + public static void beginSave() + { + if (RolesHooks.CONNECTION == null || ServerWorldDatabase.instance == null) return; + + Connection connection = (Connection) RolesHooks.CONNECTION.get(ServerWorldDatabase.instance); + if (connection == null) return; + + try + { + if (!connection.getAutoCommit()) return; + + connection.setAutoCommit(false); + RolesHooks.transaction = connection; + } + catch (SQLException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: " + e); } + } + + /** + * Called after {@code Roles.save()}, also when it threw: commits what it wrote, as autocommit + * would have, and switches autocommit back on. + */ + public static void endSave() + { + Connection connection = RolesHooks.transaction; + RolesHooks.transaction = null; + if (connection == null) return; + + try { connection.commit(); } + catch (SQLException e) { System.out.println("[ZomboidForge] Committing the saved roles failed: " + e); } + finally + { + try { connection.setAutoCommit(true); } + catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); } + } + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooksTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooksTest.java new file mode 100644 index 0000000..92b75de --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooksTest.java @@ -0,0 +1,99 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import zombie.network.ServerWorldDatabase; + +import java.lang.reflect.Field; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The hooks on a real SQLite database, installed as the connection of {@code ServerWorldDatabase}. */ +class RolesHooksTest +{ + private Connection connection; + + private void install(Connection connection) throws ReflectiveOperationException + { + Field field = ServerWorldDatabase.class.getDeclaredField("conn"); + field.setAccessible(true); + field.set(ServerWorldDatabase.instance, connection); + + this.connection = connection; + } + + @AfterEach + void uninstall() throws ReflectiveOperationException, SQLException + { + this.install(null); + } + + private static int count(Connection connection) throws SQLException + { + try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM roles")) + { + rows.next(); + return rows.getInt(1); + } + } + + @Test + void writesBetweenTheHooksBecomeVisibleTogetherAtTheEnd(@TempDir Path temp) throws Exception + { + String url = "jdbc:sqlite:" + temp.resolve("test.db"); + + try (Connection server = DriverManager.getConnection(url); Connection reader = DriverManager.getConnection(url)) + { + try (Statement statement = server.createStatement()) { statement.executeUpdate("CREATE TABLE roles (name TEXT)"); } + this.install(server); + + RolesHooks.beginSave(); + assertFalse(server.getAutoCommit()); + + try (Statement statement = server.createStatement()) + { + statement.executeUpdate("INSERT INTO roles VALUES ('admin')"); + statement.executeUpdate("INSERT INTO roles VALUES ('user')"); + } + assertEquals(0, RolesHooksTest.count(reader), "Rows are visible before the end of the save."); + + RolesHooks.endSave(); + assertTrue(server.getAutoCommit()); + assertEquals(2, RolesHooksTest.count(reader)); + } + } + + @Test + void leavesAConnectionAloneThatIsAlreadyInATransaction(@TempDir Path temp) throws Exception + { + try (Connection server = DriverManager.getConnection("jdbc:sqlite:" + temp.resolve("test.db"))) + { + server.setAutoCommit(false); + this.install(server); + + RolesHooks.beginSave(); + RolesHooks.endSave(); + + assertFalse(server.getAutoCommit()); + } + } + + @Test + void doesNothingWithoutAConnection() throws ReflectiveOperationException + { + this.install(null); + + RolesHooks.beginSave(); + RolesHooks.endSave(); + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java index 8b2c6eb..6c1ace9 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java @@ -4,14 +4,17 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TryCatchBlockNode; import org.objectweb.asm.tree.VarInsnNode; import java.util.Arrays; -/** Replaces the body of a method of the target class with a call to a {@link Hook}. */ +/** Replaces the body of a method of the target class with a call to a {@link Hook}, or wraps it in hook calls. */ public final class MethodBody { private MethodBody() {} @@ -56,6 +59,70 @@ public final class MethodBody method.instructions.add(new InsnNode(type.getReturnType().getOpcode(Opcodes.IRETURN))); } + /** + * Wraps the static void method {@code method}: renames it to {@code renamed} and adds a method + * with its name, descriptor and access that runs + * + *
{@code
+ * before();
+ * try { renamed(arguments); }
+ * finally { after(); }
+ * }
+ *
+ * {@code before} and {@code after} take no arguments. Fails for instance methods, methods
+ * that return a value, and when {@code node} already has a method named {@code renamed}.
+ */
+ public static void wrap(ClassNode node, MethodNode method, String renamed, Hook before, Hook after)
+ {
+ String name = "'" + node.name + "." + method.name + method.desc + "'";
+
+ if ((method.access & Opcodes.ACC_STATIC) == 0)
+ throw new IllegalStateException(name + " is not static.");
+ if (Type.getReturnType(method.desc) != Type.VOID_TYPE)
+ throw new IllegalStateException(name + " returns a value.");
+ if (node.methods.stream().anyMatch(other -> other.name.equals(renamed)))
+ throw new IllegalStateException("'" + node.name + "' already has a method '" + renamed + "'.");
+
+ MethodNode wrapper = new MethodNode(method.access, method.name, method.desc, method.signature, method.exceptions.toArray(String[]::new));
+ method.name = renamed;
+
+ LabelNode start = new LabelNode();
+ LabelNode end = new LabelNode();
+ LabelNode handler = new LabelNode();
+ InsnList code = wrapper.instructions;
+ int slot = 0;
+
+ code.add(MethodBody.call(before));
+ code.add(start);
+ for (Type argument : Type.getArgumentTypes(method.desc))
+ {
+ code.add(new VarInsnNode(argument.getOpcode(Opcodes.ILOAD), slot));
+ slot += argument.getSize();
+ }
+ code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, node.name, renamed, method.desc, (node.access & Opcodes.ACC_INTERFACE) != 0));
+ code.add(end);
+ code.add(MethodBody.call(after));
+ code.add(new InsnNode(Opcodes.RETURN));
+
+ // finally on the exception path: run after(), rethrow; the exception goes to the first free slot.
+ code.add(handler);
+ code.add(new VarInsnNode(Opcodes.ASTORE, slot));
+ code.add(MethodBody.call(after));
+ code.add(new VarInsnNode(Opcodes.ALOAD, slot));
+ code.add(new InsnNode(Opcodes.ATHROW));
+
+ wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null));
+ node.methods.add(wrapper);
+ }
+
+ private static MethodInsnNode call(Hook hook)
+ {
+ if (!hook.desc().equals("()V"))
+ throw new IllegalStateException("The hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' must take no arguments and return nothing.");
+
+ return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
+ }
+
/** Whether the method reads or writes local variable 0, which holds {@code this}. */
private static boolean usesThis(MethodNode method)
{
diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
index 5219702..19c5bad 100644
--- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
+++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
@@ -6,8 +6,10 @@ import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
+import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -18,9 +20,11 @@ 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.ICONST_0;
+import static org.objectweb.asm.Opcodes.INVOKESTATIC;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.IRETURN;
import static org.objectweb.asm.Opcodes.LCONST_0;
+import static org.objectweb.asm.Opcodes.LLOAD;
import static org.objectweb.asm.Opcodes.LRETURN;
import static org.objectweb.asm.Opcodes.POP;
import static org.objectweb.asm.Opcodes.RETURN;
@@ -41,6 +45,17 @@ public class MethodBodyTest
public static void record(String value) { MethodBodyTest.recorded = value; }
+ /** Calls of the hooks below, in order. */
+ public static final List