/config.toml}, over the defaults in the mod's
+ * jar ({@code META-INF/zomboidforge/config.toml}). A key missing from the file takes the
+ * default. The table {@code [forge]} belongs to ZomboidForge and is not part of these settings.
+ *
+ * Keys are {@code snake_case}; record components and paths use the same names converted
+ * from {@code camelCase} ({@code maxBalance} reads {@code max_balance}).
+ */
+public interface ModConfig
+{
+ /**
+ * Creates a record from the settings. Supported component types: {@code String},
+ * {@code boolean}, {@code int}, {@code long}, {@code float}, {@code double} (and their
+ * wrappers), enums (by constant name), records (TOML tables), {@code List},
+ * {@code Map} (tables with free keys), and {@code Optional} for values that
+ * may be missing. Every other component must have a value. Keys without a component are
+ * logged as warnings.
+ *
+ * @throws IllegalStateException listing every missing or mistyped value
+ */
+ T bind(Class type);
+
+ /**
+ * The value at a dotted path, e.g. {@code "features.max_balance"}, converted like a record
+ * component of {@code type}. Primitive values use the wrapper types ({@code Long.class}).
+ *
+ * @throws IllegalStateException when the value exists but has another type
+ */
+ Optional get(String path, Class type);
+}
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 c85dab4..0ea3074 100644
--- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java
+++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java
@@ -22,4 +22,7 @@ public interface ModContext
/** The mod's folder, {@code /mods/}. */
Path directory();
+
+ /** The mod's settings from {@code config.toml}. */
+ ModConfig config();
}
diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java
index 91264e7..f7c377d 100644
--- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java
+++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java
@@ -7,6 +7,8 @@ import dev.overlord.zomboidforge.core.mods.ModLoadException;
import zombie.core.Core;
+import java.nio.file.Path;
+
/**
* Hooks called by patched {@code zombie.network.GameServer} code and its shutdown hook
* {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only
@@ -34,8 +36,10 @@ public final class ServerHooks
{
System.out.println("[ZomboidForge] " + ZomboidForge.VERSION + " loading mods.");
- GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion());
- ServerHooks.FORGE.load(game, ServerHooks.class.getClassLoader());
+ GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion());
+ Path gameJar = Path.of(Core.class.getProtectionDomain().getCodeSource().getLocation().toURI());
+
+ ServerHooks.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader());
return true;
}
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index 79386de..e36c8b5 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -7,6 +7,7 @@ plugins {
dependencies {
implementation(project(":api"))
implementation(libs.night.config.toml)
+ implementation(libs.asm)
testImplementation(libs.bundles.asm)
testImplementation(platform(libs.junit.bom))
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 d83f471..65153d8 100644
--- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java
@@ -3,14 +3,17 @@ package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.api.ZomboidForge;
+import dev.overlord.zomboidforge.core.mods.GameClasses;
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModLoader;
import dev.overlord.zomboidforge.core.mods.ModResolver;
+import dev.overlord.zomboidforge.core.mods.ModVerifier;
import dev.overlord.zomboidforge.core.mods.ModVersion;
import org.jetbrains.annotations.Nullable;
+import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -70,20 +73,35 @@ public final class Forge
* Discovers, checks, and loads every mod in {@code /mods}. Called once on the
* main thread.
*
- * @param parent parent of the mods' class loaders
+ * @param gameJar the Project Zomboid jar the server runs
+ * @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge
* @throws ModLoadException listing every problem found
*/
- public void load(GameVersion game, ClassLoader parent) throws ModLoadException
+ public void load(GameVersion game, Path gameJar, ClassLoader parent) throws ModLoadException
{
Path modsDirectory = this.directory.resolve(Forge.MODS);
if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked.");
List candidates = Files.isDirectory(modsDirectory)
- ? ModDiscovery.discover(modsDirectory)
+ ? ModDiscovery.discover(modsDirectory, this.logger)
: List.of();
- this.mods = ModLoader.load(ModResolver.resolve(candidates, game, this.api), game, parent);
+ List disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).toList();
+ if (!disabled.isEmpty()) this.logger.log(System.Logger.Level.INFO, "Disabled in config.toml: " + String.join(", ", disabled) + ".");
+
+ List ordered = ModResolver.resolve(candidates, game, this.api);
+
+ try (GameClasses gameClasses = GameClasses.open(gameJar))
+ {
+ ModVerifier.verify(ordered, gameClasses, game);
+ this.mods = ModLoader.load(ordered, game, parent, gameClasses);
+ }
+ catch (IOException e)
+ {
+ throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e);
+ }
+
this.lifecycle.loaded();
this.logger.log(System.Logger.Level.INFO, this.mods.isEmpty()
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java
new file mode 100644
index 0000000..8842705
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/RecordBinder.java
@@ -0,0 +1,212 @@
+package dev.overlord.zomboidforge.core.config;
+
+import org.jetbrains.annotations.Nullable;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.RecordComponent;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Collectors;
+
+/**
+ * Converts {@link TomlTree} values to records and other Java types. Collects every problem
+ * instead of stopping at the first one, and records the keys no component reads.
+ */
+public final class RecordBinder
+{
+ private final List problems = new ArrayList<>();
+ private final Set unknownKeys = new TreeSet<>();
+
+ public List problems() { return List.copyOf(this.problems); }
+
+ /** Dotted paths of keys that no record component reads, sorted. */
+ public Set unknownKeys() { return Set.copyOf(this.unknownKeys); }
+
+ /** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */
+ public static String key(String component)
+ {
+ StringBuilder key = new StringBuilder(component.length() + 4);
+
+ for (int i = 0; i < component.length(); i++)
+ {
+ char c = component.charAt(i);
+ boolean upper = Character.isUpperCase(c);
+ boolean afterLower = i > 0 && !Character.isUpperCase(component.charAt(i - 1));
+ boolean wordStart = i > 0 && i + 1 < component.length() && Character.isUpperCase(component.charAt(i - 1)) && Character.isLowerCase(component.charAt(i + 1));
+
+ if (upper && (afterLower || wordStart)) key.append('_');
+ key.append(Character.toLowerCase(c));
+ }
+
+ return key.toString();
+ }
+
+ /** A record of {@code type} from {@code table}, or {@code null} when a problem was found. */
+ public @Nullable T record(Map table, Class type, String path)
+ {
+ RecordComponent[] components = type.getRecordComponents();
+ @Nullable Object[] arguments = new Object[components.length];
+ Set keys = new TreeSet<>(table.keySet());
+ int before = this.problems.size();
+
+ for (int i = 0; i < components.length; i++)
+ {
+ String key = RecordBinder.key(components[i].getName());
+ keys.remove(key);
+
+ arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key));
+ }
+
+ for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key));
+
+ // value() returns null only after recording a problem, so past this check no argument is null.
+ if (this.problems.size() > before) return null;
+
+ try
+ {
+ Constructor constructor = type.getDeclaredConstructor(Arrays.stream(components).map(RecordComponent::getType).toArray(Class>[]::new));
+ constructor.setAccessible(true);
+
+ return constructor.newInstance(arguments);
+ }
+ catch (InvocationTargetException e)
+ {
+ this.problems.add("'" + (path.isEmpty() ? "" : path) + "': " + type.getSimpleName() + " rejected the values: " + e.getCause() + ".");
+ return null;
+ }
+ catch (ReflectiveOperationException e)
+ {
+ throw new IllegalStateException("Cannot create record '" + type.getName() + "'.", e);
+ }
+ }
+
+ /**
+ * {@code raw} converted to {@code target}, or {@code null} after recording a problem.
+ * {@code raw == null} means the key is missing.
+ */
+ public @Nullable Object value(@Nullable Object raw, Type target, String path)
+ {
+ Class> type = RecordBinder.rawType(target);
+
+ if (type == Optional.class)
+ {
+ if (raw == null) return Optional.empty();
+
+ Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path);
+ return element == null ? null : Optional.of(element);
+ }
+
+ if (raw == null) return this.problem(path, "is missing");
+
+ if (type == String.class) return raw instanceof String ? raw : this.mistyped(path, "a string", raw);
+ if (type == boolean.class || type == Boolean.class) return raw instanceof Boolean ? raw : this.mistyped(path, "true or false", raw);
+ if (type == long.class || type == Long.class) return raw instanceof Long ? raw : this.mistyped(path, "an integer", raw);
+ if (type == int.class || type == Integer.class) return this.integer(raw, path);
+ if (type == double.class || type == Double.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).doubleValue() : this.mistyped(path, "a number", raw);
+ if (type == float.class || type == Float.class) return raw instanceof Long || raw instanceof Double ? ((Number) raw).floatValue() : this.mistyped(path, "a number", raw);
+ if (type.isEnum()) return this.constant(raw, type, path);
+ if (type.isRecord()) return raw instanceof Map, ?> table ? this.record(TomlTree.cast(table), type.asSubclass(Record.class), path) : this.mistyped(path, "a table", raw);
+ if (type == List.class) return this.list(raw, RecordBinder.typeArgument(target, 0), path);
+ if (type == Map.class) return this.map(raw, target, path);
+
+ throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have.");
+ }
+
+ private @Nullable Object integer(Object raw, String path)
+ {
+ if (!(raw instanceof Long number)) return this.mistyped(path, "an integer", raw);
+ if (number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) return this.problem(path, "must be between " + Integer.MIN_VALUE + " and " + Integer.MAX_VALUE + ", found " + number);
+
+ return number.intValue();
+ }
+
+ private @Nullable Object constant(Object raw, Class> type, String path)
+ {
+ Object[] constants = type.getEnumConstants();
+
+ if (raw instanceof String name) {
+ for (Object constant : constants) {
+ if (((Enum>) constant).name().equalsIgnoreCase(name)) return constant;
+ }
+ }
+
+ String allowed = Arrays.stream(constants).map(constant -> "\"" + ((Enum>) constant).name().toLowerCase(Locale.ROOT) + "\"").collect(Collectors.joining(", "));
+ return this.mistyped(path, "one of " + allowed, raw);
+ }
+
+ private @Nullable Object list(Object raw, Type element, String path)
+ {
+ if (!(raw instanceof List> list)) return this.mistyped(path, "a list", raw);
+
+ List values = new ArrayList<>(list.size());
+ int before = this.problems.size();
+
+ for (int i = 0; i < list.size(); i++)
+ {
+ Object value = this.value(list.get(i), element, path + "[" + i + "]");
+ if (value != null) values.add(value);
+ }
+
+ return this.problems.size() > before ? null : List.copyOf(values);
+ }
+
+ private @Nullable Object map(Object raw, Type target, String path)
+ {
+ if (RecordBinder.typeArgument(target, 0) != String.class)
+ throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys.");
+
+ if (!(raw instanceof Map, ?> table)) return this.mistyped(path, "a table", raw);
+
+ Map values = new LinkedHashMap<>();
+ int before = this.problems.size();
+
+ for (Map.Entry entry : TomlTree.cast(table).entrySet())
+ {
+ Object value = this.value(entry.getValue(), RecordBinder.typeArgument(target, 1), RecordBinder.join(path, entry.getKey()));
+ if (value != null) values.put(entry.getKey(), value);
+ }
+
+ return this.problems.size() > before ? null : Map.copyOf(values);
+ }
+
+ private @Nullable Object mistyped(String path, String expected, Object raw)
+ {
+ String found = raw instanceof Map, ?> ? "a table" : raw instanceof List> ? "a list" : raw instanceof String text ? "\"" + text + "\"" : String.valueOf(raw);
+ return this.problem(path, "must be " + expected + ", found " + found);
+ }
+
+ private @Nullable Object problem(String path, String message)
+ {
+ this.problems.add("'" + path + "' " + message + ".");
+ return null;
+ }
+
+ private static Class> rawType(Type type)
+ {
+ return switch (type)
+ {
+ case Class> clazz -> clazz;
+ case ParameterizedType parameters -> (Class>) parameters.getRawType();
+ default -> throw new IllegalArgumentException("Configuration values cannot have the type '" + type.getTypeName() + "'.");
+ };
+ }
+
+ private static Type typeArgument(Type type, int index)
+ {
+ if (type instanceof ParameterizedType parameters) return parameters.getActualTypeArguments()[index];
+
+ throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records.");
+ }
+
+ private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; }
+}
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlModConfig.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlModConfig.java
new file mode 100644
index 0000000..91a9748
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlModConfig.java
@@ -0,0 +1,58 @@
+package dev.overlord.zomboidforge.core.config;
+
+import dev.overlord.zomboidforge.api.ModConfig;
+
+import java.util.Map;
+import java.util.Optional;
+
+/** {@link ModConfig} over the merged {@link TomlTree} of a mod's {@code config.toml}. */
+public final class TomlModConfig implements ModConfig
+{
+ private final Map values;
+ private final System.Logger logger;
+
+ /**
+ * @param values the settings without the {@code [forge]} table
+ * @param logger receives warnings about keys no record component reads
+ */
+ public TomlModConfig(Map values, System.Logger logger)
+ {
+ this.values = Map.copyOf(values);
+ this.logger = logger;
+ }
+
+ @Override
+ public T bind(Class type)
+ {
+ RecordBinder binder = new RecordBinder();
+ T record = binder.record(this.values, type, "");
+
+ if (record == null || !binder.problems().isEmpty())
+ throw new IllegalStateException("config.toml does not match '" + type.getSimpleName() + "': " + String.join(" ", binder.problems()));
+
+ for (String key : binder.unknownKeys()) this.logger.log(System.Logger.Level.WARNING, "config.toml: unknown key '" + key + "'.");
+
+ return record;
+ }
+
+ @Override
+ public Optional get(String path, Class type)
+ {
+ Object value = this.values;
+
+ for (String key : path.split("\\."))
+ {
+ if (!(value instanceof Map, ?> table)) return Optional.empty();
+
+ value = table.get(key);
+ if (value == null) return Optional.empty();
+ }
+
+ RecordBinder binder = new RecordBinder();
+ Object converted = binder.value(value, type, path);
+
+ if (converted == null) throw new IllegalStateException("config.toml: " + String.join(" ", binder.problems()));
+
+ return Optional.of(type.cast(converted));
+ }
+}
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlTree.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlTree.java
new file mode 100644
index 0000000..472bd23
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/TomlTree.java
@@ -0,0 +1,81 @@
+package dev.overlord.zomboidforge.core.config;
+
+import com.electronwill.nightconfig.core.UnmodifiableConfig;
+import com.electronwill.nightconfig.core.io.ParsingException;
+import com.electronwill.nightconfig.toml.TomlParser;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * TOML documents as plain Java values: tables become {@code Map}, arrays
+ * {@code List}, integers {@code Long}, floats {@code Double}; strings and booleans stay
+ * as they are. Dates and times keep the types of the parser.
+ */
+public final class TomlTree
+{
+ private TomlTree() {}
+
+ /** @throws IllegalArgumentException when {@code toml} is not valid TOML */
+ public static Map parse(String toml)
+ {
+ try { return TomlTree.table(new TomlParser().parse(toml)); }
+ catch (ParsingException e) { throw new IllegalArgumentException("Not valid TOML: " + e.getMessage(), e); }
+ }
+
+ /**
+ * {@code overrides} over {@code defaults}: tables are merged key by key, every other value of
+ * {@code overrides} replaces the default.
+ */
+ public static Map merge(Map defaults, Map overrides)
+ {
+ Map merged = new LinkedHashMap<>(defaults);
+
+ for (Map.Entry entry : overrides.entrySet())
+ {
+ Object defaultValue = merged.get(entry.getKey());
+
+ if (defaultValue instanceof Map, ?> defaultTable && entry.getValue() instanceof Map, ?> table)
+ merged.put(entry.getKey(), TomlTree.merge(TomlTree.cast(defaultTable), TomlTree.cast(table)));
+ else
+ merged.put(entry.getKey(), entry.getValue());
+ }
+
+ return merged;
+ }
+
+ private static Map table(UnmodifiableConfig config)
+ {
+ Map table = new LinkedHashMap<>();
+
+ for (UnmodifiableConfig.Entry entry : config.entrySet()) table.put(entry.getKey(), TomlTree.value(entry.getRawValue()));
+
+ return table;
+ }
+
+ private static Object value(Object raw)
+ {
+ return switch (raw)
+ {
+ case UnmodifiableConfig config -> TomlTree.table(config);
+ case List> list -> TomlTree.list(list);
+ case Integer number -> number.longValue();
+ case Float number -> number.doubleValue();
+ default -> raw;
+ };
+ }
+
+ private static List list(List> raw)
+ {
+ List list = new ArrayList<>(raw.size());
+
+ for (Object element : raw) list.add(TomlTree.value(element));
+
+ return list;
+ }
+
+ @SuppressWarnings("unchecked")
+ static Map cast(Map, ?> table) { return (Map) table; }
+}
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/package-info.java
new file mode 100644
index 0000000..53d38bc
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/package-info.java
@@ -0,0 +1,9 @@
+/**
+ * TOML configuration: parsing into plain maps, merging over defaults, and binding to records.
+ *
+ * @noinspection UnstableApiUsage, RedundantSuppression
+ */
+@NotNullByDefault
+package dev.overlord.zomboidforge.core.config;
+
+import org.jetbrains.annotations.NotNullByDefault;
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/GameClasses.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/GameClasses.java
new file mode 100644
index 0000000..42dabd9
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/GameClasses.java
@@ -0,0 +1,82 @@
+package dev.overlord.zomboidforge.core.mods;
+
+import org.jetbrains.annotations.Nullable;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.ZipFile;
+
+/**
+ * The classes of the Project Zomboid jar (game code and the libraries it bundles). The names
+ * stay available after {@link #close()}; the class files can be read until then.
+ */
+public final class GameClasses implements AutoCloseable
+{
+ private static final String CLASS_SUFFIX = ".class";
+ private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
+
+ private final JarFile file;
+ private final Set classes;
+ private final Set packages;
+
+ private GameClasses(JarFile file, Set classes, Set packages)
+ {
+ this.file = file;
+ this.classes = Set.copyOf(classes);
+ this.packages = Set.copyOf(packages);
+ }
+
+ /** Indexes {@code jar}; multi-release entries count for their base name. */
+ public static GameClasses open(Path jar) throws IOException
+ {
+ JarFile file = new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, Runtime.version());
+ Set classes = new HashSet<>();
+ Set packages = new HashSet<>();
+
+ for (JarEntry entry : file.stream().toList())
+ {
+ String name = entry.getName();
+ Matcher versioned = GameClasses.VERSIONED.matcher(name);
+
+ if (versioned.matches()) name = versioned.group(1);
+ if (!name.endsWith(GameClasses.CLASS_SUFFIX) || name.startsWith("META-INF/")) continue;
+
+ String internalName = name.substring(0, name.length() - GameClasses.CLASS_SUFFIX.length());
+ classes.add(internalName);
+ packages.add(GameClasses.packageOf(internalName));
+ }
+
+ return new GameClasses(file, classes, packages);
+ }
+
+ /** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
+ public boolean contains(String internalName) { return this.classes.contains(internalName); }
+
+ /** Whether the jar contains classes in the package of this internal class name. */
+ public boolean containsPackageOf(String internalName) { return this.packages.contains(GameClasses.packageOf(internalName)); }
+
+ /** The class file for the running Java version, or {@code null} when the jar has none. */
+ byte @Nullable [] read(String internalName) throws IOException
+ {
+ JarEntry entry = this.file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
+ if (entry == null) return null;
+
+ try (InputStream in = this.file.getInputStream(entry)) { return in.readAllBytes(); }
+ }
+
+ @Override
+ public void close() throws IOException { this.file.close(); }
+
+ static String packageOf(String internalName)
+ {
+ int slash = internalName.lastIndexOf('/');
+ return slash < 0 ? "" : internalName.substring(0, slash);
+ }
+}
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/JdkPackages.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/JdkPackages.java
new file mode 100644
index 0000000..ed120d0
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/JdkPackages.java
@@ -0,0 +1,35 @@
+package dev.overlord.zomboidforge.core.mods;
+
+import org.jetbrains.annotations.Nullable;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Packages of the modules in the boot layer (the JDK), with the class loader of each. */
+final class JdkPackages
+{
+ private static final Map LOADERS = JdkPackages.loaders();
+
+ private JdkPackages() {}
+
+ /** The loader for a class of the JDK package {@code dottedPackage}, or {@code null} for other packages. */
+ static @Nullable ClassLoader loader(String dottedPackage) { return JdkPackages.LOADERS.get(dottedPackage); }
+
+ /** Whether the class with this internal name, e.g. {@code java/util/List}, is in a JDK package. */
+ static boolean contains(String internalName) { return JdkPackages.LOADERS.containsKey(GameClasses.packageOf(internalName).replace('/', '.')); }
+
+ private static Map loaders()
+ {
+ Map loaders = new HashMap<>();
+
+ for (Module module : ModuleLayer.boot().modules())
+ {
+ // Modules of the boot loader report null; the platform loader delegates to it.
+ ClassLoader loader = module.getClassLoader() == null ? ClassLoader.getPlatformClassLoader() : module.getClassLoader();
+
+ for (String name : module.getPackages()) loaders.put(name, loader);
+ }
+
+ return Map.copyOf(loaders);
+ }
+}
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java
index c0d52dc..1d0004e 100644
--- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModClassLoader.java
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.core.mods;
+import org.jetbrains.annotations.Nullable;
+
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
@@ -13,36 +15,86 @@ import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
- * Class loader of one mod, over its jar and its {@code lib/} jars. Classes are looked up in the
- * parent first, then in the mod's own jars, then in the own jars (not the libraries) of the
- * mod's declared dependencies.
+ * Class loader of one mod, over its jar and its {@code lib/} jars. Lookup order:
+ *
+ *
+ * JDK classes, from the loader of their module;
+ * the ZomboidForge API ({@code dev.overlord.zomboidforge.api}, without {@code .internal}),
+ * from the parent;
+ * the mod's own jar and libraries;
+ * the own jars (not the libraries) of the mod's declared dependencies;
+ * classes of the Project Zomboid jar, from the parent, only for mods that declare
+ * {@code game} versions.
+ *
+ *
+ * Everything else on the parent's class path, such as ZomboidForge's own classes and libraries,
+ * is not visible. A mod's own copy of a library that the game also bundles takes precedence.
*/
final class ModClassLoader extends URLClassLoader
{
+ private static final String API = "dev.overlord.zomboidforge.api.";
+ private static final String API_INTERNAL = "dev.overlord.zomboidforge.api.internal.";
+
static { ClassLoader.registerAsParallelCapable(); }
+ private final String id;
private final Set ownClasses;
private final List dependencies;
+ private final @Nullable GameClasses game;
- ModClassLoader(String id, Path jar, List libraries, ClassLoader parent, List dependencies)
+ /** @param game the game's classes, or {@code null} when the mod declares no {@code game} versions */
+ ModClassLoader(String id, Path jar, List libraries, ClassLoader parent, List dependencies, @Nullable GameClasses game)
{
super("mod:" + id, ModClassLoader.urls(jar, libraries), parent);
+ this.id = id;
this.ownClasses = ModClassLoader.classNames(jar);
this.dependencies = List.copyOf(dependencies);
+ this.game = game;
}
+ /** Whether a class with this binary name is part of the mod API. */
+ static boolean isApi(String name) { return name.startsWith(ModClassLoader.API) && !name.startsWith(ModClassLoader.API_INTERNAL); }
+
@Override
- protected Class> findClass(String name) throws ClassNotFoundException
+ protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
- try { return super.findClass(name); }
+ synchronized (this.getClassLoadingLock(name))
+ {
+ Class> type = this.findLoadedClass(name);
+ if (type == null) type = this.lookUp(name);
+ if (resolve) this.resolveClass(type);
+
+ return type;
+ }
+ }
+
+ /** Resources of the mod's own jars first, then the parent's. */
+ @Override
+ public @Nullable URL getResource(String name)
+ {
+ URL own = this.findResource(name);
+ return own != null ? own : super.getResource(name);
+ }
+
+ private Class> lookUp(String name) throws ClassNotFoundException
+ {
+ int dot = name.lastIndexOf('.');
+ ClassLoader jdk = JdkPackages.loader(dot < 0 ? "" : name.substring(0, dot));
+
+ if (jdk != null) return jdk.loadClass(name);
+ if (ModClassLoader.isApi(name)) return this.getParent().loadClass(name);
+
+ try { return this.findClass(name); }
catch (ClassNotFoundException e) { /* not in the mod's own jars */ }
for (ModClassLoader dependency : this.dependencies) {
if (dependency.ownClasses.contains(name)) return dependency.loadClass(name);
}
- throw new ClassNotFoundException(name);
+ if (this.game != null && this.game.contains(name.replace('.', '/'))) return this.getParent().loadClass(name);
+
+ throw new ClassNotFoundException(name + " (not visible to mod '" + this.id + "')");
}
private static URL[] urls(Path jar, List libraries)
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModDiscovery.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModDiscovery.java
index b29fc9f..722c035 100644
--- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModDiscovery.java
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModDiscovery.java
@@ -1,12 +1,19 @@
package dev.overlord.zomboidforge.core.mods;
+import dev.overlord.zomboidforge.core.config.TomlTree;
+
+import org.jetbrains.annotations.Nullable;
+
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
@@ -23,25 +30,44 @@ import java.util.zip.ZipEntry;
*/
public final class ModDiscovery
{
- private static final String JAR_SUFFIX = ".jar";
- private static final String LIBRARIES = "lib";
+ /** Location of the default settings inside a mod's jar. */
+ public static final String DEFAULT_CONFIG = "META-INF/zomboidforge/config.toml";
+ public static final String CONFIG = "config.toml";
- /** A mod folder whose descriptor was read. */
- public record Candidate(Path directory, Path jar, List libraries, ModDescriptor descriptor)
+ private static final String JAR_SUFFIX = ".jar";
+ private static final String LIBRARIES = "lib";
+ private static final String FORGE_TABLE = "forge";
+ private static final String ENABLED = "enabled";
+
+ /**
+ * A mod folder whose descriptor and settings were read.
+ *
+ * @param enabled {@code [forge] enabled} from the settings; {@code true} when missing
+ * @param config the settings over the defaults from the jar, without the {@code [forge]} table
+ */
+ public record Candidate(Path directory, Path jar, List libraries, ModDescriptor descriptor, boolean enabled, Map config)
{
- public Candidate { libraries = List.copyOf(libraries); }
+ public Candidate
+ {
+ libraries = List.copyOf(libraries);
+ config = Map.copyOf(config);
+ }
public String id() { return this.descriptor.id(); }
}
+ private record JarContents(String descriptor, byte @Nullable [] defaultConfig) {}
+
private ModDiscovery() {}
/**
- * Reads every mod folder in {@code modsDirectory}, sorted by folder name.
+ * Reads every mod folder in {@code modsDirectory}, sorted by folder name. Writes the default
+ * settings of a mod to {@code config.toml} when the folder has none and is writable.
*
+ * @param logger receives notes about written or unwritable default settings
* @throws ModLoadException listing the problems of every folder
*/
- public static List discover(Path modsDirectory) throws ModLoadException
+ public static List discover(Path modsDirectory, System.Logger logger) throws ModLoadException
{
List candidates = new ArrayList<>();
List problems = new ArrayList<>();
@@ -57,7 +83,7 @@ public final class ModDiscovery
continue;
}
- try { candidates.add(ModDiscovery.read(entry)); }
+ try { candidates.add(ModDiscovery.read(entry, logger)); }
catch (ModLoadException e) { e.problems().forEach(problem -> problems.add("'" + name + "': " + problem)); }
}
@@ -66,7 +92,7 @@ public final class ModDiscovery
return candidates;
}
- private static Candidate read(Path directory) throws ModLoadException
+ private static Candidate read(Path directory, System.Logger logger) throws ModLoadException
{
String name = directory.getFileName().toString();
Path jar = directory.resolve(name + ModDiscovery.JAR_SUFFIX);
@@ -79,7 +105,8 @@ public final class ModDiscovery
if (!Files.isRegularFile(jar)) problems.add("'" + jar.getFileName() + "' is missing.");
if (!problems.isEmpty()) throw new ModLoadException(problems);
- ModDescriptor descriptor = ModDiscovery.descriptor(jar);
+ JarContents contents = ModDiscovery.contents(jar);
+ ModDescriptor descriptor = ModDiscovery.descriptor(contents.descriptor());
if (!descriptor.id().equals(name)) throw new ModLoadException(List.of("The folder is named '" + name + "', but 'mod.toml' declares the id '" + descriptor.id() + "'."));
Path libraryDirectory = directory.resolve(ModDiscovery.LIBRARIES);
@@ -87,22 +114,106 @@ public final class ModDiscovery
? ModDiscovery.sortedEntries(libraryDirectory).stream().filter(ModDiscovery::isJar).toList()
: List.of();
- return new Candidate(directory, jar, libraries, descriptor);
+ Map config = ModDiscovery.config(directory, contents.defaultConfig(), logger, problems);
+ boolean enabled = ModDiscovery.enabled(config.remove(ModDiscovery.FORGE_TABLE), problems);
+
+ if (!problems.isEmpty()) throw new ModLoadException(problems);
+
+ return new Candidate(directory, jar, libraries, descriptor, enabled, config);
}
- private static ModDescriptor descriptor(Path jar) throws ModLoadException
+ /** The folder's {@code config.toml} over the jar's defaults, as a mutable map. */
+ private static Map config(Path directory, byte @Nullable [] defaultConfig, System.Logger logger, List problems)
{
- String toml;
+ Path file = directory.resolve(ModDiscovery.CONFIG);
+ Map defaults = Map.of();
+ Map settings = Map.of();
+ if (defaultConfig != null)
+ {
+ try
+ {
+ defaults = TomlTree.parse(new String(defaultConfig, StandardCharsets.UTF_8));
+ }
+ catch (IllegalArgumentException e)
+ {
+ // Invalid defaults are reported and never copied to the folder.
+ problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "' in the jar: " + e.getMessage());
+ return new LinkedHashMap<>();
+ }
+ }
+
+ if (Files.isRegularFile(file))
+ {
+ try { settings = TomlTree.parse(Files.readString(file)); }
+ catch (IOException e) { problems.add("Cannot read '" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
+ catch (IllegalArgumentException e) { problems.add("'" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
+ }
+ else if (defaultConfig != null)
+ {
+ String id = directory.getFileName().toString();
+
+ try
+ {
+ Files.write(file, defaultConfig, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
+ logger.log(System.Logger.Level.INFO, "'" + id + "': wrote the default settings to '" + file + "'.");
+ }
+ catch (IOException | UnsupportedOperationException e)
+ {
+ logger.log(System.Logger.Level.INFO, "'" + id + "': cannot write the default settings to '" + file + "' (" + e + "); using them without a file.");
+ }
+ }
+
+ return TomlTree.merge(defaults, settings);
+ }
+
+ /** {@code [forge] enabled}; {@code true} without a {@code [forge]} table. */
+ private static boolean enabled(@Nullable Object forge, List problems)
+ {
+ if (forge == null) return true;
+
+ if (!(forge instanceof Map, ?> table)) {
+ problems.add("'" + ModDiscovery.CONFIG + "': 'forge' must be a table ([forge]).");
+ return true;
+ }
+
+ boolean enabled = true;
+
+ for (Map.Entry, ?> entry : table.entrySet())
+ {
+ if (!ModDiscovery.ENABLED.equals(entry.getKey()))
+ problems.add("'" + ModDiscovery.CONFIG + "': unknown key 'forge." + entry.getKey() + "'; [forge] only has 'enabled'.");
+ else if (entry.getValue() instanceof Boolean value)
+ enabled = value;
+ else
+ problems.add("'" + ModDiscovery.CONFIG + "': 'forge.enabled' must be true or false.");
+ }
+
+ return enabled;
+ }
+
+ private static JarContents contents(Path jar) throws ModLoadException
+ {
try (JarFile file = new JarFile(jar.toFile()))
{
- ZipEntry entry = file.getEntry(ModDescriptor.PATH);
- if (entry == null) throw new ModLoadException(List.of("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'."));
+ byte[] descriptor = ModDiscovery.entry(file, ModDescriptor.PATH);
+ if (descriptor == null) throw new ModLoadException(List.of("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'."));
- try (InputStream in = file.getInputStream(entry)) { toml = new String(in.readAllBytes(), StandardCharsets.UTF_8); }
+ return new JarContents(new String(descriptor, StandardCharsets.UTF_8), ModDiscovery.entry(file, ModDiscovery.DEFAULT_CONFIG));
}
catch (IOException e) { throw new ModLoadException("Cannot read '" + jar.getFileName() + "': " + e.getMessage(), e); }
+ }
+ private static byte @Nullable [] entry(JarFile file, String name) throws IOException
+ {
+ ZipEntry entry = file.getEntry(name);
+ if (entry == null) return null;
+
+ try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
+ }
+
+ private static ModDescriptor descriptor(String toml) throws ModLoadException
+ {
try { return ModDescriptor.parse(toml); }
catch (ModLoadException e) { throw new ModLoadException(e.problems().stream().map(problem -> "mod.toml: " + problem).toList()); }
}
@@ -112,6 +223,6 @@ public final class ModDiscovery
private static List sortedEntries(Path directory) throws ModLoadException
{
try (Stream entries = Files.list(directory)) { return entries.sorted().toList(); }
- catch (IOException e) { throw new ModLoadException("Cannot list '" + directory + "': " + e.getMessage(), e); }
+ catch (IOException e) { throw new ModLoadException("Cannot list '" + directory + "': " + e.getMessage(), e); }
}
}
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 2df05fd..e81c2f2 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
@@ -2,9 +2,13 @@ package dev.overlord.zomboidforge.core.mods;
import dev.overlord.zomboidforge.api.GameVersion;
import dev.overlord.zomboidforge.api.Mod;
+import dev.overlord.zomboidforge.api.ModConfig;
import dev.overlord.zomboidforge.api.ModContext;
import dev.overlord.zomboidforge.api.internal.ModBinding;
import dev.overlord.zomboidforge.core.ConsoleLogger;
+import dev.overlord.zomboidforge.core.config.TomlModConfig;
+
+import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.lang.reflect.Constructor;
@@ -26,16 +30,19 @@ public final class ModLoader
/** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
- private record Context(String id, String version, GameVersion gameVersion, System.Logger logger, Path directory) implements ModContext {}
+ private record Context(String id, String version, GameVersion gameVersion, System.Logger logger, Path directory, ModConfig config) implements ModContext {}
private ModLoader() {}
/**
- * @param ordered mods in load order, as returned by {@link ModResolver#resolve}
- * @param parent parent of every mod's class loader
+ * @param ordered mods in load order, as returned by {@link ModResolver#resolve} and checked
+ * by {@link ModVerifier#verify}
+ * @param parent parent of every mod's class loader
+ * @param gameClasses classes of the Project Zomboid jar, visible to mods that declare
+ * {@code game} versions
* @throws ModLoadException naming the mod that failed and why
*/
- public static List load(List ordered, GameVersion game, ClassLoader parent) throws ModLoadException
+ public static List load(List ordered, GameVersion game, ClassLoader parent, GameClasses gameClasses) throws ModLoadException
{
Map loaders = new HashMap<>();
List loaded = new ArrayList<>();
@@ -51,15 +58,18 @@ public final class ModLoader
.map(dependency -> Objects.requireNonNull(loaders.get(dependency), "'" + dependency + "' is not loaded before '" + descriptor.id() + "'."))
.toList();
- ModClassLoader loader = new ModClassLoader(descriptor.id(), candidate.jar(), candidate.libraries(), parent, dependencies);
+ @Nullable GameClasses visible = descriptor.game().isEmpty() ? null : gameClasses;
+ ModClassLoader loader = new ModClassLoader(descriptor.id(), candidate.jar(), candidate.libraries(), parent, dependencies, visible);
loaders.put(descriptor.id(), loader);
- Context context = new Context(
+ System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id());
+ Context context = new Context(
descriptor.id(),
descriptor.version().toString(),
game,
- new ConsoleLogger("ZomboidForge/" + descriptor.id()),
- candidate.directory()
+ logger,
+ candidate.directory(),
+ new TomlModConfig(candidate.config(), logger)
);
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
@@ -88,16 +98,16 @@ public final class ModLoader
}
catch (InvocationTargetException e)
{
- throw new ModLoadException("'" + id + "': the constructor of '" + descriptor.entrypoint() + "' threw " + e.getCause() + ".", e.getCause());
+ throw new ModLoadException(ModLoader.sentence("'" + id + "': the constructor of '" + descriptor.entrypoint() + "' threw " + e.getCause()), e.getCause());
}
catch (ReflectiveOperationException | LinkageError e)
{
- throw new ModLoadException("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e + ".", e);
+ throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
}
try { mod.onLoad(); }
- catch (Exception e) { throw new ModLoadException("'" + id + "': onLoad() threw " + e + ".", e); }
- catch (LinkageError e) { throw new ModLoadException("'" + id + "': onLoad() failed with " + e + ".", e); }
+ catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
+ catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
return mod;
}
@@ -110,7 +120,7 @@ public final class ModLoader
Class> type;
try { type = Class.forName(entrypoint, false, loader); }
- catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException("'" + id + "': entry point '" + entrypoint + "' cannot be loaded: " + e + ".", e); }
+ catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': entry point '" + entrypoint + "' cannot be loaded: " + e), e); }
if (!Mod.class.isAssignableFrom(type))
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' does not extend '" + Mod.class.getName() + "'."));
@@ -122,6 +132,9 @@ public final class ModLoader
catch (NoSuchMethodException e) { throw new ModLoadException("'" + id + "': entry point '" + entrypoint + "' has no public constructor without parameters.", e); }
}
+ /** {@code text} ending with a period; exception messages often have one already. */
+ private static String sentence(String text) { return text.endsWith(".") ? text : text + "."; }
+
private static void close(Iterable loaders)
{
for (ModClassLoader loader : loaders) {
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java
index 497daeb..1a68189 100644
--- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java
@@ -24,13 +24,16 @@ public final class ModResolver
private ModResolver() {}
/**
+ * Returns the enabled mods in load order; disabled mods are left out.
+ *
* @param api the running ZomboidForge API version, or {@code null} to skip the API check
* (development builds)
- * @throws ModLoadException listing every problem of every mod
+ * @throws ModLoadException listing every problem of every enabled mod
*/
public static List resolve(List candidates, GameVersion game, @Nullable ModVersion api) throws ModLoadException
{
- Map byId = candidates.stream().collect(Collectors.toMap(ModDiscovery.Candidate::id, Function.identity(), (a, b) -> a, TreeMap::new));
+ Map byId = candidates.stream().filter(ModDiscovery.Candidate::enabled).collect(Collectors.toMap(ModDiscovery.Candidate::id, Function.identity(), (a, b) -> a, TreeMap::new));
+ Set disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).collect(Collectors.toSet());
List problems = new ArrayList<>();
for (ModDiscovery.Candidate candidate : byId.values())
@@ -48,7 +51,9 @@ public final class ModResolver
{
ModDiscovery.Candidate installed = byId.get(dependency.getKey());
- if (installed == null)
+ if (installed == null && disabled.contains(dependency.getKey()))
+ problems.add("'" + id + "': requires '" + dependency.getKey() + "', which is disabled in its config.toml.");
+ else if (installed == null)
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, which is not installed.");
else if (installed.descriptor().version().compareTo(dependency.getValue()) < 0)
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, " + installed.descriptor().version() + " is installed.");
diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java
new file mode 100644
index 0000000..d1caab6
--- /dev/null
+++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVerifier.java
@@ -0,0 +1,383 @@
+package dev.overlord.zomboidforge.core.mods;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+
+import org.jetbrains.annotations.Nullable;
+
+import org.objectweb.asm.ClassReader;
+import org.objectweb.asm.ClassVisitor;
+import org.objectweb.asm.FieldVisitor;
+import org.objectweb.asm.Handle;
+import org.objectweb.asm.Label;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.Opcodes;
+import org.objectweb.asm.RecordComponentVisitor;
+import org.objectweb.asm.Type;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.nio.file.Path;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.stream.Collectors;
+
+/**
+ * Checks the classes of resolved mods before any of them is loaded:
+ *
+ *
+ * no class in a ZomboidForge package, and no class in the mod's own jar with the name of a
+ * game class;
+ * no use of ZomboidForge classes outside the API;
+ * a mod that uses classes of the Project Zomboid jar declares {@code game} versions;
+ * every game class, field, and method such a mod uses exists in the running jar
+ * (members are looked up through superclasses and interfaces).
+ *
+ *
+ * Annotations are not checked: the JVM does not load annotation types a class only carries.
+ */
+public final class ModVerifier
+{
+ private static final String FORGE = "dev/overlord/zomboidforge/";
+ private static final String API = "dev/overlord/zomboidforge/api/";
+ private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/";
+ private static final int EXAMPLES = 5;
+
+ /** A field or method that a mod's code uses. */
+ private record Member(boolean method, String owner, String name, String desc) implements Comparable
+ {
+ @Override
+ public int compareTo(Member other) { return this.toString().compareTo(other.toString()); }
+
+ @Override
+ public String toString() { return this.owner.replace('/', '.') + "." + this.name + (this.method ? "" : ":") + this.desc; }
+ }
+
+ private ModVerifier() {}
+
+ /**
+ * @param ordered mods in load order, as returned by {@link ModResolver#resolve}
+ * @throws ModLoadException listing every problem of every mod
+ */
+ public static void verify(List ordered, GameClasses game, GameVersion version) throws ModLoadException
+ {
+ Hierarchy hierarchy = new Hierarchy(game);
+ Map> ownByMod = new HashMap<>();
+ List problems = new ArrayList<>();
+
+ for (ModDiscovery.Candidate candidate : ordered)
+ {
+ String id = candidate.id();
+ Map own = ModVerifier.classes(candidate.jar());
+ Map libraries = new TreeMap<>();
+
+ for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library));
+
+ ownByMod.put(id, own.keySet());
+
+ Set provided = new HashSet<>(own.keySet());
+ provided.addAll(libraries.keySet());
+ for (String dependency : candidate.descriptor().dependencies().keySet()) provided.addAll(ownByMod.getOrDefault(dependency, Set.of()));
+
+ Set contained = new TreeSet<>(own.keySet());
+ contained.addAll(libraries.keySet());
+
+ for (String name : contained) {
+ if (name.startsWith(ModVerifier.FORGE)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is in a ZomboidForge package.");
+ }
+
+ for (String name : new TreeSet<>(own.keySet())) {
+ if (game.contains(name)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is a class of Project Zomboid.");
+ }
+
+ References references = new References();
+ for (byte[] bytes : own.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
+ for (byte[] bytes : libraries.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
+
+ Set gameTypes = new TreeSet<>();
+ Set missingTypes = new TreeSet<>();
+
+ for (String type : references.types)
+ {
+ if (JdkPackages.contains(type) || provided.contains(type)) continue;
+
+ if (type.startsWith(ModVerifier.FORGE) && (!type.startsWith(ModVerifier.API) || type.startsWith(ModVerifier.API_INTERNAL)))
+ problems.add("'" + id + "': uses '" + ModVerifier.dotted(type) + "', which is internal to ZomboidForge.");
+ else if (game.contains(type))
+ gameTypes.add(type);
+ else if (!type.startsWith(ModVerifier.FORGE) && game.containsPackageOf(type))
+ missingTypes.add(type);
+ }
+
+ boolean declaresGame = !candidate.descriptor().game().isEmpty();
+
+ if (!declaresGame && !(gameTypes.isEmpty() && missingTypes.isEmpty()))
+ {
+ Set used = new TreeSet<>(gameTypes);
+ used.addAll(missingTypes);
+
+ problems.add("'" + id + "': uses classes of the Project Zomboid jar (" + ModVerifier.examples(used) + ") but declares no 'game' versions in mod.toml.");
+ continue;
+ }
+
+ List linkage = new ArrayList<>();
+
+ for (String type : missingTypes) linkage.add("'" + ModVerifier.dotted(type) + "'");
+
+ for (Member member : references.members) {
+ if (gameTypes.contains(member.owner()) && !hierarchy.has(member)) linkage.add("'" + member + "'");
+ }
+
+ if (!linkage.isEmpty())
+ problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in Project Zomboid " + version + ".");
+ }
+
+ if (!problems.isEmpty()) throw new ModLoadException(problems);
+ }
+
+ /** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */
+ private static Map classes(Path jar)
+ {
+ Map classes = new TreeMap<>();
+
+ 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/") || name.endsWith("module-info.class")) continue;
+
+ try (InputStream in = file.getInputStream(entry)) { classes.put(name.substring(0, name.length() - ".class".length()), in.readAllBytes()); }
+ }
+ }
+ catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
+
+ return classes;
+ }
+
+ /** The first {@value #EXAMPLES} elements, quoted unless already quoted, and how many more there are. */
+ private static String examples(Iterable elements)
+ {
+ List all = new ArrayList<>();
+ for (String element : elements) all.add(element.startsWith("'") ? element : "'" + ModVerifier.dotted(element) + "'");
+
+ String shown = all.stream().limit(ModVerifier.EXAMPLES).collect(Collectors.joining(", "));
+ return all.size() > ModVerifier.EXAMPLES ? shown + " and " + (all.size() - ModVerifier.EXAMPLES) + " more" : shown;
+ }
+
+ private static String dotted(String internalName) { return internalName.replace('/', '.'); }
+
+ /** Collects the classes and members that code uses; skips annotations and debug information. */
+ private static final class References extends ClassVisitor
+ {
+ private final Set types = new TreeSet<>();
+ private final Set members = new TreeSet<>();
+
+ private References() { super(Opcodes.ASM9); }
+
+ @Override
+ public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces)
+ {
+ if (superName != null) this.type(superName);
+ if (interfaces != null) for (String type : interfaces) this.type(type);
+ }
+
+ @Override
+ public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
+ {
+ this.descriptor(descriptor);
+ return null;
+ }
+
+ @Override
+ public @Nullable RecordComponentVisitor visitRecordComponent(String name, String descriptor, @Nullable String signature)
+ {
+ this.descriptor(descriptor);
+ return null;
+ }
+
+ @Override
+ public MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
+ {
+ this.descriptor(descriptor);
+ if (exceptions != null) for (String type : exceptions) this.type(type);
+
+ References references = this;
+
+ return new MethodVisitor(Opcodes.ASM9)
+ {
+ @Override
+ public void visitTypeInsn(int opcode, String type) { references.type(type); }
+
+ @Override
+ public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { references.member(false, owner, name, descriptor); }
+
+ @Override
+ public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) { references.member(true, owner, name, descriptor); }
+
+ @Override
+ public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrap, Object... arguments)
+ {
+ references.descriptor(descriptor);
+ references.constant(bootstrap);
+
+ for (Object argument : arguments) references.constant(argument);
+ }
+
+ @Override
+ public void visitLdcInsn(Object value) { references.constant(value); }
+
+ @Override
+ public void visitMultiANewArrayInsn(String descriptor, int dimensions) { references.descriptor(descriptor); }
+
+ @Override
+ public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type)
+ {
+ if (type != null) references.type(type);
+ }
+ };
+ }
+
+ private void member(boolean method, String owner, String name, String descriptor)
+ {
+ this.type(owner);
+ this.descriptor(descriptor);
+
+ if (!owner.startsWith("[")) this.members.add(new Member(method, owner, name, descriptor));
+ }
+
+ private void constant(Object value)
+ {
+ switch (value)
+ {
+ case Handle handle -> this.member(handle.getTag() > Opcodes.H_PUTSTATIC, handle.getOwner(), handle.getName(), handle.getDesc());
+ case Type type -> this.descriptor(type.getDescriptor());
+ default -> { /* numbers, strings, dynamic constants */ }
+ }
+ }
+
+ /** An internal class name, or an array descriptor as used by {@code anewarray} and {@code checkcast}. */
+ private void type(String name)
+ {
+ if (name.startsWith("[")) this.descriptor(name);
+ else this.types.add(name);
+ }
+
+ private void descriptor(String descriptor)
+ {
+ Type type = Type.getType(descriptor);
+
+ if (type.getSort() == Type.METHOD)
+ {
+ for (Type argument : type.getArgumentTypes()) this.add(argument);
+ this.add(type.getReturnType());
+ }
+ else this.add(type);
+ }
+
+ private void add(Type type)
+ {
+ Type element = type.getSort() == Type.ARRAY ? type.getElementType() : type;
+ if (element.getSort() == Type.OBJECT) this.types.add(element.getInternalName());
+ }
+ }
+
+ /** Fields and methods of game and JDK classes, read from their class files. */
+ private static final class Hierarchy
+ {
+ private record Info(@Nullable String superName, List interfaces, Set fields, Set methods) {}
+
+ private final GameClasses game;
+ private final Map cache = new HashMap<>();
+
+ private Hierarchy(GameClasses game) { this.game = game; }
+
+ /**
+ * Whether {@code member} resolves in its owner, a superclass, or a superinterface.
+ * Constructors only count in the owner. Supertypes whose class files cannot be read
+ * count as having every member.
+ */
+ private boolean has(Member member)
+ {
+ String key = member.name() + member.desc();
+ Deque pending = new ArrayDeque<>(List.of(member.owner()));
+ Set seen = new HashSet<>();
+
+ while (!pending.isEmpty())
+ {
+ String type = pending.pop();
+ if (!seen.add(type)) continue;
+
+ Info info = this.info(type);
+ if (info == null) return !type.equals(member.owner());
+
+ if ((member.method() ? info.methods() : info.fields()).contains(key)) return true;
+ if (member.method() && member.name().equals("")) return false;
+
+ if (info.superName() != null) pending.add(info.superName());
+ pending.addAll(info.interfaces());
+ }
+
+ // Interface methods may also be declared by java.lang.Object.
+ return member.method() && !member.owner().equals("java/lang/Object") && this.has(new Member(true, "java/lang/Object", member.name(), member.desc()));
+ }
+
+ private @Nullable Info info(String type)
+ {
+ if (this.cache.containsKey(type)) return this.cache.get(type);
+
+ Info info = null;
+
+ try
+ {
+ byte[] bytes = this.game.contains(type) ? this.game.read(type) : JdkPackages.contains(type) ? Hierarchy.jdkClass(type) : null;
+ if (bytes != null) info = Hierarchy.read(bytes);
+ }
+ catch (IOException e) { throw new UncheckedIOException("Cannot read class '" + type + "'.", e); }
+
+ this.cache.put(type, info);
+ return info;
+ }
+
+ private static byte @Nullable [] jdkClass(String type) throws IOException
+ {
+ try (InputStream in = ClassLoader.getSystemResourceAsStream(type + ".class")) { return in == null ? null : in.readAllBytes(); }
+ }
+
+ private static Info read(byte[] bytes)
+ {
+ ClassReader reader = new ClassReader(bytes);
+ Set fields = new HashSet<>();
+ Set methods = new HashSet<>();
+
+ reader.accept(new ClassVisitor(Opcodes.ASM9)
+ {
+ @Override
+ public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
+ {
+ fields.add(name + descriptor);
+ return null;
+ }
+
+ @Override
+ public @Nullable MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
+ {
+ methods.add(name + descriptor);
+ return null;
+ }
+ }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
+
+ return new Info(reader.getSuperName(), List.of(reader.getInterfaces()), fields, methods);
+ }
+ }
+}
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 175cfc0..8a502ee 100644
--- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java
@@ -1,24 +1,29 @@
package dev.overlord.zomboidforge.core;
import dev.overlord.zomboidforge.api.GameVersion;
-import dev.overlord.zomboidforge.api.Mod;
import dev.overlord.zomboidforge.core.mods.ModLoadException;
import dev.overlord.zomboidforge.core.mods.ModVersion;
import dev.overlord.zomboidforge.core.mods.TestMods;
+import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import testmods.ContextMod;
+import testmods.Recorder;
+
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -26,46 +31,55 @@ class ForgeTest
{
private static final GameVersion GAME = GameVersion.parse("42.21.0");
+ /** Mods that call {@link Recorder} use the fake game jar, so they declare {@code game}. */
+ private static final String USES_GAME = "game = [\"42\"]\n";
+
@TempDir
Path directory;
private Path mods;
-
- /** Entry point on the test class path; records what its context returns in the constructor. */
- public static final class ContextMod extends Mod
- {
- public static ContextMod instance;
-
- public final String idInConstructor = this.id();
- public final GameVersion gameInConstructor = this.gameVersion();
- public final Path directoryInConstructor = this.directory();
-
- public ContextMod() { ContextMod.instance = this; }
- }
+ private Path gameJar;
@BeforeEach
void setUp() throws IOException
{
- this.mods = Files.createDirectories(this.directory.resolve("mods"));
- TestMods.Recorder.EVENTS.clear();
+ this.mods = Files.createDirectories(this.directory.resolve("mods"));
+ this.gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
+
+ Recorder.EVENTS.clear();
}
private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); }
+ private Forge load() throws ModLoadException
+ {
+ Forge forge = this.forge();
+ forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader());
+
+ return forge;
+ }
+
+ /** {@link ContextMod} and its settings record, packaged as the mod {@code context}. */
+ private void contextMod(String extra, @Nullable String defaultConfig) throws IOException
+ {
+ TestMods.folder(this.mods, "context", TestMods.toml("context", ContextMod.class.getName(), extra), defaultConfig, Map.of(
+ "testmods/ContextMod", TestMods.classFile(ContextMod.class),
+ "testmods/ContextMod$Settings", TestMods.classFile(ContextMod.Settings.class)
+ ));
+ }
+
@Test
void loadsStartsAndStopsModsInDependencyOrder() throws Exception
{
- TestMods.folder(this.mods, "shop", TestMods.toml("shop", "shop.ShopMod", "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
+ TestMods.folder(this.mods, "shop", TestMods.toml("shop", "shop.ShopMod", ForgeTest.USES_GAME + "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
"shop/ShopMod", TestMods.modClass("shop/ShopMod", "shop", "economy/Accounts", false)
));
- TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ""), Map.of(
+ TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of(
"economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false),
"economy/Accounts", TestMods.pingClass("economy/Accounts")
));
- Forge forge = this.forge();
-
- forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
+ Forge forge = this.load();
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
assertEquals(List.of("economy", "shop"), forge.mods().stream().map(mod -> mod.descriptor().id()).toList());
@@ -80,23 +94,68 @@ class ForgeTest
"economy:onServerStarted", "shop:onServerStarted",
"shop:onStopping", "economy:onStopping"
),
- TestMods.Recorder.EVENTS
+ Recorder.EVENTS
);
}
@Test
- void modsSeeTheirContextInTheConstructor() throws Exception
+ void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
{
- TestMods.folder(this.mods, "context", TestMods.toml("context", ContextMod.class.getName(), ""), Map.of());
+ this.contextMod("", """
+ greeting = "default"
+ limit = 5
- Forge forge = this.forge();
- forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
+ [prices]
+ apple = 3
+ """);
+ Files.writeString(this.mods.resolve("context").resolve("config.toml"), "greeting = \"hi\"\n");
- ContextMod mod = ContextMod.instance;
- assertSame(mod, forge.mods().getFirst().mod());
- assertEquals("context", mod.idInConstructor);
- assertEquals(ForgeTest.GAME, mod.gameInConstructor);
- assertEquals(this.mods.resolve("context"), mod.directoryInConstructor);
+ Object mod = this.load().mods().getFirst().mod();
+
+ assertNotSame(ContextMod.class, mod.getClass(), "the mod class comes from the mod's jar");
+ assertEquals("context", ForgeTest.field(mod, "idInConstructor"));
+ assertEquals(ForgeTest.GAME, ForgeTest.field(mod, "gameInConstructor"));
+ assertEquals(this.mods.resolve("context"), ForgeTest.field(mod, "directoryInConstructor"));
+ assertEquals("Settings[greeting=hi, limit=5, extra=Optional.empty, prices={apple=3}]", ForgeTest.field(mod, "settings").toString());
+ }
+
+ @Test
+ void writesTheDefaultSettingsWhenTheFolderHasNone() throws Exception
+ {
+ String defaults = "greeting = \"default\"\nlimit = 5\n[prices]\n";
+ this.contextMod("", defaults);
+
+ this.load();
+
+ assertEquals(defaults, Files.readString(this.mods.resolve("context").resolve("config.toml")));
+ }
+
+ @Test
+ void failsWhenTheSettingsDoNotMatchTheRecord() throws IOException
+ {
+ this.contextMod("", "greeting = 7\n");
+
+ ModLoadException e = assertThrows(ModLoadException.class, this::load);
+
+ assertEquals(
+ List.of("'context': the constructor of 'testmods.ContextMod' threw java.lang.IllegalStateException: config.toml does not match 'Settings': 'greeting' must be a string, found 7. 'limit' is missing. 'prices' is missing."),
+ e.problems()
+ );
+ }
+
+ @Test
+ void skipsDisabledModsAndFailsTheirDependents() throws Exception
+ {
+ this.contextMod("", null);
+ Files.writeString(this.mods.resolve("context").resolve("config.toml"), "[forge]\nenabled = false\n");
+
+ Forge forge = this.load();
+ assertTrue(forge.mods().isEmpty());
+
+ TestMods.folder(this.mods, "needs", TestMods.toml("needs", "needs.Mod", "[dependencies]\ncontext = \"1.0\"\n"), Map.of());
+
+ ModLoadException e = assertThrows(ModLoadException.class, this::load);
+ assertEquals(List.of("'needs': requires 'context', which is disabled in its config.toml."), e.problems());
}
@Test
@@ -112,8 +171,7 @@ class ForgeTest
{
Files.delete(this.mods);
- Forge forge = this.forge();
- forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader());
+ Forge forge = this.load();
assertTrue(forge.mods().isEmpty());
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
@@ -122,12 +180,12 @@ class ForgeTest
@Test
void failsWhenOnLoadThrows() throws IOException
{
- TestMods.folder(this.mods, "broken", TestMods.toml("broken", "broken.BrokenMod", ""), Map.of(
+ TestMods.folder(this.mods, "broken", TestMods.toml("broken", "broken.BrokenMod", ForgeTest.USES_GAME), Map.of(
"broken/BrokenMod", TestMods.modClass("broken/BrokenMod", "broken", null, true)
));
Forge forge = this.forge();
- ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
+ ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader()));
assertEquals(List.of("'broken': onLoad() threw java.lang.IllegalStateException: broken."), e.problems());
assertEquals(Lifecycle.Phase.BOOTING, forge.phase());
@@ -136,17 +194,30 @@ class ForgeTest
@Test
void failsWhenTheEntryPointIsNoMod() throws IOException
{
- TestMods.folder(this.mods, "plain", TestMods.toml("plain", "plain.Accounts", ""), Map.of(
+ TestMods.folder(this.mods, "plain", TestMods.toml("plain", "plain.Accounts", ForgeTest.USES_GAME), Map.of(
"plain/Accounts", TestMods.pingClass("plain/Accounts")
));
TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.Gone", ""), Map.of());
- ModLoadException missing = assertThrows(ModLoadException.class, () -> this.forge().load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
- assertEquals(List.of("'missing': entry point 'missing.Gone' cannot be loaded: java.lang.ClassNotFoundException: missing.Gone."), missing.problems());
+ ModLoadException missing = assertThrows(ModLoadException.class, this::load);
+ assertEquals(List.of("'missing': entry point 'missing.Gone' cannot be loaded: java.lang.ClassNotFoundException: missing.Gone (not visible to mod 'missing')."), missing.problems());
- Files.walk(this.mods.resolve("missing")).sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
+ try (Stream paths = Files.walk(this.mods.resolve("missing"))) { paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); }
- ModLoadException plain = assertThrows(ModLoadException.class, () -> this.forge().load(ForgeTest.GAME, ForgeTest.class.getClassLoader()));
+ ModLoadException plain = assertThrows(ModLoadException.class, this::load);
assertEquals(List.of("'plain': entry point 'plain.Accounts' does not extend 'dev.overlord.zomboidforge.api.Mod'."), plain.problems());
}
+
+ @Test
+ void settingsOfOptionalValues() throws Exception
+ {
+ this.contextMod("", "greeting = \"a\"\nlimit = 1\nextra = \"b\"\n[prices]\n");
+
+ Object mod = this.load().mods().getFirst().mod();
+ Object settings = ForgeTest.field(mod, "settings");
+
+ assertEquals(Optional.of("b"), settings.getClass().getMethod("extra").invoke(settings));
+ }
+
+ private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); }
}
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java
new file mode 100644
index 0000000..24787dd
--- /dev/null
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/config/TomlModConfigTest.java
@@ -0,0 +1,136 @@
+package dev.overlord.zomboidforge.core.config;
+
+import dev.overlord.zomboidforge.core.ConsoleLogger;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class TomlModConfigTest
+{
+ private enum Mode { EASY, HARD }
+
+ private record Limits(int perDay, double factor) {}
+
+ private record Settings(
+ String greeting,
+ boolean enabled,
+ long maxBalance,
+ float ratio,
+ Mode mode,
+ List admins,
+ Map prices,
+ Limits limits,
+ Optional motd,
+ Optional httpPort
+ ) {}
+
+ private static TomlModConfig config(String defaults, String settings)
+ {
+ return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test"));
+ }
+
+ @Test
+ void bindsEverySupportedTypeOverDefaults()
+ {
+ TomlModConfig config = TomlModConfigTest.config("""
+ greeting = "default"
+ enabled = true
+ max_balance = 100
+ ratio = 0.5
+ mode = "easy"
+ admins = ["a"]
+
+ [prices]
+ apple = 3
+
+ [limits]
+ per_day = 10
+ factor = 1.5
+ """, """
+ greeting = "hi"
+ mode = "HARD"
+ http_port = 8080
+ unused = 1
+
+ [limits]
+ per_day = 20
+ """);
+
+ assertEquals(
+ new Settings("hi", true, 100, 0.5F, Mode.HARD, List.of("a"), Map.of("apple", 3L), new Limits(20, 1.5), Optional.empty(), Optional.of(8080)),
+ config.bind(Settings.class)
+ );
+ }
+
+ @Test
+ void reportsEveryProblem()
+ {
+ TomlModConfig config = TomlModConfigTest.config("", """
+ greeting = 1
+ enabled = "yes"
+ mode = "medium"
+ admins = ["a", 2]
+ prices = 5
+ http_port = 99999999999
+
+ [limits]
+ per_day = 1.5
+ """);
+
+ IllegalStateException e = assertThrows(IllegalStateException.class, () -> config.bind(Settings.class));
+
+ assertEquals(
+ "config.toml does not match 'Settings': "
+ + "'greeting' must be a string, found 1. "
+ + "'enabled' must be true or false, found \"yes\". "
+ + "'max_balance' is missing. "
+ + "'ratio' is missing. "
+ + "'mode' must be one of \"easy\", \"hard\", found \"medium\". "
+ + "'admins[1]' must be a string, found 2. "
+ + "'prices' must be a table, found 5. "
+ + "'limits.per_day' must be an integer, found 1.5. "
+ + "'limits.factor' is missing. "
+ + "'http_port' must be between -2147483648 and 2147483647, found 99999999999.",
+ e.getMessage()
+ );
+ }
+
+ @Test
+ void readsSingleValuesByPath()
+ {
+ TomlModConfig config = TomlModConfigTest.config("[limits]\nper_day = 10\n", "");
+
+ assertEquals(Optional.of(10L), config.get("limits.per_day", Long.class));
+ assertEquals(Optional.of(10), config.get("limits.per_day", Integer.class));
+ assertEquals(Optional.empty(), config.get("limits.other", Long.class));
+ assertEquals(Optional.empty(), config.get("missing.per_day", Long.class));
+ assertThrows(IllegalStateException.class, () -> config.get("limits.per_day", String.class));
+ }
+
+ @Test
+ void convertsComponentNamesToKeys()
+ {
+ assertEquals("max_balance", RecordBinder.key("maxBalance"));
+ assertEquals("http_port", RecordBinder.key("httpPort"));
+ assertEquals("http_port", RecordBinder.key("HTTPPort"));
+ assertEquals("api_key2", RecordBinder.key("apiKey2"));
+ assertEquals("name", RecordBinder.key("name"));
+ }
+
+ @Test
+ void mergesTablesKeyByKey()
+ {
+ Map merged = TomlTree.merge(
+ TomlTree.parse("a = 1\n[t]\nx = 1\ny = 2\n"),
+ TomlTree.parse("b = 2.5\n[t]\ny = 3\n")
+ );
+
+ assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged);
+ }
+}
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModClassLoaderTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModClassLoaderTest.java
new file mode 100644
index 0000000..adaf27e
--- /dev/null
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModClassLoaderTest.java
@@ -0,0 +1,104 @@
+package dev.overlord.zomboidforge.core.mods;
+
+import org.jetbrains.annotations.Nullable;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class ModClassLoaderTest
+{
+ @TempDir
+ Path directory;
+
+ private GameClasses game;
+ private URLClassLoader parent;
+
+ @BeforeEach
+ void setUp() throws IOException
+ {
+ Path gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
+
+ this.game = GameClasses.open(gameJar);
+ this.parent = new URLClassLoader(new URL[]{gameJar.toUri().toURL()}, ModClassLoaderTest.class.getClassLoader());
+ }
+
+ @AfterEach
+ void tearDown() throws IOException
+ {
+ this.game.close();
+ this.parent.close();
+ }
+
+ private ModClassLoader loader(String id, Map own, Map library, List dependencies, @Nullable GameClasses game) throws IOException
+ {
+ Path jar = this.directory.resolve(id + ".jar");
+ Path lib = this.directory.resolve(id + "-lib.jar");
+
+ TestMods.jar(jar, null, own);
+ TestMods.jar(lib, null, library);
+
+ return new ModClassLoader(id, jar, List.of(lib), this.parent, dependencies, game);
+ }
+
+ @Test
+ void seesTheJdkAndTheApiButNotZomboidForgeInternals() throws Exception
+ {
+ try (ModClassLoader loader = this.loader("plain", Map.of(), Map.of(), List.of(), null))
+ {
+ assertSame(String.class, loader.loadClass("java.lang.String"));
+ assertSame(java.sql.Connection.class, loader.loadClass("java.sql.Connection"));
+ assertSame(dev.overlord.zomboidforge.api.Mod.class, loader.loadClass("dev.overlord.zomboidforge.api.Mod"));
+
+ assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.api.internal.ModBinding"));
+ assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.core.Forge"));
+ assertThrows(ClassNotFoundException.class, () -> loader.loadClass("org.junit.jupiter.api.Test"));
+ }
+ }
+
+ @Test
+ void seesGameClassesOnlyWithDeclaredGameVersions() throws Exception
+ {
+ try (ModClassLoader without = this.loader("without", Map.of(), Map.of(), List.of(), null);
+ ModClassLoader with = this.loader("with", Map.of(), Map.of(), List.of(), this.game))
+ {
+ ClassNotFoundException e = assertThrows(ClassNotFoundException.class, () -> without.loadClass("zombie.core.Core"));
+ assertEquals("zombie.core.Core (not visible to mod 'without')", e.getMessage());
+
+ assertSame(this.parent.loadClass("zombie.core.Core"), with.loadClass("zombie.core.Core"));
+ }
+ }
+
+ @Test
+ void ownLibrariesTakePrecedenceOverGameLibraries() throws Exception
+ {
+ Map shared = Map.of("com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null));
+
+ try (ModClassLoader loader = this.loader("bundled", Map.of(), shared, List.of(), this.game))
+ {
+ assertSame(loader, loader.loadClass("com.example.Shared").getClassLoader());
+ }
+ }
+
+ @Test
+ void dependenciesShareTheirOwnJarButNotTheirLibraries() throws Exception
+ {
+ try (ModClassLoader economy = this.loader("economy", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of("economy/lib/Util", TestMods.type("economy/lib/Util", "java/lang/Object", null)), List.of(), null);
+ ModClassLoader shop = this.loader("shop", Map.of(), Map.of(), List.of(economy), null))
+ {
+ assertSame(economy.loadClass("economy.Accounts"), shop.loadClass("economy.Accounts"));
+ assertThrows(ClassNotFoundException.class, () -> shop.loadClass("economy.lib.Util"));
+ }
+ }
+}
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModDiscoveryTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModDiscoveryTest.java
index dbbdb30..ed29827 100644
--- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModDiscoveryTest.java
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModDiscoveryTest.java
@@ -1,5 +1,7 @@
package dev.overlord.zomboidforge.core.mods;
+import dev.overlord.zomboidforge.core.ConsoleLogger;
+
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -14,6 +16,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
class ModDiscoveryTest
{
+ private static final System.Logger LOGGER = new ConsoleLogger("test");
+
@TempDir
Path mods;
@@ -30,7 +34,7 @@ class ModDiscoveryTest
Files.writeString(economy.resolve("config.toml"), "");
Files.writeString(this.mods.resolve(".hidden"), "");
- List candidates = ModDiscovery.discover(this.mods);
+ List candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
assertEquals(List.of("economy", "shop"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
assertEquals(economy.resolve("economy.jar"), candidates.getFirst().jar());
@@ -51,7 +55,7 @@ class ModDiscoveryTest
TestMods.folder(this.mods, "plain", null, Map.of());
TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", "colour = \"red\"\n"), Map.of());
- ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods));
+ ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
assertEquals(
List.of(
@@ -65,4 +69,33 @@ class ModDiscoveryTest
e.problems()
);
}
+
+ @Test
+ void readsTheForgeTableAndReportsBadSettings() throws Exception
+ {
+ Path off = TestMods.folder(this.mods, "off", TestMods.toml("off", "a.Off", ""), Map.of());
+ Files.writeString(off.resolve("config.toml"), "[forge]\nenabled = false\n");
+
+ Path typo = TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", ""), Map.of());
+ Files.writeString(typo.resolve("config.toml"), "[forge]\nenable = false\nenabled = \"no\"\n");
+
+ Path broken = TestMods.folder(this.mods, "broken", TestMods.toml("broken", "a.Broken", ""), Map.of());
+ Files.writeString(broken.resolve("config.toml"), "limit = \n");
+
+ TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge\n", Map.of());
+
+ ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
+
+ assertEquals(List.of("author", "broken", "typo", "typo"), e.problems().stream().map(problem -> problem.substring(1, problem.indexOf("'", 1))).toList());
+ assertEquals("'typo': 'config.toml': unknown key 'forge.enable'; [forge] only has 'enabled'.", e.problems().get(2));
+ assertEquals("'typo': 'config.toml': 'forge.enabled' must be true or false.", e.problems().get(3));
+
+ Files.delete(typo.resolve("config.toml"));
+ Files.writeString(broken.resolve("config.toml"), "");
+ TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge]\nenabled = false\n", Map.of());
+
+ List candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
+ assertEquals(List.of("author", "broken", "off", "typo"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
+ assertEquals(List.of(false, true, false, true), candidates.stream().map(ModDiscovery.Candidate::enabled).toList());
+ }
}
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModResolverTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModResolverTest.java
index 9ab2d87..c743a36 100644
--- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModResolverTest.java
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModResolverTest.java
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -19,7 +20,7 @@ class ModResolverTest
private static ModDiscovery.Candidate mod(String id, String extra) throws ModLoadException
{
Path directory = Path.of("mods", id);
- return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)));
+ return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
}
/** A mod built against API 0.4. */
@@ -28,7 +29,7 @@ class ModResolverTest
Path directory = Path.of("mods", id);
String toml = TestMods.toml(id, "a.Mod", "").replace("api = \"0.3\"", "api = \"0.4\"");
- return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(toml));
+ return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(toml), true, Map.of());
}
private static List order(ModDiscovery.Candidate... candidates) throws ModLoadException
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java
new file mode 100644
index 0000000..ff4febd
--- /dev/null
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVerifierTest.java
@@ -0,0 +1,147 @@
+package dev.overlord.zomboidforge.core.mods;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class ModVerifierTest
+{
+ private static final GameVersion GAME = GameVersion.parse("42.21.0");
+ private static final String CORE = "zombie/core/Core";
+
+ @TempDir
+ Path directory;
+
+ private GameClasses game;
+
+ @BeforeEach
+ void setUp() throws IOException { this.game = GameClasses.open(TestMods.gameJar(this.directory.resolve("projectzomboid.jar"))); }
+
+ @AfterEach
+ void tearDown() throws IOException { this.game.close(); }
+
+ private ModDiscovery.Candidate mod(String id, String extra, Map classes, Map library) throws Exception
+ {
+ Path folder = TestMods.folder(this.directory.resolve("mods"), id, TestMods.toml(id, "a.Mod", extra), classes);
+ List libraries = List.of();
+
+ if (!library.isEmpty()) {
+ Path jar = Files.createDirectories(folder.resolve("lib")).resolve("library.jar");
+ TestMods.jar(jar, null, library);
+ libraries = List.of(jar);
+ }
+
+ return new ModDiscovery.Candidate(folder, folder.resolve(id + ".jar"), libraries, ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
+ }
+
+ private List problems(ModDiscovery.Candidate... candidates)
+ {
+ ModLoadException e = assertThrows(ModLoadException.class, () -> ModVerifier.verify(List.of(candidates), this.game, ModVerifierTest.GAME));
+ return e.problems();
+ }
+
+ @Test
+ void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception
+ {
+ ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
+ TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
+ TestMods.Use.virtualCall(ModVerifierTest.CORE, "inherited", "()V"),
+ TestMods.Use.virtualCall(ModVerifierTest.CORE, "toString", "()Ljava/lang/String;"),
+ TestMods.Use.field(ModVerifierTest.CORE, "counter", "I"),
+ TestMods.Use.type("java/util/List")
+ )), Map.of());
+
+ assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
+ }
+
+ @Test
+ void reportsMissingGameClassesAndMembers() throws Exception
+ {
+ ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
+ TestMods.Use.staticCall(ModVerifierTest.CORE, "gone", "()V"),
+ TestMods.Use.field(ModVerifierTest.CORE, "missing", "I"),
+ TestMods.Use.type("zombie/core/Removed")
+ )), Map.of());
+
+ assertEquals(
+ List.of("'linked': uses 'zombie.core.Removed', 'zombie.core.Core.gone()V', 'zombie.core.Core.missing:I', which do not exist in Project Zomboid 42.21.0."),
+ this.problems(mod)
+ );
+ }
+
+ @Test
+ void requiresGameVersionsForGameClassesIncludingBundledLibraries() throws Exception
+ {
+ ModDiscovery.Candidate mod = this.mod("plain", "", Map.of("a/Use", TestMods.user("a/Use",
+ TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
+ TestMods.Use.type("com/example/Shared")
+ )), Map.of());
+
+ assertEquals(
+ List.of("'plain': uses classes of the Project Zomboid jar ('com.example.Shared', 'zombie.core.Core') but declares no 'game' versions in mod.toml."),
+ this.problems(mod)
+ );
+ }
+
+ @Test
+ void ownLibrariesAndAnnotationsDoNotCountAsGameUse() throws Exception
+ {
+ ModDiscovery.Candidate mod = this.mod("bundled", "", Map.of(
+ "a/Use", TestMods.user("a/Use", TestMods.Use.type("com/example/Shared")),
+ "a/Annotated", TestMods.type("a/Annotated", "java/lang/Object", "Lorg/jetbrains/annotations/Nullable;")
+ ), Map.of(
+ "com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null)
+ ));
+
+ assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
+ }
+
+ @Test
+ void reportsInternalClassesAndForbiddenPackages() throws Exception
+ {
+ ModDiscovery.Candidate mod = this.mod("sneaky", "game = [\"42\"]\n", Map.of(
+ "a/Use", TestMods.user("a/Use",
+ TestMods.Use.type("dev/overlord/zomboidforge/core/Forge"),
+ TestMods.Use.type("dev/overlord/zomboidforge/api/internal/ModBinding"),
+ TestMods.Use.type("dev/overlord/zomboidforge/api/Mod")
+ ),
+ ModVerifierTest.CORE, TestMods.type(ModVerifierTest.CORE, "java/lang/Object", null),
+ "dev/overlord/zomboidforge/api/Fake", TestMods.type("dev/overlord/zomboidforge/api/Fake", "java/lang/Object", null)
+ ), Map.of());
+
+ assertEquals(
+ List.of(
+ "'sneaky': contains 'dev.overlord.zomboidforge.api.Fake', which is in a ZomboidForge package.",
+ "'sneaky': contains 'zombie.core.Core', which is a class of Project Zomboid.",
+ "'sneaky': uses 'dev.overlord.zomboidforge.api.internal.ModBinding', which is internal to ZomboidForge.",
+ "'sneaky': uses 'dev.overlord.zomboidforge.core.Forge', which is internal to ZomboidForge."
+ ),
+ this.problems(mod)
+ );
+ }
+
+ @Test
+ void dependenciesProvideTheirOwnClasses() throws Exception
+ {
+ // Accounts.ping() calls Recorder, which is in the fake game jar.
+ ModDiscovery.Candidate economy = this.mod("economy", "game = [\"42\"]\n", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of());
+ ModDiscovery.Candidate shop = this.mod("shop", "[dependencies]\neconomy = \"1.0\"\n", Map.of("a/Use", TestMods.user("a/Use",
+ TestMods.Use.staticCall("economy/Accounts", "ping", "()V")
+ )), Map.of());
+
+ assertDoesNotThrow(() -> ModVerifier.verify(List.of(economy, shop), this.game, ModVerifierTest.GAME));
+ }
+}
diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/TestMods.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/TestMods.java
index 41c1ec0..46c7663 100644
--- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/TestMods.java
+++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/TestMods.java
@@ -1,17 +1,18 @@
package dev.overlord.zomboidforge.core.mods;
+import testmods.Recorder;
+
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Type;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -20,11 +21,21 @@ import java.util.jar.JarOutputStream;
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.ATHROW;
+import static org.objectweb.asm.Opcodes.CHECKCAST;
+import static org.objectweb.asm.Opcodes.DCONST_0;
import static org.objectweb.asm.Opcodes.DUP;
+import static org.objectweb.asm.Opcodes.FCONST_0;
+import static org.objectweb.asm.Opcodes.GETFIELD;
+import static org.objectweb.asm.Opcodes.GETSTATIC;
+import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
+import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
+import static org.objectweb.asm.Opcodes.IRETURN;
+import static org.objectweb.asm.Opcodes.LCONST_0;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
@@ -33,20 +44,119 @@ import static org.objectweb.asm.Opcodes.V25;
public final class TestMods
{
private static final String MOD = "dev/overlord/zomboidforge/api/Mod";
- private static final String RECORDER = Type.getInternalName(TestMods.Recorder.class);
+ private static final String RECORDER = Type.getInternalName(Recorder.class);
- /** Events recorded by generated classes, e.g. {@code "shop:onLoad"}. */
- public static final class Recorder
+ /**
+ * One instruction of {@link #user}: {@code NEW}/{@code CHECKCAST} use only {@code owner};
+ * {@code GETSTATIC}/{@code GETFIELD} and the {@code INVOKE...} opcodes use all parts.
+ */
+ public record Use(int opcode, String owner, String name, String desc)
{
- public static final List EVENTS = Collections.synchronizedList(new ArrayList<>());
-
- private Recorder() {}
-
- public static void record(String event) { Recorder.EVENTS.add(event); }
+ public static Use type(String owner) { return new Use(CHECKCAST, owner, "", ""); }
+ public static Use field(String owner, String name, String desc) { return new Use(GETSTATIC, owner, name, desc); }
+ public static Use staticCall(String owner, String name, String desc) { return new Use(INVOKESTATIC, owner, name, desc); }
+ public static Use virtualCall(String owner, String name, String desc) { return new Use(INVOKEVIRTUAL, owner, name, desc); }
}
private TestMods() {}
+ /** A public class extending {@code superName}, optionally carrying a class annotation (not loaded at runtime). */
+ public static byte[] type(String name, String superName, @Nullable String annotationDescriptor, String... methods)
+ {
+ ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+ writer.visit(V25, ACC_PUBLIC, name, null, superName, null);
+
+ if (annotationDescriptor != null) writer.visitAnnotation(annotationDescriptor, false).visitEnd();
+
+ MethodVisitor init = writer.visitMethod(ACC_PUBLIC, "", "()V", null, null);
+ init.visitVarInsn(ALOAD, 0);
+ init.visitMethodInsn(INVOKESPECIAL, superName, "", "()V", false);
+ init.visitInsn(RETURN);
+ init.visitMaxs(0, 0);
+
+ // "name:desc" declares a public static method returning a default value; "name" with a field descriptor declares a field.
+ for (String member : methods)
+ {
+ String[] parts = member.split(":");
+
+ if (parts[1].startsWith("(")) {
+ MethodVisitor method = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, parts[0], parts[1], null, null);
+ Type returnType = Type.getReturnType(parts[1]);
+
+ switch (returnType.getSort())
+ {
+ case Type.VOID -> {}
+ case Type.LONG -> method.visitInsn(LCONST_0);
+ case Type.FLOAT -> method.visitInsn(FCONST_0);
+ case Type.DOUBLE -> method.visitInsn(DCONST_0);
+ case Type.OBJECT, Type.ARRAY -> method.visitInsn(ACONST_NULL);
+ default -> method.visitInsn(ICONST_0);
+ }
+
+ method.visitInsn(returnType.getOpcode(IRETURN));
+ method.visitMaxs(0, 0);
+ }
+ else writer.visitField(ACC_PUBLIC | ACC_STATIC, parts[0], parts[1], null, null).visitEnd();
+ }
+
+ writer.visitEnd();
+ return writer.toByteArray();
+ }
+
+ /** A class whose static {@code run()} performs {@code uses}; meant to be scanned, not run. */
+ public static byte[] user(String name, Use... uses)
+ {
+ ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
+ writer.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
+
+ MethodVisitor run = writer.visitMethod(ACC_PUBLIC | ACC_STATIC, "run", "()V", null, null);
+
+ for (Use use : uses)
+ {
+ switch (use.opcode())
+ {
+ case NEW, CHECKCAST -> { run.visitInsn(ACONST_NULL); run.visitTypeInsn(CHECKCAST, use.owner()); }
+ case GETSTATIC, GETFIELD -> run.visitFieldInsn(GETSTATIC, use.owner(), use.name(), use.desc());
+ default -> run.visitMethodInsn(use.opcode(), use.owner(), use.name(), use.desc(), false);
+ }
+ }
+
+ run.visitInsn(RETURN);
+ run.visitMaxs(0, 0);
+
+ writer.visitEnd();
+ return writer.toByteArray();
+ }
+
+ /**
+ * A stand-in for the Project Zomboid jar: {@code zombie/core/Base} with {@code inherited()V},
+ * {@code zombie/core/Core} extending it with {@code version()I} and the field
+ * {@code counter:I}, {@code com/example/Shared}, the annotation
+ * {@code org/jetbrains/annotations/Nullable}, and {@link Recorder}.
+ */
+ public static Path gameJar(Path jar) throws IOException
+ {
+ TestMods.jar(jar, null, Map.of(
+ "zombie/core/Base", TestMods.type("zombie/core/Base", "java/lang/Object", null, "inherited:()V"),
+ "zombie/core/Core", TestMods.type("zombie/core/Core", "zombie/core/Base", null, "version:()I", "counter:I"),
+ "com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null),
+ "org/jetbrains/annotations/Nullable", TestMods.type("org/jetbrains/annotations/Nullable", "java/lang/Object", null),
+ Type.getInternalName(Recorder.class), TestMods.classFile(Recorder.class)
+ ));
+
+ return jar;
+ }
+
+ /** The class file of a class on the test class path, e.g. to package it into a mod jar. */
+ public static byte[] classFile(Class> type) throws IOException
+ {
+ try (InputStream in = type.getResourceAsStream("/" + Type.getInternalName(type) + ".class"))
+ {
+ if (in == null) throw new IOException("No class file for '" + type.getName() + "'.");
+ return in.readAllBytes();
+ }
+ }
+
/** {@code mod.toml} with the required keys and {@code extra} lines appended. */
public static String toml(String id, String entrypoint, String extra)
{
@@ -59,14 +169,25 @@ public final class TestMods
/** {@code //.jar} with {@code mod.toml} (unless {@code null}) and {@code classes} (internal name to bytes). */
public static Path folder(Path mods, String id, @Nullable String toml, Map classes) throws IOException
+ {
+ return TestMods.folder(mods, id, toml, null, classes);
+ }
+
+ /** Like {@link #folder(Path, String, String, Map)}, with default settings in the jar (unless {@code null}). */
+ public static Path folder(Path mods, String id, @Nullable String toml, @Nullable String defaultConfig, Map classes) throws IOException
{
Path directory = Files.createDirectories(mods.resolve(id));
- TestMods.jar(directory.resolve(id + ".jar"), toml, classes);
+ TestMods.jar(directory.resolve(id + ".jar"), toml, defaultConfig, classes);
return directory;
}
public static void jar(Path jar, @Nullable String toml, Map classes) throws IOException
+ {
+ TestMods.jar(jar, toml, null, classes);
+ }
+
+ public static void jar(Path jar, @Nullable String toml, @Nullable String defaultConfig, Map classes) throws IOException
{
try (OutputStream file = Files.newOutputStream(jar); JarOutputStream out = new JarOutputStream(file))
{
@@ -76,6 +197,12 @@ public final class TestMods
out.closeEntry();
}
+ if (defaultConfig != null) {
+ out.putNextEntry(new JarEntry("META-INF/zomboidforge/config.toml"));
+ out.write(defaultConfig.getBytes(StandardCharsets.UTF_8));
+ out.closeEntry();
+ }
+
for (Map.Entry entry : new TreeMap<>(classes).entrySet()) {
out.putNextEntry(new JarEntry(entry.getKey() + ".class"));
out.write(entry.getValue());
diff --git a/core/src/test/java/testmods/ContextMod.java b/core/src/test/java/testmods/ContextMod.java
new file mode 100644
index 0000000..af991fd
--- /dev/null
+++ b/core/src/test/java/testmods/ContextMod.java
@@ -0,0 +1,22 @@
+package testmods;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+import dev.overlord.zomboidforge.api.Mod;
+
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Entry point that tests package into a mod jar: outside the ZomboidForge packages, so the mod
+ * class loader loads it from the jar. Records what its context returns in the constructor.
+ */
+public final class ContextMod extends Mod
+{
+ public record Settings(String greeting, long limit, Optional extra, Map prices) {}
+
+ public final String idInConstructor = this.id();
+ public final GameVersion gameInConstructor = this.gameVersion();
+ public final Path directoryInConstructor = this.directory();
+ public final Settings settings = this.config().bind(Settings.class);
+}
diff --git a/core/src/test/java/testmods/Recorder.java b/core/src/test/java/testmods/Recorder.java
new file mode 100644
index 0000000..75b4186
--- /dev/null
+++ b/core/src/test/java/testmods/Recorder.java
@@ -0,0 +1,18 @@
+package testmods;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Events recorded by generated mod classes, e.g. {@code "shop:onLoad"}. Tests put this class
+ * into their fake game jar, so mods that declare {@code game} versions can call it.
+ */
+public final class Recorder
+{
+ public static final List EVENTS = Collections.synchronizedList(new ArrayList<>());
+
+ private Recorder() {}
+
+ public static void record(String event) { Recorder.EVENTS.add(event); }
+}