diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java
index 60cf2ba..5b98fab 100644
--- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java
+++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java
@@ -17,6 +17,7 @@ public final class B42PatchSet implements PatchSet
new ServerStartedPatch(),
new ServerTickPatch(),
new ServerStoppingPatch(),
+ new ZipBackupSinglePassPerformancePatch(),
new BackupStoragePatch(),
new CommandLookupPatch(),
new CommandListPatch(),
diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatch.java
new file mode 100644
index 0000000..2a69097
--- /dev/null
+++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatch.java
@@ -0,0 +1,60 @@
+package dev.overlord.zomboidforge.compat.b42.perf;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+import dev.overlord.zomboidforge.patcher.Anchor;
+import dev.overlord.zomboidforge.patcher.Hook;
+import dev.overlord.zomboidforge.patcher.MethodBody;
+import dev.overlord.zomboidforge.patcher.patches.PerformancePatch;
+
+import org.objectweb.asm.tree.ClassNode;
+import org.objectweb.asm.tree.MethodNode;
+
+/**
+ * Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)} with a call to
+ * {@code BackupHooks.makeBackupFile}, which writes the same zip in one pass:
+ *
+ *
{@code
+ * private static void makeBackupFile(String serverName, BackupTypes type)
+ * {
+ * BackupHooks.makeBackupFile(serverName, type);
+ * }
+ * }
+ *
+ * Vanilla's {@code ParallelScatterZipCreator} copies every file into a temporary file per thread
+ * and then into the zip: about three times the size of the save written per backup. For an
+ * explored world of 880 MiB in 365,538 files, the startup backup takes 15.2 to 16.8 s and writes
+ * 2.9 GB; in one pass 7.5 s and 1.0 GB, with the same entries. The save folder is read under
+ * {@code IsoChunk.WriteLock}, as vanilla; chunk saves wait for it half as long.
+ *
+ * Registered before {@code BackupStoragePatch}, which renames this method and wraps it: the
+ * anchor requires vanilla's body, and the storage hooks stay around the whole backup.
+ */
+public final class ZipBackupSinglePassPerformancePatch extends PerformancePatch
+{
+ private static final Anchor.Call ANCHOR = new Anchor.Call(
+ new Anchor.Method("makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"),
+ "org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator", "writeTo", "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveOutputStream;)V"
+ );
+
+ // BackupTypes is private: the hook takes it as Object.
+ private static final Hook HOOK = new Hook(
+ "dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", "makeBackupFile", "(Ljava/lang/String;Ljava/lang/Object;)V"
+ );
+
+ public ZipBackupSinglePassPerformancePatch() {
+ super("zombie/core/backup/ZipBackup", ZipBackupSinglePassPerformancePatch.ANCHOR, ZipBackupSinglePassPerformancePatch.HOOK);
+ }
+
+ //
+
+ @Override
+ public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
+
+ @Override
+ public void apply(ClassNode node)
+ {
+ MethodNode method = ZipBackupSinglePassPerformancePatch.ANCHOR.in().resolve(node);
+
+ MethodBody.delegate(node, method, ZipBackupSinglePassPerformancePatch.HOOK);
+ }
+}
diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatchTest.java
new file mode 100644
index 0000000..af6f44d
--- /dev/null
+++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZipBackupSinglePassPerformancePatchTest.java
@@ -0,0 +1,157 @@
+package dev.overlord.zomboidforge.compat.b42.perf;
+
+import dev.overlord.zomboidforge.api.GameVersion;
+import dev.overlord.zomboidforge.compat.b42.B42PatchSet;
+import dev.overlord.zomboidforge.compat.b42.patches.BackupStoragePatch;
+import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
+import dev.overlord.zomboidforge.patcher.ClassPatch;
+
+import org.junit.jupiter.api.Test;
+import org.objectweb.asm.MethodVisitor;
+import org.objectweb.asm.tree.AbstractInsnNode;
+import org.objectweb.asm.tree.ClassNode;
+import org.objectweb.asm.tree.MethodInsnNode;
+import org.objectweb.asm.tree.MethodNode;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
+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.CHECKCAST;
+import static org.objectweb.asm.Opcodes.INVOKESTATIC;
+import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
+import static org.objectweb.asm.Opcodes.RETURN;
+import static org.objectweb.asm.Opcodes.V25;
+
+class ZipBackupSinglePassPerformancePatchTest
+{
+ private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
+ private static final String DESC = "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V";
+ private static final String SCATTER = "org/apache/commons/compress/archivers/zip/ParallelScatterZipCreator";
+ private static final String STREAM = "org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream";
+
+ /** {@code ZipBackup} with a reduced {@code makeBackupFile}: {@code ((ParallelScatterZipCreator) null).writeTo(null);} */
+ private static ClassNode zipBackup()
+ {
+ ClassNode node = new ClassNode();
+ node.visit(V25, ACC_PUBLIC, ZipBackupSinglePassPerformancePatchTest.ZIP_BACKUP, null, "java/lang/Object", null);
+
+ MethodVisitor make = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", ZipBackupSinglePassPerformancePatchTest.DESC, null, null);
+ make.visitInsn(ACONST_NULL);
+ make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.SCATTER);
+ make.visitInsn(ACONST_NULL);
+ make.visitTypeInsn(CHECKCAST, ZipBackupSinglePassPerformancePatchTest.STREAM);
+ make.visitMethodInsn(INVOKEVIRTUAL, ZipBackupSinglePassPerformancePatchTest.SCATTER, "writeTo", "(L" + ZipBackupSinglePassPerformancePatchTest.STREAM + ";)V", false);
+ make.visitInsn(RETURN);
+ make.visitMaxs(0, 0);
+
+ return node;
+ }
+
+ private static MethodNode method(ClassNode node, String name)
+ {
+ return node.methods.stream().filter(method -> method.name.equals(name)).findFirst().orElseThrow();
+ }
+
+ private static List calls(MethodNode method)
+ {
+ List calls = new ArrayList<>();
+
+ for (AbstractInsnNode instruction : method.instructions) {
+ if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
+ }
+
+ return calls;
+ }
+
+ @Test
+ void anchorMatchesTheTarget()
+ {
+ new ZipBackupSinglePassPerformancePatch().anchor().verify(ZipBackupSinglePassPerformancePatchTest.zipBackup());
+ }
+
+ @Test
+ void replacesTheBodyWithTheHookCall()
+ {
+ ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
+ new ZipBackupSinglePassPerformancePatch().apply(node);
+
+ List instructions = new ArrayList<>();
+ for (AbstractInsnNode instruction : ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile").instructions) {
+ if (instruction.getOpcode() != -1) instructions.add(instruction);
+ }
+ assertEquals(List.of(ALOAD, ALOAD, INVOKESTATIC, RETURN), instructions.stream().map(AbstractInsnNode::getOpcode).toList());
+
+ MethodInsnNode call = (MethodInsnNode) instructions.get(2);
+ assertEquals("dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks", call.owner);
+ assertEquals("makeBackupFile", call.name);
+ assertEquals("(Ljava/lang/String;Ljava/lang/Object;)V", call.desc);
+ }
+
+ @Test
+ void patchedClassIsValid() throws ClassNotFoundException
+ {
+ ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
+ new ZipBackupSinglePassPerformancePatch().apply(node);
+
+ // Initializing links the class, which runs the bytecode verifier on the new body.
+ ClassDefiner definer = new ClassDefiner();
+ definer.define(node);
+ Class.forName(node.name.replace('/', '.'), true, definer);
+ }
+
+ /** As in {@link B42PatchSet}: this patch first, then the storage wrapper around the hook call. */
+ @Test
+ void storagePatchWrapsTheReplacedBody()
+ {
+ ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
+ BackupStoragePatch storage = new BackupStoragePatch();
+
+ new ZipBackupSinglePassPerformancePatch().apply(node);
+ storage.anchor().verify(node);
+ storage.apply(node);
+
+ assertEquals(List.of("StorageHooks.backupRunning", "ZipBackup.zomboidForge$makeBackupFile", "StorageHooks.backupRunning", "StorageHooks.backupRunning"),
+ ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "makeBackupFile")));
+ assertEquals(List.of("BackupHooks.makeBackupFile"),
+ ZipBackupSinglePassPerformancePatchTest.calls(ZipBackupSinglePassPerformancePatchTest.method(node, "zomboidForge$makeBackupFile")));
+ }
+
+ @Test
+ void registeredBeforeTheStoragePatch()
+ {
+ List names = new B42PatchSet().patches().stream().map(ClassPatch::getClass).map(Class::getSimpleName).toList();
+
+ assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") >= 0);
+ assertTrue(names.indexOf("ZipBackupSinglePassPerformancePatch") < names.indexOf("BackupStoragePatch"));
+ }
+
+ /** After the storage patch, {@code makeBackupFile} is the wrapper, which the hook must not replace. */
+ @Test
+ void anchorFailsOnTheStorageWrapper()
+ {
+ ClassNode node = ZipBackupSinglePassPerformancePatchTest.zipBackup();
+ new BackupStoragePatch().apply(node);
+
+ assertThrows(IllegalStateException.class, () -> new ZipBackupSinglePassPerformancePatch().anchor().verify(node));
+ }
+
+ @Test
+ void appliesOnlyToVerifiedVersions()
+ {
+ ZipBackupSinglePassPerformancePatch patch = new ZipBackupSinglePassPerformancePatch();
+
+ assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
+ assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
+ assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
+ assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
+ }
+}
diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks.java
new file mode 100644
index 0000000..f72b91e
--- /dev/null
+++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooks.java
@@ -0,0 +1,114 @@
+package dev.overlord.zomboidforge.compat.b42.hooks;
+
+import dev.overlord.zomboidforge.compat.b42.util.ParallelZip;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import zombie.ZomboidFileSystem;
+import zombie.core.backup.ZipBackup;
+import zombie.debug.DebugLog;
+import zombie.debug.DebugType;
+import zombie.debug.LogSeverity;
+import zombie.iso.IsoChunk;
+import zombie.network.CoopSlave;
+
+/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
+@SuppressWarnings("unused")
+public final class BackupHooks
+{
+ /** {@code ZipBackup.rotateBackupFile(BackupTypes)}, private, taking the enum as {@code Object}. */
+ private static final MethodHandle ROTATE;
+ /** {@code ZipBackup.getBackupReadme(String)}, private. */
+ private static final MethodHandle README;
+
+ /** The files of the cache folder that vanilla adds, each when it exists. */
+ private static final String[] FILES = {
+ "options.ini", "popman-options.ini", "latestSave.ini", "debug-options.ini", "sounds.ini", "gamepadBinding.config"
+ };
+
+ /** The folders of the cache folder whose top-level files vanilla adds. */
+ private static final String[] TOP_LEVEL_FOLDERS = { "mods", "Lua", "db", "Server" };
+
+ static
+ {
+ try
+ {
+ MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(ZipBackup.class, MethodHandles.lookup());
+ Class> types = Class.forName("zombie.core.backup.ZipBackup$BackupTypes");
+
+ ROTATE = lookup.findStatic(ZipBackup.class, "rotateBackupFile", MethodType.methodType(void.class, types))
+ .asType(MethodType.methodType(void.class, Object.class));
+ README = lookup.findStatic(ZipBackup.class, "getBackupReadme", MethodType.methodType(String.class, String.class));
+ }
+ catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
+ }
+
+ private BackupHooks() {}
+
+ /**
+ * Replaces the body of {@code ZipBackup.makeBackupFile(String, BackupTypes)}; {@code type} is
+ * the {@code BackupTypes} constant, a private enum. Writes the same entries into
+ * {@code backups//backup_1.zip} as vanilla, after the same rotation: {@code readme.txt},
+ * the files of {@link #FILES}, the top-level files of {@link #TOP_LEVEL_FOLDERS} (vanilla's
+ * {@code zipDir(String, String)} skips every subfolder), and the save folder without the
+ * folders named {@code blam}, read under {@code IsoChunk.WriteLock}. {@link ParallelZip}
+ * writes them in one pass instead of vanilla's three. As vanilla, the backup logs its
+ * failures and does not throw.
+ */
+ public static void makeBackupFile(String serverName, Object type)
+ {
+ String backupDir = ZomboidFileSystem.instance.getCacheDir() + File.separator + "backups" + File.separator + ((Enum>) type).name();
+ long startTime = System.currentTimeMillis();
+
+ DebugType.General.println("Start making backup");
+ DebugType.DetailedInfo.println("backup dir: " + backupDir);
+ CoopSlave.status("UI_ServerStatus_CreateBackup");
+
+ try
+ {
+ //noinspection ResultOfMethodCallIgnored
+ new File(backupDir).mkdirs();
+ BackupHooks.ROTATE.invokeExact(type);
+
+ Path zipFile = Paths.get(backupDir + File.separator + "backup_1.zip");
+ try { Files.deleteIfExists(zipFile); }
+ catch (IOException e) { DebugType.General.printException(e, LogSeverity.Error); }
+
+ String readme = (String) BackupHooks.README.invokeExact(serverName);
+ String saveDir = "Saves" + File.separator + "Multiplayer" + File.separator + serverName;
+ int threads = Runtime.getRuntime().availableProcessors();
+
+ try (ParallelZip zip = new ParallelZip(zipFile, readme, threads, e -> DebugType.General.printException(e, LogSeverity.Error)))
+ {
+ zip.addText("readme.txt", readme);
+
+ for (String name : BackupHooks.FILES)
+ {
+ Path file = Paths.get(ZomboidFileSystem.instance.getCacheDir() + File.separator + name);
+ if (Files.exists(file)) zip.addFile(name, file);
+ }
+
+ for (String folder : BackupHooks.TOP_LEVEL_FOLDERS) zip.addFolder(folder, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(folder)), subfolder -> false);
+
+ synchronized (IsoChunk.WriteLock)
+ {
+ zip.addFolder(saveDir, Paths.get(ZomboidFileSystem.instance.getCacheDirSub(saveDir)), subfolder -> !subfolder.endsWith("blam"));
+ }
+
+ zip.finish();
+ }
+ }
+ // As vanilla's catch of Exception: errors pass; invokeExact declares Throwable.
+ catch (Error e) { throw e; }
+ catch (Throwable t) { DebugType.General.printException(t, LogSeverity.Error); }
+
+ DebugLog.log("Backup made in " + (System.currentTimeMillis() - startTime) + " ms");
+ }
+}
diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZip.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZip.java
new file mode 100644
index 0000000..caf8e85
--- /dev/null
+++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZip.java
@@ -0,0 +1,367 @@
+package dev.overlord.zomboidforge.compat.b42.util;
+
+import org.apache.commons.compress.archivers.zip.Zip64Mode;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
+import org.jspecify.annotations.Nullable;
+
+import java.io.ByteArrayInputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.NonReadableChannelException;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.DirectoryIteratorException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
+import java.util.zip.CRC32;
+
+/**
+ * A zip file of uncompressed (STORED) entries, Zip64 as needed, as {@code ZipBackup} writes,
+ * written in one pass from files that a thread pool reads in parallel.
+ *
+ * {@code ZipBackup.makeBackupFile} hands every file to {@code ParallelScatterZipCreator}, whose
+ * threads copy the files into one temporary file per thread, which it then copies into the zip:
+ * every byte is written three times. Here reader threads list the folders and read each file
+ * with its CRC into memory, and the thread that adds a folder writes the files as entries with
+ * size and CRC known: each byte is written once, each header once. Files of more than
+ * {@value #LARGE} bytes are not held in memory: the writing thread copies them and patches size
+ * and CRC into the entry's header afterwards. Read files waiting to be written hold at most
+ * {@value #BUDGET} bytes.
+ *
+ *
Entries appear in the order their files were read, which varies between runs, as with
+ * {@code ParallelScatterZipCreator}. The file is a valid zip only after {@link #finish()}.
+ */
+public final class ParallelZip implements Closeable
+{
+ /** Files larger than this are copied by the writing thread instead of read into memory. */
+ private static final int LARGE = 4 << 20;
+ /** Bytes of read files that wait for the writing thread, at most. */
+ private static final int BUDGET = 64 << 20;
+ /** Write buffer of the zip file. */
+ private static final int BUFFER = 1 << 20;
+
+ private static final AtomicInteger THREADS = new AtomicInteger();
+
+ /** A file read with its CRC; {@code permits} of the budget are released once it is written. */
+ private record Loaded(String name, byte[] data, long crc, int permits) implements Item {}
+
+ /** A file the writing thread copies itself; {@code size} as listed. */
+ private record Large(String name, Path file, long size) implements Item {}
+
+ /** An unexpected failure of a reader thread. */
+ private record Failed(Throwable cause) implements Item {}
+
+ /** Every folder of the current {@link #addFolder} is read. */
+ private record Done() implements Item {}
+
+ private sealed interface Item permits Loaded, Large, Failed, Done {}
+
+ private final BufferedChannel channel;
+ private final ZipArchiveOutputStream zip;
+ private final ExecutorService readers;
+ private final Consumer failures;
+ private final Semaphore budget = new Semaphore(ParallelZip.BUDGET);
+ private boolean finished;
+
+ /**
+ * Creates or truncates {@code file}, with {@code threads} reader threads. Files and folders
+ * that cannot be read are passed to {@code failures}, from any of these threads, and left out.
+ */
+ public ParallelZip(Path file, String comment, int threads, Consumer failures) throws IOException
+ {
+ this.channel = new BufferedChannel(FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
+ this.zip = new ZipArchiveOutputStream(this.channel);
+ this.failures = failures;
+ this.readers = Executors.newFixedThreadPool(threads, task -> {
+ Thread thread = new Thread(task, "zf-backup-reader-" + ParallelZip.THREADS.incrementAndGet());
+ thread.setDaemon(true);
+ return thread;
+ });
+
+ this.zip.setUseZip64(Zip64Mode.AsNeeded);
+ this.zip.setMethod(ZipArchiveEntry.STORED);
+ this.zip.setComment(comment);
+ }
+
+ /** Adds the entry {@code name} with the UTF-8 bytes of {@code text}. */
+ public void addText(String name, String text) throws IOException
+ {
+ byte[] data = text.getBytes(StandardCharsets.UTF_8);
+ CRC32 crc = new CRC32();
+ crc.update(data);
+
+ this.write(new Loaded(name, data, crc.getValue(), 0));
+ }
+
+ /** Adds the entry {@code name} with the content of {@code file}, on the calling thread. */
+ public void addFile(String name, Path file) throws IOException
+ {
+ try
+ {
+ Item item = this.read(name, file, Files.readAttributes(file, BasicFileAttributes.class));
+ if (item != null) this.write(item);
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while adding '" + file + "'.");
+ }
+ catch (IOException e) { this.failures.accept(e); }
+ }
+
+ /**
+ * Adds every file in {@code folder} as the entry {@code prefix/}, and
+ * the files of each subfolder for which {@code descend} holds, recursively; as
+ * {@code ZipBackup.zipDir}, links are not followed into folders, and a link to a file is
+ * added with the file's content. Returns once every entry is written; nothing when
+ * {@code folder} is no folder.
+ */
+ @SuppressWarnings("DeconstructionCanBeUsed")
+ public void addFolder(String prefix, Path folder, Predicate descend) throws IOException
+ {
+ if (!Files.isDirectory(folder)) return;
+
+ BlockingQueue- ready = new LinkedBlockingQueue<>();
+ AtomicInteger pending = new AtomicInteger(1);
+
+ this.readers.execute(() -> this.readFolder(prefix, folder, folder, descend, ready, pending));
+
+ try
+ {
+ while (true)
+ {
+ Item item = ready.take();
+
+ if (item instanceof Done) return;
+ if (item instanceof Failed failed) throw new IOException("Reading '" + folder + "' failed.", failed.cause());
+
+ this.write(item);
+ }
+ }
+ catch (InterruptedException e)
+ {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while adding '" + folder + "'.");
+ }
+ }
+
+ /** Writes the central directory: the file is a complete zip. */
+ public void finish() throws IOException
+ {
+ this.zip.finish();
+ this.finished = true;
+ }
+
+ /**
+ * Stops the reader threads and closes the file; without {@link #finish()} the file has no
+ * central directory, so no tool takes it for a complete backup.
+ */
+ @Override
+ public void close() throws IOException
+ {
+ this.readers.shutdownNow();
+
+ if (this.finished) this.zip.close();
+ else this.channel.close();
+ }
+
+ /** On a reader thread: lists {@code folder}, queues its files, and starts a task per subfolder to descend into. */
+ private void readFolder(String prefix, Path root, Path folder, Predicate descend, BlockingQueue
- ready, AtomicInteger pending)
+ {
+ try (DirectoryStream entries = Files.newDirectoryStream(folder))
+ {
+ for (Path entry : entries)
+ {
+ try
+ {
+ BasicFileAttributes attributes = Files.readAttributes(entry, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+
+ if (attributes.isDirectory())
+ {
+ if (!descend.test(entry)) continue;
+
+ pending.incrementAndGet();
+ this.readers.execute(() -> this.readFolder(prefix, root, entry, descend, ready, pending));
+ continue;
+ }
+
+ String name = prefix + File.separator + root.relativize(entry).toString().replace("/", File.separator);
+ Item item = this.read(name, entry, attributes);
+ if (item != null) ready.add(item);
+ }
+ catch (IOException e) { this.failures.accept(e); }
+ }
+ }
+ catch (IOException e) { this.failures.accept(e); }
+ catch (DirectoryIteratorException e) { this.failures.accept(e.getCause()); }
+ // Interrupted by close(), or an unexpected failure: addFolder throws.
+ catch (Throwable t) { ready.add(new Failed(t)); }
+ finally { if (pending.decrementAndGet() == 0) ready.add(new Done()); }
+ }
+
+ /**
+ * {@code file} as an item to write: read with its CRC, or, when large, to be copied by the
+ * writing thread. {@code null} for files that cannot be read (sockets and the like).
+ */
+ private @Nullable Item read(String name, Path file, BasicFileAttributes attributes) throws IOException, InterruptedException
+ {
+ if (attributes.isOther()) return null;
+
+ // A link: the size of the file it points to.
+ long size = attributes.isSymbolicLink() ? Files.size(file) : attributes.size();
+ if (size > ParallelZip.LARGE) return new Large(name, file, size);
+
+ int permits = (int) size;
+ this.budget.acquire(permits);
+
+ try
+ {
+ byte[] data = Files.readAllBytes(file);
+ CRC32 crc = new CRC32();
+ crc.update(data);
+
+ return new Loaded(name, data, crc.getValue(), permits);
+ }
+ catch (IOException | RuntimeException | Error e)
+ {
+ this.budget.release(permits);
+ throw e;
+ }
+ }
+
+ private void write(Item item) throws IOException
+ {
+ switch (item)
+ {
+ case Loaded loaded ->
+ {
+ ZipArchiveEntry entry = new ZipArchiveEntry(loaded.name());
+ entry.setMethod(ZipArchiveEntry.STORED);
+ entry.setSize(loaded.data().length);
+ entry.setCompressedSize(loaded.data().length);
+ entry.setCrc(loaded.crc());
+
+ // Size and CRC known: written once, no header rewrite.
+ this.zip.addRawArchiveEntry(entry, new ByteArrayInputStream(loaded.data()));
+ this.budget.release(loaded.permits());
+ }
+ case Large large ->
+ {
+ InputStream input;
+ try { input = Files.newInputStream(large.file()); }
+ catch (IOException e) { this.failures.accept(e); return; }
+
+ // The listed size keeps the header free of Zip64 fields below 4 GiB; the zip
+ // stream then writes the copied size and CRC into the header.
+ ZipArchiveEntry entry = new ZipArchiveEntry(large.name());
+ entry.setMethod(ZipArchiveEntry.STORED);
+ entry.setSize(large.size());
+
+ try (input)
+ {
+ this.zip.putArchiveEntry(entry);
+ input.transferTo(this.zip);
+ this.zip.closeArchiveEntry();
+ }
+ }
+ case Failed failed -> throw new IOException(failed.cause());
+ case Done done -> throw new IllegalStateException("'Done' is no entry.");
+ }
+ }
+
+ /**
+ * A {@link FileChannel} with a write buffer: the zip stream writes headers and data in small
+ * pieces. Moving the position writes the buffer first, so patched headers land where the
+ * zip stream puts them.
+ */
+ private static final class BufferedChannel implements SeekableByteChannel
+ {
+ private final FileChannel channel;
+ private final ByteBuffer buffer = ByteBuffer.allocate(ParallelZip.BUFFER);
+
+ BufferedChannel(FileChannel channel) { this.channel = channel; }
+
+ @Override
+ public int write(ByteBuffer source) throws IOException
+ {
+ int length = source.remaining();
+
+ if (length > this.buffer.remaining()) this.flush();
+
+ if (length >= this.buffer.capacity())
+ {
+ while (source.hasRemaining()) this.channel.write(source);
+ }
+ else this.buffer.put(source);
+
+ return length;
+ }
+
+ @Override
+ public long position() throws IOException { return this.channel.position() + this.buffer.position(); }
+
+ @Override
+ public SeekableByteChannel position(long position) throws IOException
+ {
+ this.flush();
+ this.channel.position(position);
+
+ return this;
+ }
+
+ @Override
+ public long size() throws IOException
+ {
+ this.flush();
+
+ return this.channel.size();
+ }
+
+ @Override
+ public SeekableByteChannel truncate(long size) throws IOException
+ {
+ this.flush();
+ this.channel.truncate(size);
+
+ return this;
+ }
+
+ @Override
+ public int read(ByteBuffer target) { throw new NonReadableChannelException(); }
+
+ @Override
+ public boolean isOpen() { return this.channel.isOpen(); }
+
+ @Override
+ public void close() throws IOException
+ {
+ try { this.flush(); }
+ finally { this.channel.close(); }
+ }
+
+ private void flush() throws IOException
+ {
+ this.buffer.flip();
+ while (this.buffer.hasRemaining()) this.channel.write(this.buffer);
+ this.buffer.clear();
+ }
+ }
+}
diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooksTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooksTest.java
new file mode 100644
index 0000000..d279572
--- /dev/null
+++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/hooks/BackupHooksTest.java
@@ -0,0 +1,186 @@
+package dev.overlord.zomboidforge.compat.b42.hooks;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import zombie.ZomboidFileSystem;
+import zombie.core.backup.ZipBackup;
+import zombie.core.random.RandStandard;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.Random;
+import java.util.TreeMap;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** The hook against vanilla's {@code ZipBackup.makeBackupFile} from the game jar, on the same cache folder. */
+class BackupHooksTest
+{
+ private static final String SERVER = "servertest";
+
+ private @TempDir Path cache;
+
+ /** Unset, {@code getCacheDir()} picks the default folder again. */
+ private static void unsetCacheDir() throws ReflectiveOperationException
+ {
+ Field field = ZomboidFileSystem.class.getDeclaredField("cacheDir");
+ field.setAccessible(true);
+ field.set(ZomboidFileSystem.instance, null);
+ }
+
+ private static Object type(String name) throws ClassNotFoundException
+ {
+ for (Object constant : Class.forName("zombie.core.backup.ZipBackup$BackupTypes").getEnumConstants()) {
+ if (((Enum>) constant).name().equals(name)) return constant;
+ }
+
+ throw new IllegalArgumentException(name);
+ }
+
+ private static void vanilla(String serverName, Object type) throws ReflectiveOperationException
+ {
+ Method make = ZipBackup.class.getDeclaredMethod("makeBackupFile", String.class, type.getClass());
+ make.setAccessible(true);
+ make.invoke(null, serverName, type);
+ }
+
+ private void write(String path, byte[] data) throws IOException
+ {
+ Path file = this.cache.resolve(path);
+ Files.createDirectories(file.getParent());
+ Files.write(file, data);
+ }
+
+ private static byte[] random(int size, long seed)
+ {
+ byte[] data = new byte[size];
+ new Random(seed).nextBytes(data);
+ return data;
+ }
+
+ /** Entry name to content and method; {@code readme.txt} holds the backup time and is compared apart. */
+ private static Map entries(Path zip) throws IOException
+ {
+ Map entries = new TreeMap<>();
+
+ try (ZipFile file = new ZipFile(zip.toFile()))
+ {
+ for (ZipEntry entry : Collections.list(file.entries()))
+ {
+ if (entry.getName().equals("readme.txt")) continue;
+
+ byte[] data = file.getInputStream(entry).readAllBytes();
+ entries.put(entry.getName(), entry.getMethod() + " " + HexFormat.of().formatHex(data));
+ }
+ }
+
+ return entries;
+ }
+
+ /** {@code ZipBackup.rotateBackupFile} reads {@code ServerOptions}, whose constructor draws a random number. */
+ @BeforeAll
+ static void initRandom()
+ {
+ RandStandard.INSTANCE.init();
+ }
+
+ @BeforeEach
+ void createCacheFolder() throws IOException
+ {
+ ZomboidFileSystem.instance.setCacheDir(this.cache.toString());
+
+ this.write("options.ini", "volume=1".getBytes(StandardCharsets.UTF_8));
+ this.write("sounds.ini", "sounds".getBytes(StandardCharsets.UTF_8));
+ this.write("mods/default.txt", "mods".getBytes(StandardCharsets.UTF_8));
+ this.write("mods/SomeMod/mod.info", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
+ this.write("Lua/settings.lua", "lua".getBytes(StandardCharsets.UTF_8));
+ this.write("db/" + BackupHooksTest.SERVER + ".db", BackupHooksTest.random(5000, 1));
+ this.write("Server/" + BackupHooksTest.SERVER + ".ini", "PVP=true".getBytes(StandardCharsets.UTF_8));
+ this.write("Server/backup/old.ini", "skipped: subfolder".getBytes(StandardCharsets.UTF_8));
+
+ String save = "Saves/Multiplayer/" + BackupHooksTest.SERVER + "/";
+ this.write(save + "map_t.bin", BackupHooksTest.random(100, 2));
+ this.write(save + "players.db", BackupHooksTest.random(5 << 20, 3));
+ this.write(save + "blam/skipped.bin", BackupHooksTest.random(10, 4));
+ this.write(save + "map/blam/skipped.bin", BackupHooksTest.random(10, 5));
+ for (int x = 0; x < 10; x++) {
+ for (int y = 0; y < 10; y++) this.write(save + "map/" + x + "/" + y + ".bin", BackupHooksTest.random(x * 300 + y, x * 100L + y));
+ }
+ Files.createDirectories(this.cache.resolve(save + "isoregiondata"));
+ }
+
+ @AfterEach
+ void resetCacheFolder() throws ReflectiveOperationException
+ {
+ BackupHooksTest.unsetCacheDir();
+ }
+
+ @Test
+ void writesTheEntriesOfVanilla() throws Exception
+ {
+ BackupHooksTest.vanilla(BackupHooksTest.SERVER, BackupHooksTest.type("version"));
+ BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
+
+ Path vanilla = this.cache.resolve("backups/version/backup_1.zip");
+ Path hooked = this.cache.resolve("backups/period/backup_1.zip");
+
+ Map expected = BackupHooksTest.entries(vanilla);
+ assertTrue(expected.containsKey("Saves/Multiplayer/" + BackupHooksTest.SERVER + "/map/9/9.bin"), expected.keySet().toString());
+ assertFalse(expected.containsKey("mods/SomeMod/mod.info"));
+ assertEquals(expected, BackupHooksTest.entries(hooked));
+
+ try (ZipFile vanillaZip = new ZipFile(vanilla.toFile()); ZipFile hookedZip = new ZipFile(hooked.toFile()))
+ {
+ byte[] vanillaReadme = vanillaZip.getInputStream(vanillaZip.getEntry("readme.txt")).readAllBytes();
+ byte[] hookedReadme = hookedZip.getInputStream(hookedZip.getEntry("readme.txt")).readAllBytes();
+
+ // Both start with the backup time, to the second.
+ String readme = new String(hookedReadme, StandardCharsets.UTF_8);
+ assertTrue(readme.startsWith("Backup time: "), readme);
+ assertEquals(readme, hookedZip.getComment());
+ assertArrayEquals(BackupHooksTest.tail(vanillaReadme), BackupHooksTest.tail(hookedReadme));
+ }
+ }
+
+ /** The readme after its first line, the backup time. */
+ private static byte[] tail(byte[] readme)
+ {
+ String text = new String(readme, StandardCharsets.UTF_8);
+ return text.substring(text.indexOf('\n')).getBytes(StandardCharsets.UTF_8);
+ }
+
+ @Test
+ void rotatesTheBackupsAsVanilla() throws Exception
+ {
+ BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
+ BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
+
+ assertTrue(Files.exists(this.cache.resolve("backups/period/backup_1.zip")));
+ assertTrue(Files.exists(this.cache.resolve("backups/period/backup_2.zip")));
+ }
+
+ @Test
+ void doesNotThrowWhenTheBackupFails() throws Exception
+ {
+ // A folder where the zip file goes: opening it fails.
+ Files.createDirectories(this.cache.resolve("backups/period/backup_1.zip/blocked"));
+
+ BackupHooks.makeBackupFile(BackupHooksTest.SERVER, BackupHooksTest.type("period"));
+ }
+}
diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZipTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZipTest.java
new file mode 100644
index 0000000..8817ac5
--- /dev/null
+++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/ParallelZipTest.java
@@ -0,0 +1,219 @@
+package dev.overlord.zomboidforge.compat.b42.util;
+
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipFile;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+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.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.TreeMap;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ParallelZipTest
+{
+ private static byte[] random(int size, long seed)
+ {
+ byte[] data = new byte[size];
+ new Random(seed).nextBytes(data);
+ return data;
+ }
+
+ private static void write(Path file, byte[] data) throws IOException
+ {
+ Files.createDirectories(file.getParent());
+ Files.write(file, data);
+ }
+
+ /** Entry name to content, read with {@code ZipInputStream}, which checks each entry's CRC and size. */
+ private static Map entries(Path zip) throws IOException
+ {
+ Map entries = new TreeMap<>();
+
+ try (ZipInputStream input = new ZipInputStream(Files.newInputStream(zip)))
+ {
+ for (ZipEntry entry = input.getNextEntry(); entry != null; entry = input.getNextEntry()) {
+ entries.put(entry.getName(), input.readAllBytes());
+ }
+ }
+
+ return entries;
+ }
+
+ private static Path zip(Path temp, Path folder, String prefix) throws IOException
+ {
+ Path zip = temp.resolve("out.zip");
+
+ try (ParallelZip writer = new ParallelZip(zip, "comment", 4, e -> { throw new AssertionError(e); }))
+ {
+ writer.addFolder(prefix, folder, subfolder -> !subfolder.endsWith("blam"));
+ writer.finish();
+ }
+
+ return zip;
+ }
+
+ @Test
+ void addsEveryFileOfTheTreeExceptSkippedFolders(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("save");
+ List expected = new ArrayList<>();
+
+ for (int x = 0; x < 20; x++)
+ {
+ for (int y = 0; y < 30; y++)
+ {
+ ParallelZipTest.write(root.resolve("map/" + x + "/" + y + ".bin"), ParallelZipTest.random(x * 100 + y, x * 1000L + y));
+ expected.add("world/map/" + x + "/" + y + ".bin");
+ }
+ }
+ ParallelZipTest.write(root.resolve("map_t.bin"), ParallelZipTest.random(10, 1));
+ ParallelZipTest.write(root.resolve("blam/skipped.bin"), ParallelZipTest.random(10, 2));
+ ParallelZipTest.write(root.resolve("map/blam/skipped.bin"), ParallelZipTest.random(10, 3));
+ ParallelZipTest.write(root.resolve("notblam/kept.bin"), ParallelZipTest.random(10, 4));
+ Files.createDirectories(root.resolve("empty"));
+ expected.add("world/map_t.bin");
+ expected.add("world/notblam/kept.bin");
+
+ Map entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
+
+ Collections.sort(expected);
+ assertEquals(expected, new ArrayList<>(entries.keySet()));
+ for (String name : expected) assertArrayEquals(Files.readAllBytes(root.resolve(name.substring("world/".length()))), entries.get(name), name);
+ }
+
+ @Test
+ void addsOnlyTopLevelFilesWhenNotDescending(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("mods");
+ ParallelZipTest.write(root.resolve("a.txt"), "a".getBytes(StandardCharsets.UTF_8));
+ ParallelZipTest.write(root.resolve("sub/b.txt"), "b".getBytes(StandardCharsets.UTF_8));
+ Path zip = temp.resolve("out.zip");
+
+ try (ParallelZip writer = new ParallelZip(zip, "", 2, e -> { throw new AssertionError(e); }))
+ {
+ writer.addFolder("mods", root, subfolder -> false);
+ writer.finish();
+ }
+
+ assertEquals(List.of("mods/a.txt"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
+ }
+
+ /** Large files are copied by the writing thread; more read data than the budget waits for it. */
+ @Test
+ void writesLargeFilesAndMoreThanTheBudget(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("save");
+ for (int i = 0; i < 80; i++) ParallelZipTest.write(root.resolve("chunks/" + i + ".bin"), ParallelZipTest.random(1 << 20, i));
+ ParallelZipTest.write(root.resolve("players.db"), ParallelZipTest.random(9 << 20, 100));
+
+ Map entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
+
+ assertEquals(81, entries.size());
+ assertArrayEquals(Files.readAllBytes(root.resolve("players.db")), entries.get("world/players.db"));
+ assertArrayEquals(Files.readAllBytes(root.resolve("chunks/42.bin")), entries.get("world/chunks/42.bin"));
+ }
+
+ /** As {@code ParallelScatterZipCreator}'s entries: STORED, without Zip64 fields; the comment is set. */
+ @Test
+ void writesStoredEntriesWithoutZip64Fields(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("save");
+ ParallelZipTest.write(root.resolve("small.bin"), ParallelZipTest.random(100, 1));
+ ParallelZipTest.write(root.resolve("large.bin"), ParallelZipTest.random(5 << 20, 2));
+ Path zip = ParallelZipTest.zip(temp, root, "world");
+
+ try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip.toFile())) { assertEquals("comment", file.getComment()); }
+
+ try (ZipFile file = ZipFile.builder().setPath(zip).get())
+ {
+ for (ZipArchiveEntry entry : Collections.list(file.getEntries()))
+ {
+ assertEquals(ZipEntry.STORED, entry.getMethod(), entry.getName());
+ assertEquals(0, entry.getLocalFileDataExtra().length, entry.getName());
+ assertEquals(0, entry.getCentralDirectoryExtra().length, entry.getName());
+ assertTrue(file.canReadEntryData(entry));
+
+ try (InputStream input = file.getInputStream(entry)) { assertEquals(entry.getSize(), input.readAllBytes().length); }
+ }
+ }
+ }
+
+ @Test
+ void reportsAndSkipsFilesThatCannotBeRead(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("save");
+ ParallelZipTest.write(root.resolve("kept.bin"), ParallelZipTest.random(10, 1));
+ Files.createSymbolicLink(root.resolve("dangling.bin"), root.resolve("missing.bin"));
+ Path zip = temp.resolve("out.zip");
+ List failures = Collections.synchronizedList(new ArrayList<>());
+
+ try (ParallelZip writer = new ParallelZip(zip, "", 2, failures::add))
+ {
+ writer.addFolder("world", root, subfolder -> true);
+ writer.finish();
+ }
+
+ assertEquals(List.of("world/kept.bin"), new ArrayList<>(ParallelZipTest.entries(zip).keySet()));
+ assertEquals(1, failures.size());
+ assertTrue(failures.getFirst().getMessage().contains("dangling.bin"), failures.getFirst().getMessage());
+ }
+
+ @Test
+ void addsLinkedFilesWithTheirContent(@TempDir Path temp) throws IOException
+ {
+ Path root = temp.resolve("save");
+ ParallelZipTest.write(temp.resolve("target.bin"), ParallelZipTest.random(10, 1));
+ Files.createDirectories(root);
+ Files.createSymbolicLink(root.resolve("link.bin"), temp.resolve("target.bin"));
+
+ Map entries = ParallelZipTest.entries(ParallelZipTest.zip(temp, root, "world"));
+
+ assertArrayEquals(Files.readAllBytes(temp.resolve("target.bin")), entries.get("world/link.bin"));
+ }
+
+ @Test
+ void addsTextAndSingleFiles(@TempDir Path temp) throws IOException
+ {
+ Path file = temp.resolve("options.ini");
+ ParallelZipTest.write(file, "volume=1".getBytes(StandardCharsets.UTF_8));
+ Path zip = temp.resolve("out.zip");
+
+ try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); }))
+ {
+ writer.addText("readme.txt", "Backup time: now");
+ writer.addFile("options.ini", file);
+ writer.finish();
+ }
+
+ Map entries = ParallelZipTest.entries(zip);
+ assertEquals("Backup time: now", new String(entries.get("readme.txt"), StandardCharsets.UTF_8));
+ assertEquals("volume=1", new String(entries.get("options.ini"), StandardCharsets.UTF_8));
+ }
+
+ /** Without finish(), as after a failure, the file has no central directory. */
+ @Test
+ void unfinishedFileIsNoZip(@TempDir Path temp) throws IOException
+ {
+ Path zip = temp.resolve("out.zip");
+
+ try (ParallelZip writer = new ParallelZip(zip, "", 1, e -> { throw new AssertionError(e); })) { writer.addText("readme.txt", "text"); }
+
+ assertTrue(Files.size(zip) > 0);
+ assertThrows(IOException.class, () -> ZipFile.builder().setPath(zip).get().close());
+ }
+}
diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java
index 6c1ace9..46847ec 100644
--- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java
+++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/MethodBody.java
@@ -12,18 +12,20 @@ import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.objectweb.asm.tree.VarInsnNode;
-import java.util.Arrays;
-
/** Replaces the body of a method of the target class with a call to a {@link Hook}, or wraps it in hook calls. */
public final class MethodBody
{
+ private static final Type OBJECT = Type.getObjectType("java/lang/Object");
+
private MethodBody() {}
/**
* Replaces the body of {@code method} with {@code return hook(arguments);}: the hook receives
* the method's arguments, without {@code this}, and has the method's parameter and return
- * types. Fails when the method has no body, when the types differ, or when an instance
- * method's old body uses {@code this}, which the hook would not receive.
+ * types; a parameter of a reference type may be {@code Object} in the hook, for types the hook
+ * cannot name (private classes of the game). Fails when the method has no body, when the types
+ * differ otherwise, or when an instance method's old body uses {@code this}, which the hook
+ * would not receive.
*/
public static void delegate(ClassNode node, MethodNode method, Hook hook)
{
@@ -35,7 +37,7 @@ public final class MethodBody
if ((method.access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0)
throw new IllegalStateException(name + " has no body.");
- if (!Arrays.equals(type.getArgumentTypes(), hookType.getArgumentTypes()) || !type.getReturnType().equals(hookType.getReturnType()))
+ if (!MethodBody.accepts(hookType.getArgumentTypes(), type.getArgumentTypes()) || !type.getReturnType().equals(hookType.getReturnType()))
throw new IllegalStateException(name + " and its hook '" + hook.owner() + "." + hook.name() + hook.desc() + "' have different types.");
if (!isStatic && MethodBody.usesThis(method))
@@ -123,6 +125,22 @@ public final class MethodBody
return new MethodInsnNode(Opcodes.INVOKESTATIC, hook.owner(), hook.name(), hook.desc(), false);
}
+ /** Whether a hook with {@code parameters} takes {@code arguments}: equal types, or {@code Object} for a reference type. */
+ private static boolean accepts(Type[] parameters, Type[] arguments)
+ {
+ if (parameters.length != arguments.length) return false;
+
+ for (int i = 0; i < arguments.length; i++)
+ {
+ boolean reference = arguments[i].getSort() == Type.OBJECT || arguments[i].getSort() == Type.ARRAY;
+ boolean asObject = reference && parameters[i].equals(MethodBody.OBJECT);
+
+ if (!parameters[i].equals(arguments[i]) && !asObject) return false;
+ }
+
+ return true;
+ }
+
/** Whether the method reads or writes local variable 0, which holds {@code this}. */
private static boolean usesThis(MethodNode method)
{
diff --git a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
index 19c5bad..da7bfd5 100644
--- a/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
+++ b/patcher/src/test/java/dev/overlord/zomboidforge/patcher/MethodBodyTest.java
@@ -45,6 +45,10 @@ public class MethodBodyTest
public static void record(String value) { MethodBodyTest.recorded = value; }
+ public static void recordAny(String value, Object other) { MethodBodyTest.recorded = value + " " + other; }
+
+ public static void recordObject(Object value) { MethodBodyTest.recorded = String.valueOf(value); }
+
/** Calls of the hooks below, in order. */
public static final List EVENTS = new ArrayList<>();
@@ -148,6 +152,28 @@ public class MethodBodyTest
assertEquals("saved", MethodBodyTest.recorded);
}
+ @Test
+ void hookTakesAReferenceArgumentAsObject() throws ReflectiveOperationException
+ {
+ ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(Ljava/lang/String;Ljava/lang/StringBuilder;)V", false);
+ MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "recordAny", "(Ljava/lang/String;Ljava/lang/Object;)V"));
+
+ MethodBodyTest.recorded = null;
+ MethodBodyTest.run(node, "save", new Class>[] { String.class, StringBuilder.class }, "saved", new StringBuilder("text"));
+ assertEquals("saved text", MethodBodyTest.recorded);
+ }
+
+ @Test
+ void failsWhenTheHookTakesAPrimitiveArgumentAsObject()
+ {
+ ClassNode node = MethodBodyTest.target(ACC_PUBLIC | ACC_STATIC, "save", "(I)V", false);
+
+ IllegalStateException e = assertThrows(IllegalStateException.class, () ->
+ MethodBody.delegate(node, MethodBodyTest.method(node, "save"), new Hook(MethodBodyTest.HOOKS, "recordObject", "(Ljava/lang/Object;)V"))
+ );
+ assertTrue(e.getMessage().contains("different types"), e.getMessage());
+ }
+
@Test
void dropsTheLocalVariablesOfTheOldBody()
{