Add mod validation for annotations: schemas, migrations, configuration bounds, listener methods, and commands.

This commit is contained in:
Overlord committed 2026-10-08 12:44:23 +02:00
1 parent 9af951b4be
commit c79a90b88f
10 files changed
+389 -18

No files matched your search

@@ -1,6 +1,7 @@
package dev.overlord.zomboidforge.tools;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.core.config.RecordBinder;
import dev.overlord.zomboidforge.core.config.TomlTree;
import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDescriptor;
@@ -8,16 +9,24 @@ import dev.overlord.zomboidforge.core.mods.ModDiscovery;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModVerifier;
import dev.overlord.zomboidforge.core.mods.ModVersion;
import dev.overlord.zomboidforge.core.runtime.ListenerScanner;
import dev.overlord.zomboidforge.core.storage.RecordSchema;
import dev.overlord.zomboidforge.patcher.GameVersionReader;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.RecordComponentNode;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -26,6 +35,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
@@ -41,9 +52,18 @@ import java.util.zip.ZipEntry;
* minimum version it satisfies;</li>
* <li>the game jar is one of the declared {@code game} versions;</li>
* <li>{@link ModVerifier}: game use requires {@code game} versions, every used game class
* and member exists in the game jar, no ZomboidForge internals.</li>
* and member exists in the game jar, no ZomboidForge internals;</li>
* <li>the annotations the server reads while it loads the mod, through the server's own
* rules: listener and scheduled methods of the entry point ({@link ListenerScanner}),
* {@code @Schema}/{@code @Migrate} ({@link RecordSchema}) and {@code @Key}/{@code @Min}/
* {@code @Max} ({@link RecordBinder}) on the jar's records that carry them, and the
* {@code @RegisterCommand} classes.</li>
* </ol>
*
* For the last check, the mod's classes are loaded without being initialized, so no mod code
* runs. Objects that a mod passes to {@code Events.register} at runtime are only checked on the
* server.
*
* <pre>
* java -jar mod-tools.jar --jar &lt;mod.jar&gt; [--game-jar &lt;projectzomboid.jar&gt;]
* [--library &lt;jar&gt;]... [--dependency &lt;mod jar&gt;]... [--report &lt;file&gt;]
@@ -57,7 +77,15 @@ import java.util.zip.ZipEntry;
*/
public final class ModCheck
{
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
private static final String MOD_CLASS = "dev/overlord/zomboidforge/api/Mod";
private static final String RECORD = "java/lang/Record";
private static final String ANNOTATION = "Ldev/overlord/zomboidforge/api/annotations/";
/** Annotations that make a record worth loading for {@link #checkAnnotations}. */
private static final Set<String> RECORD_ANNOTATIONS = Set.of(
ModCheck.ANNOTATION + "Schema;", ModCheck.ANNOTATION + "Migrate;",
ModCheck.ANNOTATION + "Key;", ModCheck.ANNOTATION + "Min;", ModCheck.ANNOTATION + "Max;"
);
/** The command-line arguments. */
public record Arguments(Path jar, @Nullable Path gameJar, List<Path> libraries, List<Path> dependencies, @Nullable Path report)
@@ -201,7 +229,9 @@ public final class ModCheck
{
if (!descriptor.game().isEmpty()) problems.add("The mod declares " + descriptor.game() + ", so the check needs '--game-jar'.");
ModCheck.verify(candidates, GameClasses.none(), null, problems);
Map<String, List<String>> commands = ModCheck.verify(candidates, GameClasses.none(), null, problems);
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
return new Result(descriptor, null, problems);
}
@@ -211,22 +241,147 @@ public final class ModCheck
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(gameVersion::matches))
problems.add("The game jar '" + gameJar + "' is Project Zomboid " + gameVersion + ", but the mod declares " + descriptor.game() + "; the check needs a game jar of a declared version.");
Map<String, List<String>> commands = Map.of();
try (GameClasses game = GameClasses.open(gameJar))
{
ModCheck.verify(candidates, game, gameVersion, problems);
commands = ModCheck.verify(candidates, game, gameVersion, problems);
}
catch (IOException e)
{
problems.add("Cannot read the game jar '" + gameJar + "': " + e.getMessage());
}
ModCheck.checkAnnotations(arguments, descriptor, commands.getOrDefault(descriptor.id(), List.of()), problems);
return new Result(descriptor, gameVersion, problems);
}
private static void verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
/** @return mod id to its {@code @RegisterCommand} classes; empty when the verifier found problems */
private static Map<String, List<String>> verify(List<ModDiscovery.Candidate> candidates, GameClasses game, @Nullable GameVersion version, List<String> problems)
{
try { ModVerifier.verify(candidates, game, version); }
try { return ModVerifier.verify(candidates, game, version); }
catch (ModLoadException e) { problems.addAll(e.problems()); }
return Map.of();
}
/**
* The annotation rules of the server, run on the mod's classes: the entry point's listener and
* scheduled methods, the records in the jar that carry {@code @Schema}, {@code @Migrate},
* {@code @Key}, {@code @Min}, or {@code @Max}, and the {@code @RegisterCommand} classes.
* Runs only when every other check passed, since classes that do not link cannot be loaded.
*
* @param commands binary names of the mod's {@code @RegisterCommand} classes
*/
private static void checkAnnotations(Arguments arguments, ModDescriptor descriptor, List<String> commands, List<String> problems)
{
if (!problems.isEmpty()) return;
List<Path> jars = new ArrayList<>();
jars.add(arguments.jar());
jars.addAll(arguments.libraries());
jars.addAll(arguments.dependencies());
if (arguments.gameJar() != null) jars.add(arguments.gameJar());
try (URLClassLoader loader = new URLClassLoader("mod-check", jars.stream().map(ModCheck::url).toArray(URL[]::new), ModCheck.class.getClassLoader()))
{
Class<?> entrypoint = ModCheck.load(loader, descriptor.entrypoint(), problems);
if (entrypoint != null) problems.addAll(ListenerScanner.check(entrypoint));
for (String name : ModCheck.annotatedRecords(arguments.jar(), problems))
{
Class<?> type = ModCheck.load(loader, name, problems);
if (type == null || !type.isRecord()) continue;
problems.addAll(RecordSchema.check(type.asSubclass(Record.class)));
problems.addAll(RecordBinder.check(type.asSubclass(Record.class)));
}
for (String name : commands)
{
Class<?> type = ModCheck.load(loader, name, problems);
if (type == null) continue;
int modifiers = type.getModifiers();
if (!Modifier.isPublic(modifiers)) problems.add("The command '" + name + "' (@RegisterCommand) is not public.");
if (Modifier.isAbstract(modifiers) || type.isInterface()) problems.add("The command '" + name + "' (@RegisterCommand) is abstract.");
if (descriptor.game().isEmpty()) problems.add("The command '" + name + "' (@RegisterCommand) needs Project Zomboid's command framework, so 'mod.toml' needs 'game' versions.");
}
}
catch (IOException e)
{
problems.add("Cannot close the class loader of the check: " + e.getMessage());
}
}
/** The class {@code name}, loaded without initializing it, or {@code null} after adding the problem. */
private static @Nullable Class<?> load(ClassLoader loader, String name, List<String> problems)
{
try
{
return Class.forName(name, false, loader);
}
catch (ClassNotFoundException | LinkageError e)
{
problems.add("Cannot load '" + name + "' to check its annotations: " + e + ".");
return null;
}
}
/** Binary names of the records in {@code jar} that carry one of {@link #RECORD_ANNOTATIONS}, on the record, a component, or a method. */
private static Set<String> annotatedRecords(Path jar, List<String> problems)
{
Set<String> records = new TreeSet<>();
try (JarFile file = new JarFile(jar.toFile()))
{
for (JarEntry entry : file.stream().toList())
{
String name = entry.getName();
if (!name.endsWith(".class") || name.startsWith("META-INF/")) continue;
ClassNode node = new ClassNode();
try (InputStream in = file.getInputStream(entry)) { new ClassReader(in.readAllBytes()).accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); }
if (ModCheck.RECORD.equals(node.superName) && ModCheck.carriesRecordAnnotation(node)) records.add(node.name.replace('/', '.'));
}
}
catch (IOException e)
{
problems.add("Cannot read '" + jar + "': " + e.getMessage());
}
return records;
}
private static boolean carriesRecordAnnotation(ClassNode node)
{
if (ModCheck.anyRecordAnnotation(node.visibleAnnotations)) return true;
for (MethodNode method : node.methods) {
if (ModCheck.anyRecordAnnotation(method.visibleAnnotations)) return true;
}
if (node.recordComponents != null) {
for (RecordComponentNode component : node.recordComponents) {
if (ModCheck.anyRecordAnnotation(component.visibleAnnotations)) return true;
}
}
return false;
}
private static boolean anyRecordAnnotation(@Nullable List<AnnotationNode> annotations)
{
return annotations != null && annotations.stream().anyMatch(annotation -> ModCheck.RECORD_ANNOTATIONS.contains(annotation.desc));
}
private static URL url(Path path)
{
try { return path.toUri().toURL(); }
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
}
private static ModDiscovery.Candidate candidate(Path jar, List<Path> libraries, ModDescriptor descriptor)
@@ -0,0 +1,7 @@
package checkmods;
import dev.overlord.zomboidforge.api.annotations.RegisterCommand;
/** A command class that tests package into a mod jar: neither public nor concrete. */
@RegisterCommand
abstract class AbstractCommand {}
@@ -0,0 +1,16 @@
package checkmods;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.annotations.Every;
import dev.overlord.zomboidforge.api.annotations.OnMain;
/** Entry point that tests package into a mod jar; its annotated methods break the rules. */
@SuppressWarnings("unused")
public class InvalidEntry extends Mod
{
@OnMain
void tick(String text) {}
@Every(0)
void report() {}
}
@@ -0,0 +1,21 @@
package checkmods;
import dev.overlord.zomboidforge.api.annotations.Key;
import dev.overlord.zomboidforge.api.annotations.Max;
import dev.overlord.zomboidforge.api.annotations.Min;
import dev.overlord.zomboidforge.api.annotations.Schema;
/** Records that tests package into a mod jar, with valid and invalid annotations. */
public final class Records
{
public record Fine(@Key("ok") @Min(1) int amount) {}
@Schema(version = 0)
public record BadSchema(long amount) {}
public record BadKey(@Key("Bad Key") int amount) {}
public record BadBounds(@Min(5) @Max(1) int amount) {}
private Records() {}
}
@@ -0,0 +1,21 @@
package checkmods;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.TickEvent;
import dev.overlord.zomboidforge.api.annotations.Every;
import dev.overlord.zomboidforge.api.annotations.EveryNTicks;
import dev.overlord.zomboidforge.api.annotations.OnMain;
/** Entry point that tests package into a mod jar; every annotated method follows the rules. */
@SuppressWarnings("unused")
public class ValidEntry extends Mod
{
@OnMain
void tick(TickEvent event) {}
@Every(1)
void report() {}
@EveryNTicks(2)
void sweep() {}
}
@@ -1,5 +1,9 @@
package dev.overlord.zomboidforge.tools;
import checkmods.InvalidEntry;
import checkmods.Records;
import checkmods.ValidEntry;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -7,6 +11,7 @@ import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -17,6 +22,7 @@ import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
@@ -67,6 +73,80 @@ class ModCheckTest
assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems());
}
@Test
void passesValidAnnotations() throws IOException
{
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class)
));
ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null));
assertEquals(List.of(), result.problems());
}
@Test
void reportsListenerAndScheduledMethodsThatBreakTheRules() throws IOException
{
Path mod = this.jar("shop.jar", ModCheckTest.toml(InvalidEntry.class), Map.of("checkmods/InvalidEntry", ModCheckTest.classFile(InvalidEntry.class)));
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
ModCheckTest.assertContainsAll(problems, "checkmods.InvalidEntry.tick", "java.lang.String", "checkmods.InvalidEntry.report");
}
@Test
void reportsRecordAnnotationsThatBreakTheRules() throws IOException
{
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
"checkmods/Records$Fine", ModCheckTest.classFile(Records.Fine.class),
"checkmods/Records$BadSchema", ModCheckTest.classFile(Records.BadSchema.class),
"checkmods/Records$BadKey", ModCheckTest.classFile(Records.BadKey.class),
"checkmods/Records$BadBounds", ModCheckTest.classFile(Records.BadBounds.class)
));
List<String> problems = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems();
assertEquals(3, problems.size(), String.valueOf(problems));
ModCheckTest.assertContainsAll(String.join("\n", problems), "Records$BadSchema", "Records$BadKey", "Bad Key", "Records$BadBounds");
}
@Test
void reportsRegisteredCommandsThatCannotBeRegistered() throws IOException
{
Path mod = this.jar("shop.jar", ModCheckTest.toml(ValidEntry.class), Map.of(
"checkmods/ValidEntry", ModCheckTest.classFile(ValidEntry.class),
"checkmods/AbstractCommand", ModCheckTest.classFile("checkmods/AbstractCommand")
));
String problems = String.join("\n", ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)).problems());
ModCheckTest.assertContainsAll(problems, "checkmods.AbstractCommand", "not public", "abstract", "'game'");
}
/** {@link #TOML} with {@code entrypoint} as the entry point. */
private static String toml(Class<?> entrypoint) { return ModCheckTest.TOML.replace("a.Main", entrypoint.getName()); }
/** The class file of a class on the test class path. */
private static byte[] classFile(Class<?> type) throws IOException { return ModCheckTest.classFile(type.getName().replace('.', '/')); }
/** The class file of the class {@code internalName} on the test class path. */
private static byte[] classFile(String internalName) throws IOException
{
try (InputStream in = ModCheckTest.class.getResourceAsStream("/" + internalName + ".class"))
{
if (in == null) throw new IOException("No class file for '" + internalName + "'.");
return in.readAllBytes();
}
}
private static void assertContainsAll(String message, String... parts)
{
for (String part : parts) assertTrue(message.contains(part), "'" + part + "' missing in: " + message);
}
/** A public class extending {@code superName} with a public constructor without parameters. */
private static byte[] type(String name, String superName)
{