diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 08a5cbd..6f35c15 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -177,6 +177,7 @@ Methods of `Mod`, usable from the constructor on (also in field initializers): | `modThread()` | `ModThread` | the mod's own work, one task at a time | | `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | | `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | +| `commands()` | `Commands` | admin commands for chat, the server console, and RCON | ## Threads @@ -210,6 +211,54 @@ Listeners are matched by the event's exact class. Events that carry live game ob removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove it earlier. +## Commands + +Admin commands work wherever Project Zomboid's own commands work: in the in-game chat +(`/zfhello`), the server console, and RCON. They use Project Zomboid's command framework, so the +mod declares `game` versions. In Build 42 a command is a subclass of +`zombie.commands.CommandBase`: + +```java +@CommandName(name = "zfhello") +@CommandArgs(optional = "(.+)") +@CommandHelp(helpText = "zfhello [name]: greets", shouldTranslated = false) +@RequiredCapability(requiredCapability = Capability.LoginOnServer) +public class HelloCommand extends CommandBase +{ + public HelloCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() + { + String name = this.getCommandArg(0); + return "Hello " + (name == null ? this.getExecutorUsername() : name); + } +} +``` + +```java +@Override +public void onLoad() { this.commands().register(HelloCommand.class); } +``` + +- **Registration** happens in the entry point's constructor or `onLoad()`; later calls throw. + `register` checks the class and throws `IllegalArgumentException` listing every problem, + which stops the server like any other exception in `onLoad()`. +- **The class** is public and not abstract, with one public constructor + `(String, Role, String, UdpConnection)`. +- **Names** (`@CommandName`, repeatable for aliases) consist of letters, digits, and `_` and + differ, ignoring case, from the names of Project Zomboid's commands and other mods' commands. + A name matches when it is the first word of the input, ignoring case. +- **`@RequiredCapability`** is required: Project Zomboid refuses to run a command without one. + RCON and the server console run commands with the default admin role. +- **`@CommandArgs`** (regular expressions for the arguments; the capture groups become + `getCommandArg(n)`) and **`@CommandHelp`** (`help zfhello` and the `help` list; with + `shouldTranslated = false` the text is used as written) are optional. +- **`Command()`** runs on the main thread, for every use on a new instance; its return value + is the reply. Long work belongs on `modThread()` or `async()`; the reply then only confirms + that the work started. +- Project Zomboid's commands are looked up first; mods' commands follow in load order. + ## Storage Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java new file mode 100644 index 0000000..e402c87 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Commands.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api; + +/** + * Registration of admin commands. A registered command works wherever Project Zomboid's own + * admin commands work: in the in-game chat ({@code /name}), the server console, and RCON. It + * is looked up after the commands of Project Zomboid and runs on the main thread. + * + *

A command is a class of the running Project Zomboid version's command framework, so a mod + * that registers commands declares {@code game} versions in {@code mod.toml}. In Build 42 it is + * a public, non-abstract subclass of {@code zombie.commands.CommandBase} with: + *

+ * Project Zomboid creates a new instance for every use and calls its {@code Command()}, whose + * result is the reply. + */ +public interface Commands +{ + /** + * Registers {@code command}. Only on the main thread while the mod loads: in the entry point's + * constructor or {@link Mod#onLoad()}. + * + * @throws IllegalArgumentException when {@code command} does not meet the rules above, or is + * registered already + * @throws IllegalStateException when called later or on another thread + */ + void register(Class command); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java index 1190d9d..ca2e2ac 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -84,4 +84,7 @@ public abstract class Mod /** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */ protected final ModStorage storage() { return this.context.storage(); } + + /** Admin command registration. */ + protected final Commands commands() { return this.context.commands(); } } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java index 5efd9ca..3aed3d3 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java @@ -42,4 +42,7 @@ public interface ModContext /** The mod's tables in the world's {@code zomboidforge.db}. */ ModStorage storage(); + + /** Admin command registration. */ + Commands commands(); } 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 2ee7f65..ffef12a 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 @@ -18,6 +18,8 @@ public final class B42PatchSet implements PatchSet new ServerTickPatch(), new ServerStoppingPatch(), new BackupStoragePatch(), + new CommandLookupPatch(), + new CommandListPatch(), new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java new file mode 100644 index 0000000..d4f750a --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandListPatch.java @@ -0,0 +1,32 @@ +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.ReturnHookPatch; + +import org.objectweb.asm.Opcodes; + +import java.util.List; + +/** + * Makes {@code CommandBase.getSubClasses()} return + * {@code CommandHooks.listCommands(childrenClasses)}: Project Zomboid's command classes followed + * by the mods'. The {@code help} command lists commands through this method. + */ +public final class CommandListPatch extends ReturnHookPatch +{ + /** The whole method: {@code getstatic childrenClasses}, {@code areturn}. */ + private static final Anchor.Sequence ANCHOR = new Anchor.Sequence( + new Anchor.Method("getSubClasses", "()[Ljava/lang/Class;"), + new Anchor.Instruction.Opcode(Opcodes.GETSTATIC), + new Anchor.Instruction.Opcode(Opcodes.ARETURN) + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "listCommands", "([Ljava/lang/Class;)[Ljava/lang/Class;" + ); + + public CommandListPatch() { + super("zombie/commands/CommandBase", CommandListPatch.ANCHOR, CommandListPatch.HOOK, List.of()); + } +} diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java new file mode 100644 index 0000000..be4d659 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/CommandLookupPatch.java @@ -0,0 +1,33 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; +import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch; + +import org.objectweb.asm.Opcodes; + +import java.util.List; + +/** + * Makes {@code CommandBase.findCommandCls(command)} return + * {@code CommandHooks.findCommand(null, command)} where it returns {@code null}: when no command + * of Project Zomboid matches, the mods' commands are searched. The server console, RCON, chat + * commands, and {@code help } look commands up through this method. + */ +public final class CommandLookupPatch extends ReturnHookPatch +{ + private static final Anchor.Sequence ANCHOR = new Anchor.Sequence( + new Anchor.Method("findCommandCls", "(Ljava/lang/String;)Ljava/lang/Class;"), + new Anchor.Instruction.Opcode(Opcodes.ACONST_NULL), + new Anchor.Instruction.Opcode(Opcodes.ARETURN) + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks", "findCommand", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;" + ); + + public CommandLookupPatch() { + super("zombie/commands/CommandBase", CommandLookupPatch.ANCHOR, CommandLookupPatch.HOOK, List.of(new HookArgument.Parameter(0))); + } +} diff --git a/compat/b42/runtime/build.gradle.kts b/compat/b42/runtime/build.gradle.kts index 42937d1..10dcb47 100644 --- a/compat/b42/runtime/build.gradle.kts +++ b/compat/b42/runtime/build.gradle.kts @@ -10,6 +10,8 @@ dependencies { implementation(project(":api")) compileOnly(files(projectZomboid.serverJar)) + // ModCommandsTest checks command classes against the game's command framework. + testImplementation(files(projectZomboid.serverJar)) testImplementation(platform(libs.junit.bom)) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.platform.launcher) diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java index fd6ee55..e84f01d 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java @@ -1,11 +1,12 @@ package dev.overlord.zomboidforge.compat.b42; +import dev.overlord.zomboidforge.compat.b42.commands.ModCommands; import dev.overlord.zomboidforge.core.Forge; /** The one {@link Forge} of the server, shared by the hook classes. */ public final class ForgeInstance { - public static final Forge FORGE = Forge.fromSystemProperties(); + public static final Forge FORGE = Forge.fromSystemProperties(ModCommands::check); private ForgeInstance() {} } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java new file mode 100644 index 0000000..2e2b452 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommands.java @@ -0,0 +1,111 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.Nullable; + +import zombie.characters.Role; +import zombie.commands.CommandBase; +import zombie.commands.CommandName; +import zombie.commands.RequiredCapability; +import zombie.core.raknet.UdpConnection; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Command classes of mods in Build 42: subclasses of {@code CommandBase}, which + * {@code GameServer.handleServerCommand} creates through {@code getConstructors()[0]} with + * {@code (username, role, command, connection)}. + */ +public final class ModCommands +{ + private static final Class[] CONSTRUCTOR = {String.class, Role.class, String.class, UdpConnection.class}; + + /** + * Names are inserted into a regular expression by {@code findCommandCls}, so they are limited + * to word characters. With such names, {@code ^name\b} matches the input exactly when its first + * word equals the name, ignoring case. + */ + private static final Pattern NAME = Pattern.compile("\\w+"); + + private ModCommands() {} + + /** + * Fails unless {@code command} is a usable Build 42 command whose names are not taken by + * Project Zomboid's commands or by {@code registered}. + * + * @throws IllegalArgumentException listing every problem + */ + public static void check(Class command, List> registered) + { + List problems = new ArrayList<>(); + int modifiers = command.getModifiers(); + + if (!CommandBase.class.isAssignableFrom(command)) problems.add("it does not extend '" + CommandBase.class.getName() + "'"); + if (!Modifier.isPublic(modifiers)) problems.add("it is not public"); + if (Modifier.isAbstract(modifiers)) problems.add("it is abstract"); + + Constructor[] constructors = command.getConstructors(); + if (constructors.length != 1 || !Arrays.equals(constructors[0].getParameterTypes(), ModCommands.CONSTRUCTOR)) + problems.add("it needs exactly one public constructor '(String, Role, String, UdpConnection)'"); + + if (command.getAnnotationsByType(RequiredCapability.class).length == 0) + problems.add("it has no @RequiredCapability, and Project Zomboid runs no command without one"); + + CommandName[] names = command.getAnnotationsByType(CommandName.class); + if (names.length == 0) problems.add("it has no @CommandName"); + + for (CommandName name : names) + { + if (!ModCommands.NAME.matcher(name.name()).matches()) { + problems.add("the name '" + name.name() + "' contains characters other than letters, digits, and '_'"); + continue; + } + + Class owner = ModCommands.owner(name.name(), registered); + if (owner != null) problems.add("the name '" + name.name() + "' is taken by '" + owner.getName() + "'"); + } + + if (!problems.isEmpty()) throw new IllegalArgumentException("'" + command.getName() + "' cannot be a command: " + String.join("; ", problems) + "."); + } + + /** + * The first class of {@code commands} that is not disabled and has a name that {@code input} + * starts with, matched like {@code CommandBase.findCommandCls} matches Project Zomboid's + * commands; {@code null} when there is none. + */ + public static @Nullable Class find(List> commands, String input) + { + for (Class command : commands) + { + if (CommandBase.isDisabled(command)) continue; + + for (CommandName name : command.getAnnotationsByType(CommandName.class)) { + if (Pattern.compile("^" + name.name() + "\\b", Pattern.CASE_INSENSITIVE).matcher(input).find()) return command; + } + } + + return null; + } + + /** The class among Project Zomboid's commands and {@code registered} that has {@code name}, ignoring case. */ + private static @Nullable Class owner(String name, List> registered) + { + Set> taken = new LinkedHashSet<>(Arrays.>asList(CommandBase.getSubClasses())); + taken.addAll(registered); + + for (Class command : taken) + { + for (CommandName existing : command.getAnnotationsByType(CommandName.class)) { + if (existing.name().equalsIgnoreCase(name)) return command; + } + } + + return null; + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java new file mode 100644 index 0000000..a3f2f19 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/commands/package-info.java @@ -0,0 +1,10 @@ +/** + * Admin commands of mods in Build 42: checks for registered command classes and the lookup that + * mirrors {@code zombie.commands.CommandBase.findCommandCls}. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java new file mode 100644 index 0000000..4f73479 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/CommandHooks.java @@ -0,0 +1,61 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; +import dev.overlord.zomboidforge.compat.b42.commands.ModCommands; + +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.List; + +/** + * Hooks called by patched {@code zombie.commands.CommandBase} code, on the main thread: the + * server console, RCON, and chat commands all run there. Exceptions are caught here, and the + * vanilla value is returned. + */ +@SuppressWarnings("CallToPrintStackTrace") +public final class CommandHooks +{ + private CommandHooks() {} + + /** + * Replaces the {@code null} that {@code CommandBase.findCommandCls} returns when no command of + * Project Zomboid matches {@code command}: the mods' command class for it, or {@code null}. + */ + public static @Nullable Class findCommand(@Nullable Class vanilla, String command) + { + try + { + return ModCommands.find(ForgeInstance.FORGE.commands(), command); + } + catch (Throwable t) + { + t.printStackTrace(); + return vanilla; + } + } + + /** + * Replaces the array that {@code CommandBase.getSubClasses} returns: Project Zomboid's + * command classes followed by the mods', in registration order. Without mod commands, the + * vanilla array itself. + */ + public static Class[] listCommands(Class[] vanilla) + { + try + { + List> mods = ForgeInstance.FORGE.commands(); + if (mods.isEmpty()) return vanilla; + + Class[] all = Arrays.copyOf(vanilla, vanilla.length + mods.size()); + for (int i = 0; i < mods.size(); i++) all[vanilla.length + i] = mods.get(i); + + return all; + } + catch (Throwable t) + { + t.printStackTrace(); + return vanilla; + } + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java index e374764..e9ed449 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVehicleHooks.java @@ -33,10 +33,8 @@ public final class ZombieVehicleHooks * and is skipped here. */ public static @Nullable Vector3f getIntersectPoint( - @NotNull BaseVehicle vehicle, - @NotNull Vector3f start, - @NotNull Vector3f end, - @Nullable Vector3f result + BaseVehicle vehicle, Vector3f start, + Vector3f end, @Nullable Vector3f result ) { VehicleScript script = vehicle.getScript(); Vector3f extents = script.getExtents(); diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java new file mode 100644 index 0000000..c331228 --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/commands/ModCommandsTest.java @@ -0,0 +1,125 @@ +package dev.overlord.zomboidforge.compat.b42.commands; + +import org.junit.jupiter.api.Test; + +import zombie.characters.Capability; +import zombie.characters.Role; +import zombie.commands.CommandBase; +import zombie.commands.CommandName; +import zombie.commands.DisabledCommand; +import zombie.commands.RequiredCapability; +import zombie.core.raknet.UdpConnection; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** Runs against the classes of the server jar that the module compiles against. */ +class ModCommandsTest +{ + @CommandName(name = "zfshop") + @CommandName(name = "zfbuy") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class ShopCommand extends CommandBase + { + public ShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "shop"; } + } + + @CommandName(name = "ZFSHOP") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class OtherShopCommand extends CommandBase + { + public OtherShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "other shop"; } + } + + @CommandName(name = "Save") + @CommandName(name = "zf-save") + @RequiredCapability(requiredCapability = Capability.SaveWorld) + public static final class SaveCommand extends CommandBase + { + public SaveCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "save"; } + } + + @DisabledCommand + @CommandName(name = "zfoff") + @RequiredCapability(requiredCapability = Capability.LoginOnServer) + public static final class DisabledShopCommand extends CommandBase + { + public DisabledShopCommand(String username, Role role, String command, UdpConnection connection) { super(username, role, command, connection); } + + @Override + protected String Command() { return "off"; } + } + + /** Neither a command nor annotated; its constructor has no parameters. */ + public static final class NotACommand {} + + @Test + void acceptsAUsableCommand() + { + assertDoesNotThrow(() -> ModCommands.check(ModCommandsTest.ShopCommand.class, List.of())); + } + + @Test + void listsEveryProblemOfAClassThatIsNoCommand() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.NotACommand.class, List.of())); + + assertEquals( + "'" + ModCommandsTest.NotACommand.class.getName() + "' cannot be a command: it does not extend 'zombie.commands.CommandBase';" + + " it needs exactly one public constructor '(String, Role, String, UdpConnection)';" + + " it has no @RequiredCapability, and Project Zomboid runs no command without one; it has no @CommandName.", + e.getMessage() + ); + } + + @Test + void rejectsNamesOfProjectZomboidIgnoringCaseAndNamesWithOtherCharacters() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> ModCommands.check(ModCommandsTest.SaveCommand.class, List.of())); + + assertEquals( + "'" + ModCommandsTest.SaveCommand.class.getName() + "' cannot be a command:" + + " the name 'Save' is taken by 'zombie.commands.serverCommands.SaveCommand';" + + " the name 'zf-save' contains characters other than letters, digits, and '_'.", + e.getMessage() + ); + } + + @Test + void rejectsNamesOfRegisteredCommands() + { + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> ModCommands.check(ModCommandsTest.OtherShopCommand.class, List.of(ModCommandsTest.ShopCommand.class)) + ); + + assertEquals( + "'" + ModCommandsTest.OtherShopCommand.class.getName() + "' cannot be a command: the name 'ZFSHOP' is taken by '" + ModCommandsTest.ShopCommand.class.getName() + "'.", + e.getMessage() + ); + } + + @Test + void findsCommandsByTheirFirstWordIgnoringCase() + { + List> commands = List.of(ModCommandsTest.DisabledShopCommand.class, ModCommandsTest.ShopCommand.class); + + assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "zfshop")); + assertEquals(ModCommandsTest.ShopCommand.class, ModCommands.find(commands, "ZFBuy apple 3")); + assertNull(ModCommands.find(commands, "zfshopping")); + assertNull(ModCommands.find(commands, "zfoff"), "disabled commands are skipped, like Project Zomboid's"); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index e30d7fd..c769065 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -6,6 +6,7 @@ import dev.overlord.zomboidforge.api.Mod; import dev.overlord.zomboidforge.api.TickEvent; import dev.overlord.zomboidforge.api.ZomboidForge; import dev.overlord.zomboidforge.api.storage.StorageException; +import dev.overlord.zomboidforge.core.commands.CommandRegistry; import dev.overlord.zomboidforge.core.config.ForgeSettings; import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.ModDiscovery; @@ -52,6 +53,7 @@ public final class Forge private final Path directory; private final @Nullable ModVersion api; + private final CommandRegistry commands; private volatile List mods = List.of(); private volatile ForgeSettings settings = ForgeSettings.DEFAULTS; @@ -61,32 +63,41 @@ public final class Forge * @param directory the ZomboidForge directory * @param api the API version mods are checked against, or {@code null} to skip the * check + * @param commands checks the command classes that mods register against the running game + * version */ - public Forge(Path directory, @Nullable ModVersion api) + public Forge(Path directory, @Nullable ModVersion api, CommandRegistry.Validator commands) { this.directory = directory; this.api = api; + this.commands = new CommandRegistry(commands, this::commandsOpen); } /** * Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API * version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev}, * {@code 0.0.0-...}) skip the API check. + * + * @param commands checks the command classes that mods register against the running game + * version */ - public static Forge fromSystemProperties() + public static Forge fromSystemProperties(CommandRegistry.Validator commands) { Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY)); ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION) .filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0) .orElse(null); - return new Forge(directory, api); + return new Forge(directory, api, commands); } public Lifecycle.Phase phase() { return this.lifecycle.phase(); } public List mods() { return this.mods; } + /** The admin command classes that mods registered, in registration order. */ + public List> commands() { return this.commands.classes(); } + /** * Reads {@code forge.toml}, then discovers, checks, and loads every mod in * {@code /mods}. Called once on the main thread, which becomes the thread of @@ -246,6 +257,9 @@ public final class Forge catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); } } + /** Mods register commands on the main thread while they load. */ + private boolean commandsOpen() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.BOOTING; } + /** The main thread may use storage only before the main loop runs. */ private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; } @@ -260,7 +274,8 @@ public final class Forge this.queue.forMod(id, logger), executors.modThread(), executors.async(), - new ModTables(id, storage, logger) + new ModTables(id, storage, logger), + this.commands.forMod(logger) ); } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java new file mode 100644 index 0000000..b4335c9 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/CommandRegistry.java @@ -0,0 +1,74 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.Commands; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.BooleanSupplier; + +/** + * The admin command classes that mods registered, in registration order. What a command class + * has to look like depends on the Project Zomboid version, so a {@link Validator} from the compat + * module checks every class. Registration happens only while the mods load, on the main thread; + * the compat hooks read {@link #classes()} on the main thread afterwards. + */ +public final class CommandRegistry +{ + /** Checks a command class against the command framework of the running game version. */ + @FunctionalInterface + public interface Validator + { + /** + * @param registered the classes registered before, by any mod + * @throws IllegalArgumentException naming what is wrong with {@code command} + */ + void check(Class command, List> registered); + } + + private final Validator validator; + private final BooleanSupplier open; + + private volatile List> classes = List.of(); + + /** @param open whether registration is allowed now, on the calling thread */ + public CommandRegistry(Validator validator, BooleanSupplier open) + { + this.validator = Objects.requireNonNull(validator); + this.open = Objects.requireNonNull(open); + } + + /** Every registered class, in registration order. */ + public List> classes() { return this.classes; } + + /** + * Registration for one mod; registered classes are logged with {@code logger}. Exceptions do + * not name the mod: one thrown in the mod's {@code onLoad()} is reported with its id. + */ + public Commands forMod(System.Logger logger) + { + return command -> + { + this.register(command); + logger.log(System.Logger.Level.INFO, "Registered the command class '" + command.getName() + "'."); + }; + } + + private synchronized void register(Class command) + { + Objects.requireNonNull(command, "command"); + + if (!this.open.getAsBoolean()) + throw new IllegalStateException("Commands can only be registered on the main thread while the mod loads (constructor or onLoad())."); + + if (this.classes.contains(command)) + throw new IllegalArgumentException("The command class '" + command.getName() + "' is registered already."); + + this.validator.check(command, this.classes); + + List> updated = new ArrayList<>(this.classes); + updated.add(command); + + this.classes = List.copyOf(updated); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java new file mode 100644 index 0000000..ba64d1f --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/commands/package-info.java @@ -0,0 +1,9 @@ +/** + * Admin commands of loaded mods: the registry that the compat hooks consult. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.core.commands; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index 8e8e8ca..1811403 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -1,6 +1,7 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.MainThread; @@ -46,7 +47,8 @@ public final class ModLoader MainThread main, ModThread modThread, AsyncExecutor async, - ModStorage storage + ModStorage storage, + Commands commands ) implements ModContext {} private ModLoader() {} @@ -93,7 +95,8 @@ public final class ModLoader provided.main(), provided.modThread(), provided.async(), - provided.storage() + provided.storage(), + provided.commands() ); loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context))); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java index 856554f..bbd0c36 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java @@ -1,13 +1,14 @@ package dev.overlord.zomboidforge.core.mods; import dev.overlord.zomboidforge.api.AsyncExecutor; +import dev.overlord.zomboidforge.api.Commands; import dev.overlord.zomboidforge.api.Events; import dev.overlord.zomboidforge.api.MainThread; import dev.overlord.zomboidforge.api.ModThread; import dev.overlord.zomboidforge.api.storage.ModStorage; -/** The threads, event registration, and storage of one mod, created before its entry point. */ -public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage) +/** The threads, event and command registration, and storage of one mod, created before its entry point. */ +public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage, Commands commands) { /** Creates the services of one mod. */ @FunctionalInterface diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index 2b0cb04..63f282c 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import testmods.CommandMod; import testmods.ContextMod; import testmods.ErrorMod; import testmods.Recorder; @@ -19,6 +20,7 @@ import testmods.ThreadMod; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -27,6 +29,7 @@ import java.util.function.BooleanSupplier; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -45,6 +48,9 @@ class ForgeTest private Path gameJar; private Path storageFile; + /** Classes that mods registered as commands, as {@code " after "}; every class is accepted. */ + private final List checkedCommands = new ArrayList<>(); + @BeforeEach void setUp() throws IOException { @@ -56,7 +62,10 @@ class ForgeTest Recorder.EVENTS.clear(); } - private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); } + private Forge forge() + { + return new Forge(this.directory, ModVersion.parse("0.3.0"), (command, registered) -> this.checkedCommands.add(command.getName() + " after " + registered.size())); + } private Forge load() throws ModLoadException { @@ -105,6 +114,25 @@ class ForgeTest ); } + @Test + void modsRegisterCommandsOnlyWhileTheyLoad() throws Exception + { + TestMods.folder(this.mods, "commands", TestMods.toml("commands", CommandMod.class.getName(), ""), Map.of( + "testmods/CommandMod", TestMods.classFile(CommandMod.class), + "testmods/CommandMod$Command", TestMods.classFile(CommandMod.Command.class) + )); + + Forge forge = this.load(); + + assertEquals(List.of("testmods.CommandMod$Command"), forge.commands().stream().map(Class::getName).toList()); + assertEquals(List.of("testmods.CommandMod$Command after 0"), this.checkedCommands); + + forge.started(); + + assertInstanceOf(IllegalStateException.class, ForgeTest.field(forge.mods().getFirst().mod(), "lateRegistration")); + assertEquals(1, forge.commands().size()); + } + @Test void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java new file mode 100644 index 0000000..2907b21 --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/commands/CommandRegistryTest.java @@ -0,0 +1,78 @@ +package dev.overlord.zomboidforge.core.commands; + +import dev.overlord.zomboidforge.api.Commands; +import dev.overlord.zomboidforge.core.RecordingLogger; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class CommandRegistryTest +{ + private final List checked = new ArrayList<>(); + private final AtomicBoolean open = new AtomicBoolean(true); + private final RecordingLogger logger = new RecordingLogger(); + + /** Records every check as {@code " after "} and rejects {@link Integer}. */ + private final CommandRegistry registry = new CommandRegistry( + (command, registered) -> + { + this.checked.add(command.getSimpleName() + " after " + registered.size()); + if (command == Integer.class) throw new IllegalArgumentException("'java.lang.Integer' cannot be a command."); + }, + this.open::get + ); + + private final Commands commands = this.registry.forMod(this.logger); + + @Test + void registersInOrderAndShowsTheValidatorTheEarlierClasses() + { + this.commands.register(String.class); + this.commands.register(Long.class); + + assertEquals(List.of(String.class, Long.class), this.registry.classes()); + assertEquals(List.of("String after 0", "Long after 1"), this.checked); + assertEquals( + List.of("INFO: Registered the command class 'java.lang.String'.", "INFO: Registered the command class 'java.lang.Long'."), + this.logger.messages + ); + } + + @Test + void rejectedClassesAreNotRegistered() + { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(Integer.class)); + + assertEquals("'java.lang.Integer' cannot be a command.", e.getMessage()); + assertEquals(List.of(), this.registry.classes()); + assertEquals(List.of(), this.logger.messages); + } + + @Test + void rejectsTheSameClassTwice() + { + this.commands.register(String.class); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> this.commands.register(String.class)); + + assertEquals("The command class 'java.lang.String' is registered already.", e.getMessage()); + assertEquals(List.of(String.class), this.registry.classes()); + } + + @Test + void rejectsRegistrationWhileClosed() + { + this.open.set(false); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> this.commands.register(String.class)); + + assertEquals("Commands can only be registered on the main thread while the mod loads (constructor or onLoad()).", e.getMessage()); + assertEquals(List.of(), this.checked); + } +} diff --git a/core/src/test/java/testmods/CommandMod.java b/core/src/test/java/testmods/CommandMod.java new file mode 100644 index 0000000..7e38208 --- /dev/null +++ b/core/src/test/java/testmods/CommandMod.java @@ -0,0 +1,27 @@ +package testmods; + +import dev.overlord.zomboidforge.api.Mod; + +import org.jetbrains.annotations.Nullable; + +/** + * Entry point that tests package into a mod jar. Registers {@link Command} in {@code onLoad()} + * and tries again in {@code onServerStarted()}, which is too late. + */ +public final class CommandMod extends Mod +{ + /** Stands in for a command class; the tests' validator accepts any class. */ + public static final class Command {} + + public volatile @Nullable RuntimeException lateRegistration; + + @Override + public void onLoad() { this.commands().register(CommandMod.Command.class); } + + @Override + public void onServerStarted() + { + try { this.commands().register(CommandMod.Command.class); } + catch (RuntimeException e) { this.lateRegistration = e; } + } +} diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index d443efa..3ef9887 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -6,6 +6,7 @@ + @@ -159,6 +160,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -167,6 +192,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java index 22f845f..be939a4 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/HookCall.java @@ -11,18 +11,27 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; +import java.util.ArrayList; import java.util.List; -/** The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. */ +/** + * The call of a {@link Hook} with its {@link HookArgument}s, shared by the hook patch types. A + * hook may also take values that are already on the operand stack where it is called; those + * come first in its parameter list, followed by one parameter per argument. + */ final class HookCall { private HookCall() {} + /** {@link #checkShape(Hook, List, List, Type)} without values on the stack. */ + static void checkShape(Hook hook, List arguments, Type returnType) { HookCall.checkShape(hook, List.of(), arguments, returnType); } + /** - * Fails unless {@code hook} returns {@code returnType} and takes {@code arguments} parameters. - * The parameter types are checked by {@link #invoke}, once the arguments are resolved. + * Fails unless {@code hook} returns {@code returnType}, takes the types {@code onStack} first, + * and then one parameter per argument. The types of those parameters are checked by + * {@link #invoke}, once the arguments are resolved. */ - static void checkShape(Hook hook, List arguments, Type returnType) + static void checkShape(Hook hook, List onStack, List arguments, Type returnType) { Type actualReturn = Type.getReturnType(hook.desc()); Type[] parameters = Type.getArgumentTypes(hook.desc()); @@ -30,34 +39,55 @@ final class HookCall if (!actualReturn.equals(returnType)) throw new IllegalArgumentException("Hook '" + hook + "' must return '" + returnType.getDescriptor() + "'."); - if (parameters.length != arguments.size()) - throw new IllegalArgumentException("Hook '" + hook + "' must take " + arguments.size() + " parameter(s), one per argument " + arguments + "."); + if (parameters.length != onStack.size() + arguments.size()) + throw new IllegalArgumentException("Hook '" + hook + "' must take " + (onStack.size() + arguments.size()) + " parameter(s): " + HookCall.describe(onStack, arguments) + "."); + + for (int i = 0; i < onStack.size(); i++) + { + if (!parameters[i].equals(onStack.get(i))) + throw new IllegalArgumentException("Parameter " + i + " of hook '" + hook + "' must be '" + onStack.get(i).getDescriptor() + "'."); + } + } + + /** {@link #invoke(Hook, List, List, Type, ClassNode, MethodNode, AbstractInsnNode)} without values on the stack. */ + static InsnList invoke(Hook hook, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) + { + return HookCall.invoke(hook, List.of(), arguments, returnType, node, method, at); } /** * Instructions that push {@code arguments} and call {@code hook}, for insertion directly - * before or after {@code at} in {@code method}. Fails when the hook's descriptor does not - * match the types of the arguments. + * before or after {@code at} in {@code method}, where the values of the types {@code onStack} + * are on top of the operand stack. Fails when the hook's descriptor does not match. */ - static InsnList invoke(Hook hook, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) + static InsnList invoke(Hook hook, List onStack, List arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at) { - InsnList code = new InsnList(); - Type[] types = new Type[arguments.size()]; + InsnList code = new InsnList(); + List types = new ArrayList<>(onStack); - for (int i = 0; i < arguments.size(); i++) + for (HookArgument argument : arguments) { - HookArgument.Slot slot = arguments.get(i).resolve(node, method, at); + HookArgument.Slot slot = argument.resolve(node, method, at); - types[i] = slot.type(); + types.add(slot.type()); code.add(slot.load()); } - String expected = Type.getMethodDescriptor(returnType, types); + String expected = Type.getMethodDescriptor(returnType, types.toArray(Type[]::new)); if (!hook.desc().equals(expected)) - throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for the arguments " + arguments + "."); + throw new IllegalStateException("Hook '" + hook + "' must have descriptor '" + expected + "' for " + HookCall.describe(onStack, arguments) + "."); code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false)); return code; } + + /** E.g. {@code the arguments [parameter 0]} or {@code the stack value(s) [Ljava/lang/Class;] and the arguments [parameter 0]}. */ + private static String describe(List onStack, List arguments) + { + String argumentsText = "the arguments " + arguments; + if (onStack.isEmpty()) return argumentsText; + + return "the stack value(s) " + onStack.stream().map(Type::getDescriptor).toList() + " and " + argumentsText; + } } diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java new file mode 100644 index 0000000..d713f30 --- /dev/null +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/Patches/ReturnHookPatch.java @@ -0,0 +1,75 @@ +package dev.overlord.zomboidforge.patcher.Patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.HookArgument; + +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.MethodNode; +import org.objectweb.asm.util.Printer; + +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +/** + * Passes the value that one return instruction of a method is about to return to a + * {@link Hook}, which returns the value to return instead: + * + *
{@code
+ * return Hooks.hook(value, arguments);
+ * }
+ * + * The anchor is a {@link Anchor.Sequence} whose last instruction is that return instruction; + * the instructions before it identify which return of the method is meant. The hook's first + * parameter and its return type are the method's return type, followed by one parameter per + * {@link HookArgument}. Other returns of the method are unchanged. + */ +public abstract class ReturnHookPatch implements ClassPatch +{ + private final String target; + private final Anchor.Sequence anchor; + private final Hook hook; + private final List arguments; + private final Type returned; + + protected ReturnHookPatch(String target, Anchor.Sequence anchor, Hook hook, List arguments) + { + Type returned = Type.getReturnType(anchor.in().desc()); + + if (returned.equals(Type.VOID_TYPE)) + throw new IllegalArgumentException("Method '" + anchor.in().name() + anchor.in().desc() + "' returns no value."); + + HookCall.checkShape(hook, List.of(returned), arguments, returned); + + this.target = Objects.requireNonNull(target); + this.anchor = anchor; + this.hook = hook; + this.arguments = List.copyOf(arguments); + this.returned = returned; + } + + @Override + public final String target() { return this.target; } + @Override + public final Anchor.Sequence anchor() { return this.anchor; } + @Override + public final Hook hook() { return this.hook; } + + @Override + public final void apply(ClassNode node) + { + MethodNode method = this.anchor.in().resolve(node); + AbstractInsnNode instruction = this.anchor.resolve(node).getLast(); + int returnOpcode = this.returned.getOpcode(Opcodes.IRETURN); + + if (instruction.getOpcode() != returnOpcode) + throw new IllegalStateException("The last instruction of the anchor must be '" + Printer.OPCODES[returnOpcode].toLowerCase(Locale.ROOT) + "'."); + + method.instructions.insertBefore(instruction, HookCall.invoke(this.hook, List.of(this.returned), this.arguments, this.returned, node, method, instruction)); + } +} diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java new file mode 100644 index 0000000..1ef388b --- /dev/null +++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/ReturnHookPatchTest.java @@ -0,0 +1,185 @@ +package dev.overlord.zomboidforge.patcher; + +import dev.overlord.zomboidforge.patcher.Patches.ReturnHookPatch; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; + +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ACONST_NULL; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ARETURN; +import static org.objectweb.asm.Opcodes.IFEQ; +import static org.objectweb.asm.Opcodes.ILOAD; +import static org.objectweb.asm.Opcodes.LRETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ReturnHookPatchTest +{ + private static final String CALLS = Type.getInternalName(ReturnHookPatchTest.Calls.class); + + private static final Anchor.Method PICK = new Anchor.Method("pick", "(Ljava/lang/String;Z)Ljava/lang/String;"); + private static final Anchor.Method WIDE = new Anchor.Method("wide", "()J"); + + @TempDir + Path dir; + + /** The hooks. */ + public static final class Calls + { + private Calls() {} + + public static String replaceNull(@Nullable String value, String input) { return "hook " + value + " " + input; } + + public static long doubled(long value) { return value * 2; } + } + + /** Replaces the {@code null} that {@code pick} returns; the hook gets {@code input}. */ + private static final class NullPatch extends ReturnHookPatch + { + NullPatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL), new Anchor.Instruction.Opcode(ARETURN)), + new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), + List.of(new HookArgument.Parameter(0)) + ); + } + } + + /** Doubles the {@code long} that {@code wide} returns. */ + private static final class WidePatch extends ReturnHookPatch + { + WidePatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Constant(5L), new Anchor.Instruction.Opcode(LRETURN)), + new Hook(ReturnHookPatchTest.CALLS, "doubled", "(J)J"), + List.of() + ); + } + } + + /** Anchored on {@code aconst_null} alone, not on a return instruction. */ + private static final class NoReturnPatch extends ReturnHookPatch + { + NoReturnPatch() { + super( + "t/Target", + new Anchor.Sequence(ReturnHookPatchTest.PICK, new Anchor.Instruction.Opcode(ACONST_NULL)), + new Hook(ReturnHookPatchTest.CALLS, "replaceNull", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), + List.of(new HookArgument.Parameter(0)) + ); + } + } + + /** + * {@code static pick(String input, boolean keep)}: {@code return keep ? input : null;} and + * {@code static wide()}: {@code return 5L;}. + */ + private Path target() throws Exception + { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); + cw.visit(V25, ACC_PUBLIC, "t/Target", null, "java/lang/Object", null); + + Label returnNull = new Label(); + + MethodVisitor pick = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "pick", ReturnHookPatchTest.PICK.desc(), null, null); + pick.visitVarInsn(ILOAD, 1); + pick.visitJumpInsn(IFEQ, returnNull); + pick.visitVarInsn(ALOAD, 0); + pick.visitInsn(ARETURN); + pick.visitLabel(returnNull); + pick.visitInsn(ACONST_NULL); + pick.visitInsn(ARETURN); + pick.visitMaxs(0, 0); + + MethodVisitor wide = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "wide", ReturnHookPatchTest.WIDE.desc(), null, null); + wide.visitLdcInsn(5L); + wide.visitInsn(LRETURN); + wide.visitMaxs(0, 0); + + cw.visitEnd(); + + Path jar = this.dir.resolve("in.jar"); + + try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar))) + { + zip.putNextEntry(new ZipEntry("t/Target.class")); + zip.write(cw.toByteArray()); + zip.closeEntry(); + } + + return jar; + } + + @Test + void replacesTheAnchoredReturnValueOnly() throws Exception + { + Path out = this.dir.resolve("patched.jar"); + + new JarPatcher(List.of(new NullPatch(), new WidePatch())).patch(this.target(), out); + + try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, ReturnHookPatchTest.class.getClassLoader())) + { + Class target = loader.loadClass("t.Target"); + + assertEquals("kept", target.getMethod("pick", String.class, boolean.class).invoke(null, "kept", true)); + assertEquals("hook null input", target.getMethod("pick", String.class, boolean.class).invoke(null, "input", false)); + assertEquals(10L, target.getMethod("wide").invoke(null)); + } + } + + @Test + void reportsAnchorThatDoesNotEndInAReturn() throws Exception + { + Path in = this.target(); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> new JarPatcher(List.of(new NoReturnPatch())).patch(in, this.dir.resolve("out.jar")) + ); + + assertEquals("'NoReturnPatch': The last instruction of the anchor must be 'areturn'.", e.getMessage()); + } + + @Test + void rejectsMethodWithoutReturnValue() + { + Anchor.Sequence anchor = new Anchor.Sequence(new Anchor.Method("run", "()V"), new Anchor.Instruction.Opcode(ARETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "()V"), List.of()) {}); + } + + @Test + void rejectsHookWhoseFirstParameterIsNotTheReturnType() + { + Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(I)J"), List.of()) {}); + } + + @Test + void rejectsHookThatReturnsAnotherType() + { + Anchor.Sequence anchor = new Anchor.Sequence(ReturnHookPatchTest.WIDE, new Anchor.Instruction.Opcode(LRETURN)); + + assertThrows(IllegalArgumentException.class, () -> new ReturnHookPatch("t/Target", anchor, new Hook("t/Hooks", "hook", "(J)I"), List.of()) {}); + } +}