Add mod command integration for Build 42: command hooks, lookup extensions, registry, and validation mechanisms. Include corresponding tests and documentation.

This commit is contained in:
Overlord committed 2026-10-03 11:27:06 +02:00
1 parent 22077514fe
commit af7174e128
26 files changed
+1117 -30

No files matched your search

+49
View File
@@ -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
@@ -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.
*
* <p>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:
* <ul>
* <li>one public constructor {@code (String username, Role role, String command, UdpConnection connection)},
* which passes its arguments to {@code super};</li>
* <li>at least one {@code @CommandName}; names consist of letters, digits, and {@code _}, and
* differ (ignoring case) from every name of Project Zomboid and of other mods;</li>
* <li>at least one {@code @RequiredCapability}; Project Zomboid refuses to run a command
* without one;</li>
* <li>optionally {@code @CommandArgs} (argument patterns) and {@code @CommandHelp}
* ({@code help <name>} and the {@code help} list).</li>
* </ul>
* 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);
}
@@ -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(); }
}
@@ -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();
}
@@ -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(),
@@ -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());
}
}
@@ -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 <name>} 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)));
}
}
+2
View File
@@ -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)
@@ -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() {}
}
@@ -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<Class<?>> registered)
{
List<String> 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<Class<?>> 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<Class<?>> registered)
{
Set<Class<?>> taken = new LinkedHashSet<>(Arrays.<Class<?>>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;
}
}
@@ -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;
@@ -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<Class<?>> 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;
}
}
}
@@ -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();
@@ -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<Class<?>> 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");
}
}
@@ -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<ModLoader.LoadedMod> 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<ModLoader.LoadedMod> mods() { return this.mods; }
/** The admin command classes that mods registered, in registration order. */
public List<Class<?>> commands() { return this.commands.classes(); }
/**
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
* {@code <directory>/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)
);
}
}
@@ -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<Class<?>> registered);
}
private final Validator validator;
private final BooleanSupplier open;
private volatile List<Class<?>> 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<Class<?>> 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<Class<?>> updated = new ArrayList<>(this.classes);
updated.add(command);
this.classes = List.copyOf(updated);
}
}
@@ -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;
@@ -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)));
@@ -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
@@ -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 "<name> after <registered count>"}; every class is accepted. */
private final List<String> 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
{
@@ -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<String> checked = new ArrayList<>();
private final AtomicBoolean open = new AtomicBoolean(true);
private final RecordingLogger logger = new RecordingLogger();
/** Records every check as {@code "<simple name> after <registered count>"} 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);
}
}
@@ -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; }
}
}
+97
View File
@@ -6,6 +6,7 @@
<trusted-artifacts>
<trust file=".*-javadoc[.]jar" regex="true"/>
<trust file=".*-sources[.]jar" regex="true"/>
<trust group="gradle" name="gradle" file="gradle-.*-src[.]zip" regex="true"/>
</trusted-artifacts>
</configuration>
<components>
@@ -159,6 +160,30 @@
<sha256 value="d40318527f56033e0ff0789971cc38c856aa99a685eea11270814e7f1eda9fba" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy" version="4.0.33">
<artifact name="groovy-4.0.33.module">
<sha256 value="b51f0a5b8ecfba534d47612a49aa51b279ecdac72e7f790a8ed3130070d80dc5" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-4.0.33.pom">
<sha256 value="4a077cc859cb0fabab55f8637e77889fe03b2489692c9d1da253e43715c28cf8" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-ant" version="4.0.33">
<artifact name="groovy-ant-4.0.33.module">
<sha256 value="c498aa114fb510a7f6841c94f973fb16d4580357c170ab978fd5ae2a8e4fb57a" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-ant-4.0.33.pom">
<sha256 value="e64319f32699287e1d39c1f8da358a6a7740c8a8dc5516a7c43d606b0fa16298" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-astbuilder" version="4.0.33">
<artifact name="groovy-astbuilder-4.0.33.module">
<sha256 value="655c1b59499c7e590dbc3d643a9485f2d512e34145f1735fd477bcb03e3ced73" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-astbuilder-4.0.33.pom">
<sha256 value="fe25b6081390bbb9cf32fc9cf5b373fa391cb3854bfdedcde81a238ea88ad68c" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-bom" version="4.0.27">
<artifact name="groovy-bom-4.0.27.module">
<sha256 value="d6c2254c8347b84cda84caf74914a187c2f377e4284e8d8bb3f901521810aa8b" origin="Generated by Gradle"/>
@@ -167,6 +192,78 @@
<sha256 value="aa44eb52bfdfe61d27b3e450d2b348d88deaa3437ab4d9d49a84095348f9f6fb" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-bom" version="4.0.33">
<artifact name="groovy-bom-4.0.33.module">
<sha256 value="a87e4410ce69764f53e10ff399ba4ed8875bc59845b766181e9c82e9ddfc5f75" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-bom-4.0.33.pom">
<sha256 value="c30cc3b9184251be043e8b98ec9f6f17c39b0925183e91c7856ea82b18d9f5ce" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-datetime" version="4.0.33">
<artifact name="groovy-datetime-4.0.33.module">
<sha256 value="97199c00ad134459c8c3c5244f16f0d9e3f08d61a8b2a7b1ad66e827f027d10e" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-datetime-4.0.33.pom">
<sha256 value="691f2eb07b9a60f69926644902103fb2b4ae6370a4154eb4aac765d073fc9e1d" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-dateutil" version="4.0.33">
<artifact name="groovy-dateutil-4.0.33.module">
<sha256 value="b7848a9cf1159b796c11097d380a9f1cb3c2c60fdb9feb560dc88c5bb5b441bd" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-dateutil-4.0.33.pom">
<sha256 value="c7bab371bf9f8666d6c738bcf268671b45ebc305160d2d170520110527ee106b" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-docgenerator" version="4.0.33">
<artifact name="groovy-docgenerator-4.0.33.module">
<sha256 value="594227fa51d93092f70be2d17ac90c1358960131a7ccd9e9c589b82bca3b640f" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-docgenerator-4.0.33.pom">
<sha256 value="cfd1d47f567d2d8c1047c9fa69e5ac873d25c57088767204c5a7cb888d95104e" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-groovydoc" version="4.0.33">
<artifact name="groovy-groovydoc-4.0.33.module">
<sha256 value="70cf9d616c4757ebbe206e1db77e4f2225b9e238e9d79634a62ddc2cc45f706c" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-groovydoc-4.0.33.pom">
<sha256 value="de5bec405a6a258dc48820cd136bd2d2920142a6bc620921a05271157be62945" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-json" version="4.0.33">
<artifact name="groovy-json-4.0.33.module">
<sha256 value="591dc453651b086a4301984b64c18679b5f8fb70fc6dd4f2ab25263d4119dfb4" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-json-4.0.33.pom">
<sha256 value="d92a8fa210f6fb7777a1f0f123fe96f268a7d25d000666f1884d3520535b2900" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-nio" version="4.0.33">
<artifact name="groovy-nio-4.0.33.module">
<sha256 value="0a3d28bb3c364d2dd83e78127100facd2de4a7be491f8f64a58f7852be29d716" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-nio-4.0.33.pom">
<sha256 value="044bfe5a61dce53a32031c1ee373efac9648c3eb27272a64f2c05e0eed4d1ec5" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-templates" version="4.0.33">
<artifact name="groovy-templates-4.0.33.module">
<sha256 value="8eae833715e00c5d56aafa0d3bb6dd7efcbb6245cd3e9ea5f6776de4c6e9eef1" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-templates-4.0.33.pom">
<sha256 value="5819f6df4c0536bcd76d28aeb044e570e68aff3e2546118c6715a615460e92bf" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.groovy" name="groovy-xml" version="4.0.33">
<artifact name="groovy-xml-4.0.33.module">
<sha256 value="bd326e05cf9e63da4e509eeb03689889be869605eb4ac5459970adef5ba32202" origin="Generated by IntelliJ sync"/>
</artifact>
<artifact name="groovy-xml-4.0.33.pom">
<sha256 value="01eb2e96423efa4725424036b578ddf95647979438f3a92a017f2ed176ce5abd" origin="Generated by IntelliJ sync"/>
</artifact>
</component>
<component group="org.apache.logging.log4j" name="log4j" version="2.26.1">
<artifact name="log4j-2.26.1.pom">
<sha256 value="ea4705725fd94bf5debe2911d4ea7af20898603f68354e64b2461a0f249e445d" origin="Generated by Gradle"/>
@@ -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<HookArgument> 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<HookArgument> arguments, Type returnType)
static void checkShape(Hook hook, List<Type> onStack, List<HookArgument> 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<HookArgument> 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<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
static InsnList invoke(Hook hook, List<Type> onStack, List<HookArgument> arguments, Type returnType, ClassNode node, MethodNode method, AbstractInsnNode at)
{
InsnList code = new InsnList();
Type[] types = new Type[arguments.size()];
InsnList code = new InsnList();
List<Type> 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<Type> onStack, List<HookArgument> arguments)
{
String argumentsText = "the arguments " + arguments;
if (onStack.isEmpty()) return argumentsText;
return "the stack value(s) " + onStack.stream().map(Type::getDescriptor).toList() + " and " + argumentsText;
}
}
@@ -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:
*
* <pre>{@code
* return Hooks.hook(value, arguments);
* }</pre>
*
* 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<HookArgument> arguments;
private final Type returned;
protected ReturnHookPatch(String target, Anchor.Sequence anchor, Hook hook, List<HookArgument> 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));
}
}
@@ -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()) {});
}
}