Improve/add initial project structure for ZomboidForge with build system, runtime, and patching logic.

Added version support for building images.
This commit is contained in:
Overlord committed 2026-09-29 16:51:13 +02:00
1 parent bf9228d2be
commit 015e9bb2c8
32 files changed
+1268 -58

No files matched your search

@@ -0,0 +1,22 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.tree.ClassNode;
/** A build-time change to one class of the vanilla server jar. */
public interface ClassPatch {
/** Internal name of the class to patch, e.g. {@code zombie/network/GameServer}. */
String target();
/**
* Whether the patch applies to the given game version. Patches that differ
* between minor versions of the same Build provide one implementation per
* version range. Default: every version.
*/
default boolean appliesTo(GameVersion version) { return true; }
/**
* Modifies {@code node} in place. Throws if the class does not match what the
* patch expects (e.g. after a Project Zomboid update).
*/
void apply(ClassNode node);
}
@@ -0,0 +1,72 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Project Zomboid version, e.g. 42.21.0 (Core.getGameAndBuildVersion()). */
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
{
private static final Pattern FORMAT = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?");
private static final Comparator<GameVersion> ORDER = Comparator
.comparingInt(GameVersion::major)
.thenComparingInt(GameVersion::minor)
.thenComparingInt(GameVersion::build);
//
/** Parses "42.21.0", or "42.21" as 42.21.0. */
public static GameVersion parse(String text)
{
Matcher matcher = FORMAT.matcher(text.trim());
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: " + text);
int build = matcher.group(3) == null
? 0
: Integer.parseInt(matcher.group(3));
return new GameVersion(
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
build
);
}
/**
* Whether this version satisfies an expected version: "42.21" matches every
* 42.21.x build, "42.21.0" matches only 42.21.0.
*/
public boolean matches(String expected)
{
GameVersion other = parse(expected);
boolean buildGiven = expected.trim().chars().filter(c -> c == '.').count() == 2;
return
major == other.major &&
minor == other.minor &&
(!buildGiven || build == other.build);
}
//
public boolean isAtLeast(int major, int minor) {
return compareTo(new GameVersion(major, minor, 0)) >= 0;
}
public boolean isBefore(int major, int minor) {
return compareTo(new GameVersion(major, minor, 0)) < 0;
}
@Override
public int compareTo(@NotNull GameVersion other) {
return ORDER.compare(this, other);
}
@Override
public @NotNull String toString() {
return major + "." + minor + "." + build;
}
}
@@ -0,0 +1,94 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Contract;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
/**
* Reads the game version from the bytes of zombie/core/Core.class.
*
* <p>Core's static initializer contains {@code gameVersion = new GameVersion(major, minor, "")},
* and {@code buildVersion} is a compile-time constant; together they form
* Core.getGameAndBuildVersion().
*/
public final class GameVersionReader
{
public static final String CORE_CLASS = "zombie/core/Core";
private static final String GAME_VERSION_CLASS = "zombie/core/GameVersion";
private static final String GAME_VERSION_FIELD = "gameVersion";
private static final String BUILD_VERSION_FIELD = "buildVersion";
private GameVersionReader() {}
public static GameVersion read(byte[] coreClass)
{
ClassNode core = new ClassNode();
new ClassReader(coreClass).accept(core, 0);
MethodNode staticInitializer = core.methods.stream()
.filter(m -> m.name.equals("<clinit>"))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Core has no static initializer."));
int[] majorMinor = readGameVersionConstructorArguments(staticInitializer);
return new GameVersion(majorMinor[0], majorMinor[1], readBuildVersion(core));
}
/** Finds the two int constants passed to the GameVersion constructor stored in Core.gameVersion. */
private static int[] readGameVersionConstructorArguments(MethodNode staticInitializer)
{
List<Integer> intConstants = new ArrayList<>();
for (AbstractInsnNode insn : staticInitializer.instructions)
{
if (insn.getOpcode() == Opcodes.NEW) intConstants.clear();
Integer constant = intConstant(insn);
if (constant != null) intConstants.add(constant);
if
(
insn instanceof MethodInsnNode call
&& call.owner.equals(GAME_VERSION_CLASS)
&& call.name.equals("<init>")
&& isGameVersionStore(call.getNext())
&& intConstants.size() == 2
)
{ return new int[]{intConstants.get(0), intConstants.get(1)}; }
}
throw new IllegalStateException("Core.gameVersion initialization not found.");
}
private static boolean isGameVersionStore(AbstractInsnNode insn) {
return insn instanceof FieldInsnNode field
&& field.getOpcode() == Opcodes.PUTSTATIC
&& field.name.equals(GAME_VERSION_FIELD);
}
private static int readBuildVersion(ClassNode core) {
return core.fields.stream()
.filter(f -> f.name.equals(BUILD_VERSION_FIELD) && f.value instanceof Integer)
.map(f -> (Integer) f.value)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Core.buildVersion constant not found."));
}
private static Integer intConstant(AbstractInsnNode insn)
{
int opcode = insn.getOpcode();
if (opcode >= Opcodes.ICONST_M1 && opcode <= Opcodes.ICONST_5) return opcode - Opcodes.ICONST_0;
if ((opcode == Opcodes.BIPUSH || opcode == Opcodes.SIPUSH) && insn instanceof IntInsnNode push) return push.operand;
return null;
}
}
@@ -0,0 +1,75 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* {@link ClassWriter} that computes frames from class bytes instead of loading
* classes. The game classes are not on the patcher's class path, and loading
* them would run their static initializers.
*/
final class HierarchyClassWriter extends ClassWriter {
private static final String OBJECT = "java/lang/Object";
private record Header(String superName, boolean isInterface) {}
private final Function<String, byte[]> jarClasses;
private final Map<String, Header> headers = new HashMap<>();
/** @param jarClasses bytes of a class in the jar being patched, or {@code null} */
HierarchyClassWriter(Function<String, byte[]> jarClasses) {
super(COMPUTE_FRAMES);
this.jarClasses = jarClasses;
}
@Override
protected String getCommonSuperClass(String type1, String type2)
{
if (header(type1).isInterface() || header(type2).isInterface()) return OBJECT;
Set<String> supers1 = new HashSet<>();
for (String c = type1; c != null; c = header(c).superName()) {
supers1.add(c);
}
for (String c = type2; c != null; c = header(c).superName()) {
if (supers1.contains(c)) {
return c;
}
}
return OBJECT;
}
private Header header(String internalName) {
return headers.computeIfAbsent(internalName, name -> {
ClassReader reader = new ClassReader(bytes(name));
return new Header(reader.getSuperName(), (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0);
});
}
private byte[] bytes(String internalName)
{
byte[] bytes = jarClasses.apply(internalName);
if (bytes != null) return bytes;
// JDK (or other non-jar) class.
try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class"))
{
if (in == null) throw new IllegalStateException("Class not found while computing frames: '" + internalName + "'.");
return in.readAllBytes();
}
catch (IOException e) { throw new UncheckedIOException(e); }
}
}
@@ -0,0 +1,194 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Copies a jar, applying {@link ClassPatch}es to their target classes. Every
* other entry is copied through unchanged.
*/
public final class JarPatcher
{
private static final String VERSIONED_PREFIX = "META-INF/versions/";
private final Map<String, List<ClassPatch>> patchesByEntry = new LinkedHashMap<>();
public JarPatcher(Collection<? extends ClassPatch> patches) {
for (ClassPatch patch : patches) {
patchesByEntry.computeIfAbsent(patch.target() + ".class", k -> new ArrayList<>()).add(patch);
}
}
//
/**
* Usage: {@code JarPatcher <vanilla.jar> <patched.jar> <expected-version>}. Loads the
* single {@link PatchSet} on the class path and applies every patch that applies to
* the jar's game version.
*/
static void main(String[] args) throws IOException
{
if (args.length != 3) {
System.err.println("Usage: JarPatcher <vanilla.jar> <patched.jar> <expected-version>");
System.exit(2);
}
Path vanillaJar = Path.of(args[0]);
Path patchedJar = Path.of(args[1]);
String expectedVersion = args[2];
GameVersion version = readGameVersion(vanillaJar);
if (!version.matches(expectedVersion)) {
throw new IllegalStateException(
"Server jar is Project Zomboid " + version +
", but the build targets " + expectedVersion +
" (gradle property pz.version)"
);
}
PatchSet patchSet = loadPatchSet();
List<ClassPatch> applicable = applicablePatches(patchSet, version);
int patchedClasses = new JarPatcher(applicable).patch(vanillaJar, patchedJar);
System.out.println(
"Project Zomboid " + version + ": patched " + patchedClasses + " class(es) with "
+ applicable.size() + " of " + patchSet.patches().size() + " patch(es) -> " + patchedJar
);
}
/** Reads the game version from zombie/core/Core.class in the jar. */
public static GameVersion readGameVersion(Path jar) throws IOException
{
try (ZipFile zip = new ZipFile(jar.toFile()))
{
byte[] core = read(zip, GameVersionReader.CORE_CLASS + ".class");
if (core == null) throw new IllegalStateException("'" + jar + "' contains no " + GameVersionReader.CORE_CLASS + ".class");
return GameVersionReader.read(core);
}
}
/** Patches of {@code patchSet} that apply to {@code version}, in application order. */
public static List<ClassPatch> applicablePatches(PatchSet patchSet, GameVersion version)
{
if (patchSet.build() != version.major()) {
throw new IllegalStateException(
"Patch set is for Build " + patchSet.build()
+ ", but the server jar is Project Zomboid " + version
);
}
return patchSet.patches().stream()
.filter(patch -> patch.appliesTo(version))
.toList();
}
private static PatchSet loadPatchSet()
{
List<PatchSet> patchSets = ServiceLoader.load(PatchSet.class)
.stream()
.map(ServiceLoader.Provider::get)
.toList();
if (patchSets.size() != 1) throw new IllegalStateException("Expected exactly one PatchSet on the class path, found: " + patchSets.size());
return patchSets.getFirst();
}
/** @return the number of classes that were patched */
public int patch(Path in, Path out) throws IOException
{
Path parent = out.toAbsolutePath().getParent();
if (parent != null) Files.createDirectories(parent);
try (
ZipFile jar = new ZipFile(in.toFile());
ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(out))
) {
checkTargets(jar);
int patched = 0;
for (Enumeration<? extends ZipEntry> entries = jar.entries(); entries.hasMoreElements();)
{
ZipEntry entry = entries.nextElement();
List<ClassPatch> patches = patchesByEntry.get(entry.getName());
byte[] bytes = jar.getInputStream(entry).readAllBytes();
if (patches != null) {
bytes = transform(jar, bytes, patches);
patched++;
}
ZipEntry copy = new ZipEntry(entry.getName());
copy.setTime(entry.getTime());
zip.putNextEntry(copy);
zip.write(bytes);
zip.closeEntry();
}
return patched;
}
}
/** Fails if a target is missing or shadowed by an unpatched multi-release override. */
private void checkTargets(ZipFile jar)
{
List<String> problems = new ArrayList<>();
for (String name : patchesByEntry.keySet()) {
if (jar.getEntry(name) == null) {
problems.add("'" + name + "' not found in jar.");
}
}
jar.stream()
.map(ZipEntry::getName)
.filter(n -> n.startsWith(VERSIONED_PREFIX))
.filter(n -> patchesByEntry.containsKey(n.substring(n.indexOf('/', VERSIONED_PREFIX.length()) + 1)))
.forEach(n -> problems.add("'" + n + "' overrides a patched class."));
if (!problems.isEmpty()) {
throw new IllegalStateException("Cannot patch '" + jar.getName() + "':\n " + String.join("\n ", problems));
}
}
private static byte[] transform(ZipFile jar, byte[] bytes, List<ClassPatch> patches)
{
ClassNode node = new ClassNode();
new ClassReader(bytes).accept(node, 0);
for (ClassPatch patch : patches) {
patch.apply(node);
}
HierarchyClassWriter writer = new HierarchyClassWriter(name -> read(jar, name + ".class"));
node.accept(writer);
return writer.toByteArray();
}
private static byte[] read(ZipFile jar, String entryName)
{
ZipEntry entry = jar.getEntry(entryName);
if (entry == null) return null;
try { return jar.getInputStream(entry).readAllBytes(); }
catch (IOException e) { throw new UncheckedIOException(e); }
}
}
@@ -0,0 +1,15 @@
package dev.overlord.zomboidforge.patcher;
import java.util.List;
/**
* All build-time patches of one Project Zomboid Build, provided by a compat module
* (compat/b&lt;major&gt;/patches) through {@link java.util.ServiceLoader}.
*/
public interface PatchSet {
/** Project Zomboid major version (Build) the patches are written for, e.g. 42. */
int build();
/** Patches in application order. */
List<ClassPatch> patches();
}