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 calls(MethodNode method) + { + List calls = new ArrayList<>(); + + for (AbstractInsnNode instruction : method.instructions) { + if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name); + } + + return calls; + } + + @Test + void anchorMatchesTheTarget() + { + new RolesSavePerformancePatch().anchor().verify(RolesSavePerformancePatchTest.roles()); + } + + @Test + void wrapsSaveBetweenTheTransactionHooks() + { + ClassNode node = RolesSavePerformancePatchTest.roles(); + new RolesSavePerformancePatch().apply(node); + + MethodNode save = node.methods.stream().filter(method -> method.name.equals("save")).findFirst().orElseThrow(); + MethodNode original = node.methods.stream().filter(method -> method.name.equals("zomboidForge$save")).findFirst().orElseThrow(); + + // The normal path and the exception path each end the transaction. + assertEquals(List.of("RolesHooks.beginSave", "Roles.zomboidForge$save", "RolesHooks.endSave", "RolesHooks.endSave"), RolesSavePerformancePatchTest.calls(save)); + assertEquals(1, save.tryCatchBlocks.size()); + assertEquals(List.of("ServerWorldDatabase.saveRole"), RolesSavePerformancePatchTest.calls(original)); + } + + @Test + void patchedClassIsValid() throws ClassNotFoundException + { + ClassNode node = RolesSavePerformancePatchTest.roles(); + new RolesSavePerformancePatch().apply(node); + + // Initializing links the class, which runs the bytecode verifier on the wrapper. + ClassDefiner definer = new ClassDefiner(); + definer.define(node); + Class.forName(node.name.replace('/', '.'), true, definer); + } + + /** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */ + @Test + void endSaveHookExistsAsPublicStaticMethod() throws IOException + { + ClassNode hooks = PackageScan.read(RolesSavePerformancePatchTest.HOOKS); + + assertTrue(hooks.methods.stream().anyMatch(method -> + method.name.equals("endSave") && method.desc.equals("()V") + && (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0 + )); + } + + @Test + void appliesOnlyToVerifiedVersions() + { + RolesSavePerformancePatch patch = new RolesSavePerformancePatch(); + + assertTrue(patch.appliesTo(GameVersion.parse("42.21.0"))); + assertTrue(patch.appliesTo(GameVersion.parse("42.21.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.20.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.22.0"))); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks.java new file mode 100644 index 0000000..ff92152 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks.java @@ -0,0 +1,81 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import org.jetbrains.annotations.Nullable; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.sql.Connection; +import java.sql.SQLException; + +import zombie.network.ServerWorldDatabase; + +/** + * Hooks called by patched {@code zombie.characters.Roles} code: {@code Roles.save()} in one + * SQLite transaction. + * + *

{@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 EVENTS = new ArrayList<>(); + + public static void before() { MethodBodyTest.EVENTS.add("before"); } + + public static void after() { MethodBodyTest.EVENTS.add("after"); } + + public static void work(long value, String text) { MethodBodyTest.EVENTS.add("work " + value + " " + text); } + + public static void fail() { throw new IllegalStateException("failed"); } + /** Defines classes from nodes, with the test classes as parent so the hooks resolve. */ private static final class Definer extends ClassLoader { @@ -177,4 +192,80 @@ public class MethodBodyTest ); assertTrue(e.getMessage().contains("has no body"), e.getMessage()); } + + /** {@code t/Target} with {@code public static void run(long, String)} calling {@code body} with its arguments or none. */ + private static ClassNode wrappable(String body, String bodyDesc) + { + ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "placeholder", "()V", false); + MethodVisitor run = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "(JLjava/lang/String;)V", null, null); + + if (bodyDesc.equals("(JLjava/lang/String;)V")) + { + run.visitVarInsn(LLOAD, 0); + run.visitVarInsn(ALOAD, 2); + } + run.visitMethodInsn(INVOKESTATIC, MethodBodyTest.HOOKS, body, bodyDesc, false); + run.visitInsn(RETURN); + run.visitMaxs(0, 0); + + return node; + } + + private static final Hook BEFORE = new Hook(MethodBodyTest.HOOKS, "before", "()V"); + private static final Hook AFTER = new Hook(MethodBodyTest.HOOKS, "after", "()V"); + + @Test + void wrapRunsBeforeTheOriginalWithItsArgumentsThenAfter() throws ReflectiveOperationException + { + ClassNode node = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V"); + MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER); + + MethodBodyTest.EVENTS.clear(); + MethodBodyTest.run(node, "run", new Class[] { long.class, String.class }, 42L, "abc"); + + assertEquals(List.of("before", "work 42 abc", "after"), MethodBodyTest.EVENTS); + } + + @Test + void wrapRunsAfterAndRethrowsWhenTheOriginalThrows() + { + ClassNode node = MethodBodyTest.wrappable("fail", "()V"); + MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER); + + MethodBodyTest.EVENTS.clear(); + InvocationTargetException e = assertThrows(InvocationTargetException.class, () -> + MethodBodyTest.run(node, "run", new Class[] { long.class, String.class }, 1L, "x") + ); + + assertTrue(e.getCause() instanceof IllegalStateException); + assertEquals("failed", e.getCause().getMessage()); + assertEquals(List.of("before", "after"), MethodBodyTest.EVENTS); + } + + @Test + void wrapKeepsTheOriginalUnderTheNewName() + { + ClassNode node = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V"); + MethodBody.wrap(node, MethodBodyTest.method(node, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER); + + assertEquals(1, node.methods.stream().filter(method -> method.name.equals("run")).count()); + assertEquals(1, node.methods.stream().filter(method -> method.name.equals("original$run") && method.desc.equals("(JLjava/lang/String;)V")).count()); + } + + @Test + void wrapFailsForInstanceMethodsValuesTakenNamesAndHooksWithArguments() + { + ClassNode instance = MethodBodyTest.target(ACC_PUBLIC, "run", "()V", false); + assertThrows(IllegalStateException.class, () -> MethodBody.wrap(instance, MethodBodyTest.method(instance, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER)); + + ClassNode value = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "run", "()I", false); + assertThrows(IllegalStateException.class, () -> MethodBody.wrap(value, MethodBodyTest.method(value, "run"), "original$run", MethodBodyTest.BEFORE, MethodBodyTest.AFTER)); + + ClassNode taken = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V"); + assertThrows(IllegalStateException.class, () -> MethodBody.wrap(taken, MethodBodyTest.method(taken, "run"), "placeholder", MethodBodyTest.BEFORE, MethodBodyTest.AFTER)); + + ClassNode arguments = MethodBodyTest.wrappable("work", "(JLjava/lang/String;)V"); + Hook withArgs = new Hook(MethodBodyTest.HOOKS, "record", "(Ljava/lang/String;)V"); + assertThrows(IllegalStateException.class, () -> MethodBody.wrap(arguments, MethodBodyTest.method(arguments, "run"), "original$run", withArgs, MethodBodyTest.AFTER)); + } }