From 6761f2d9ea36cdfd34759b2d1fe9e20e3e9a1dc8 Mon Sep 17 00:00:00 2001 From: Overlord Date: Sat, 3 Oct 2026 09:59:47 +0200 Subject: [PATCH] Add `ModCheckTest` to test runtime mod validations and entry point superclass checks. Include Gradle verification metadata for dependency integrity. --- .gitea/workflows/ci.yml | 2 +- .gitea/workflows/publish.yml | 13 +- .gitea/workflows/release.yml | 7 +- Dockerfile | 9 +- MOD_DEVELOPMENT.md | 13 +- README.md | 5 + agent/build.gradle.kts | 22 +- .../zomboidforge/api/GameVersion.java | 5 +- .../zomboidforge/api/storage/ModStorage.java | 7 +- .../zomboidforge/api/storage/Table.java | 8 +- .../zomboidforge/api/GameVersionTest.java | 10 + ci/publish.sh | 61 +- ci/steam-buildid.sh | 2 +- .../core/mods/ModClassLoader.java | 3 + .../zomboidforge/core/mods/ModVersion.java | 3 +- .../zomboidforge/core/storage/ModTables.java | 30 +- .../core/storage/RecordCodec.java | 3 +- .../core/storage/StorageDatabase.java | 30 +- .../core/mods/ModVersionTest.java | 9 + .../core/storage/ModTablesTest.java | 51 + .../zomboidforge/gradle/DownloadGame.java | 3 +- .../gradle/GenerateModDescriptor.java | 18 +- .../gradle/ZomboidForgeModPluginTest.java | 18 +- gradle/libs.versions.toml | 4 + gradle/verification-metadata.xml | 884 ++++++++++++++++++ gradle/wrapper/gradle-wrapper.properties | 1 + .../overlord/zomboidforge/tools/ModCheck.java | 39 +- .../zomboidforge/tools/ModCheckTest.java | 108 +++ .../zomboidforge/patcher/JarPatcher.java | 10 +- 29 files changed, 1306 insertions(+), 72 deletions(-) create mode 100644 gradle/verification-metadata.xml create mode 100644 mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 556e056..ae25a5e 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: - pz_version: "42" steam_branch: public steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: # release.sh derives the version from the v* tags fetch-depth: 0 diff --git a/.gitea/workflows/publish.yml b/.gitea/workflows/publish.yml index b03d780..efe9f25 100644 --- a/.gitea/workflows/publish.yml +++ b/.gitea/workflows/publish.yml @@ -14,19 +14,22 @@ jobs: maven: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: # publish.sh derives the version from the v* tag on HEAD fetch-depth: 0 - - uses: actions/setup-java@v4 + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1 with: distribution: temurin java-version: "25" - - name: Test and publish + # The tests run without the registry credentials; only the publish step gets them. + - name: Test + run: ci/publish.sh test + + - name: Publish env: ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }} ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }} - PUBLISH: "true" - run: ci/publish.sh + run: ci/publish.sh publish diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 4751894..0c0c4f2 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -24,7 +24,7 @@ jobs: steam_branch: public latest: "true" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: # release.sh derives the version from the v* tags fetch-depth: 0 @@ -43,3 +43,8 @@ jobs: PUBLISH: "true" LATEST: ${{ matrix.latest }} run: ci/release.sh + + # Removes the stored registry token, also when a step failed, in case the runner is reused. + - name: Log out of the registry + if: always() + run: docker logout git.security-command.org diff --git a/Dockerfile b/Dockerfile index f6af830..0d14573 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,8 +29,11 @@ ARG STEAMCLIENT=bundled ARG FORGE_VERSION="0.0.0-prerelease" ARG STEAM_BUILDID="" +# Base images are pinned by digest; the tag in front of the digest is for readers only. +# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame. + # --- Stage 1: vanilla dedicated server ----------------------------------------- -FROM docker.io/steamcmd/steamcmd:debian-13 AS server +FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server # steamcmd updates itself on its first run. This runs in its own layer so the # update is cached and separate from the app installation. @@ -42,7 +45,7 @@ COPY docker/install-server.sh /usr/local/bin/install-server RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}" # --- Stage 2: ZomboidForge sources and Gradle ----------------------------------- -FROM docker.io/library/eclipse-temurin:25-jdk AS sources +FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources WORKDIR /src # Gradle distribution download, cached independently of the sources. @@ -102,7 +105,7 @@ RUN ./gradlew --no-daemon \ build -x :gradle-plugin:test :patcher:patchServerJar # --- Stage 4: runtime ------------------------------------------------------------ -FROM docker.io/library/debian:trixie-slim +FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a # ca-certificates: required by steamclient.so to connect to Steam. # sqlite3: the entrypoint checks the admin account in the server database. diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 4d5b964..08a5cbd 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -213,8 +213,8 @@ it earlier. ## Storage Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's -save folder. Vanilla backups include it, and deleting the world deletes it. Each mod only -reaches its own tables. +save folder. Vanilla backups include it, and deleting the world deletes it. Through the API, +each mod only reaches its own tables. A record declares a table's columns; each row has a `String` key: @@ -268,6 +268,10 @@ Things to know: world goes back to its last save, but the mod data keeps later writes. 3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables move to the new id once. +4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits. + These callbacks must not wait for other threads, for example with + `main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs + without pausing storage, so its copy of `zomboidforge.db` may be incomplete. ## Checks at startup @@ -293,6 +297,11 @@ Every problem of every mod is listed in the log. | game jar (game code and its bundled libraries) | only with `game` declared | | ZomboidForge internals | no | +These rules keep mods from linking against the wrong classes by accident. They are not a +sandbox: a mod runs with the full privileges of the server process. Through reflection or the +file system it can reach anything the server can, including other mods' data in +`zomboidforge.db`. + ## Profiling Main-thread tasks and event listener calls appear in JFR recordings as the event diff --git a/README.md b/README.md index a980e4a..c6e0de2 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,11 @@ forge/ podman run ... -v ./forge:/forge zomboidforge ``` +Mods are trusted code. They run inside the server process with its full privileges: they can +read and write any file the server can, open network connections, and stop the server. The +class loader isolation and the startup checks catch mistakes; they do not contain a malicious +mod. Install only mods whose authors you trust. + A mod's settings live in its `config.toml`. When the file is missing, it is created from the mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]` diff --git a/agent/build.gradle.kts b/agent/build.gradle.kts index a22c8b3..41e58d9 100644 --- a/agent/build.gradle.kts +++ b/agent/build.gradle.kts @@ -2,6 +2,7 @@ plugins { id("zomboidforge.java-conventions") + alias(libs.plugins.shadow) } dependencies { @@ -11,12 +12,19 @@ dependencies { compileOnly(files(projectZomboid.serverJar)) } -tasks.jar { - archiveBaseName = "zomboidforge-agent" +// The agent jar is appended to the system class path behind the game jar and includes api, +// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same +// library in the game jar cannot replace them. +tasks.shadowJar { + archiveBaseName = "zomboidforge-agent" + archiveClassifier = "" manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent") - // The agent jar is appended to the system class path and includes api, core and compat runtime. - // Mapping the classpath to zip trees loses its task dependencies; the input restores them. - inputs.files(configurations.runtimeClasspath) - from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } }) - duplicatesStrategy = DuplicatesStrategy.EXCLUDE + + relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm") + relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig") +} + +// Only the shadow jar is used; the plain jar would match the same file name pattern. +tasks.jar { + enabled = false } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java b/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java index d279290..b826159 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/GameVersion.java @@ -9,8 +9,9 @@ import java.util.regex.Pattern; /** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */ public record GameVersion(int major, int minor, int build) implements Comparable { - private static final Pattern VERSION = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?"); - private static final Pattern PREFIX = Pattern.compile("(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?"); + // At most 9 digits per number, so every number fits an int. + private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?"); + private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?"); private static final Comparator ORDER = Comparator .comparingInt(GameVersion::major) diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java index e077816..41bb28f 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java @@ -4,7 +4,8 @@ import java.util.function.Supplier; /** * The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to - * the mod; other mods cannot reach it. + * the mod; this interface gives no access to the tables of other mods. It is not a security + * boundary: mod code runs with the server's privileges and can open the file directly. * *

A record declares a table's columns: {@code String}, {@code long}/{@code int}, * {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant}, @@ -26,6 +27,10 @@ public interface ModStorage /** * Runs {@code work} in one transaction: writes of this thread inside it are committed * together, or not at all when {@code work} throws. + * + *

Storage of every mod waits while {@code work} runs, so {@code work} must not wait for + * other threads, for example with {@code main().submit(...).join()}. A backup waits at most + * 10 seconds for it and then runs without pausing storage. */ void transaction(Runnable work); diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java index 7064082..077afcc 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java @@ -37,7 +37,11 @@ public interface Table /** Every key, sorted. */ List keys(); - /** Calls {@code action} for every row, sorted by key, without loading all rows at once. */ + /** + * Calls {@code action} for every row, sorted by key, without loading all rows at once. + * Storage of every mod waits until it returns, so {@code action} must not wait for other + * threads. + */ void forEach(BiConsumer action); long count(); @@ -45,6 +49,8 @@ public interface Table /** * Replaces the row under {@code key} with {@code change} applied to it, or to * {@code initial} when there is none, in one transaction: no other write comes in between. + * As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for + * other threads. * * @return the stored value */ diff --git a/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java b/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java index 5a383d4..50c3c4d 100644 --- a/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java +++ b/api/src/test/java/dev/overlord/zomboidforge/api/GameVersionTest.java @@ -42,6 +42,16 @@ class GameVersionTest assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1")); } + @Test + void rejectsNumbersOutsideTheIntRange() + { + GameVersion version = new GameVersion(42, 21, 3); + + assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999")); + assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999")); + assertFalse(GameVersion.isPrefix("42.99999999999")); + } + @Test void comparesNumerically() { diff --git a/ci/publish.sh b/ci/publish.sh index bd5f4df..dd76600 100755 --- a/ci/publish.sh +++ b/ci/publish.sh @@ -7,10 +7,13 @@ # A pre-release version (containing "-", e.g. 0.3.0-rc.1) is built and tested but never # published. Without a v* tag on HEAD nothing is published. # -# Environment: +# Usage: +# ci/publish.sh test runs the checks of the published modules; needs no credentials +# ci/publish.sh publish publishes them without running the checks again +# +# Environment (publish only): # ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access # ORG_GRADLE_PROJECT_giteaPassword Token of that user -# PUBLISH true: publish after the tests. Default: false (test only) set -o errexit set -o nounset @@ -19,8 +22,6 @@ set -o pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" readonly REPO_ROOT -readonly REQUESTED_PUBLISH="${PUBLISH:-false}" - readonly MODULES=( api mod-tools @@ -61,36 +62,54 @@ run_gradle() { "$@" } -main() { - local version - local publish="${REQUESTED_PUBLISH}" +run_tests() { + local version="$1" local check_tasks - local publish_tasks - - version="$(release_tag_version)" - if [[ -z "${version}" ]]; then - log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish." - exit 1 - fi - if [[ "${version}" == *-* ]]; then - publish=false - log "${version} is a pre-release version; nothing will be published." - fi mapfile -t check_tasks < <(module_tasks check) - mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository) log "Testing ZomboidForge ${version}: ${MODULES[*]}" run_gradle "${version}" :core:check "${check_tasks[@]}" +} - if [[ "${publish}" != "true" ]]; then - log "Not publishing (PUBLISH=${REQUESTED_PUBLISH})." +publish() { + local version="$1" + local publish_tasks + + if [[ "${version}" == *-* ]]; then + log "${version} is a pre-release version; nothing is published." return fi + mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository) + log "Publishing ZomboidForge ${version}" run_gradle "${version}" "${publish_tasks[@]}" log "Published ${MODULES[*]} ${version}" } +main() { + local step="${1:-}" + local version + + version="$(release_tag_version)" + if [[ -z "${version}" ]]; then + log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish." + exit 1 + fi + + case "${step}" in + test) + run_tests "${version}" + ;; + publish) + publish "${version}" + ;; + *) + log "Usage: ci/publish.sh test|publish" + exit 2 + ;; + esac +} + main "$@" diff --git a/ci/steam-buildid.sh b/ci/steam-buildid.sh index 35b7656..5efa38c 100755 --- a/ci/steam-buildid.sh +++ b/ci/steam-buildid.sh @@ -14,7 +14,7 @@ set -o nounset set -o pipefail readonly APP_ID="380870" -readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13" +readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d" readonly BRANCH="$1" 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 1d0004e..5df4033 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 @@ -29,6 +29,9 @@ import java.util.stream.Collectors; * * 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. + * + *

The lookup order prevents accidental linkage only. It is not a security boundary: mod code + * can still reach other classes through reflection or {@link ClassLoader#getSystemClassLoader()}. */ final class ModClassLoader extends URLClassLoader { diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java index 4388e7a..cb11b96 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModVersion.java @@ -13,7 +13,8 @@ import java.util.regex.Pattern; */ public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable { - private static final Pattern FORMAT = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-([0-9A-Za-z.-]+))?"); + // At most 9 digits per number, so every number fits an int. + private static final Pattern FORMAT = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9}))?(?:\\.(\\d{1,9}))?(?:-([0-9A-Za-z.-]+))?"); private static final Comparator ORDER = Comparator .comparingInt(ModVersion::major) diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java index 53fe1bf..4bd0a15 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java @@ -44,6 +44,13 @@ public final class ModTables implements ModStorage /** A stored schema. */ private record Schema(int version, List columns) {} + /** Work on one stored row; may throw {@link SQLException}. */ + @FunctionalInterface + private interface RowAction + { + void accept(Row row) throws SQLException; + } + private final String id; private final StorageDatabase database; private final System.Logger logger; @@ -226,13 +233,12 @@ public final class ModTables implements ModStorage throw new StorageException(table + " has schema version " + stored.version() + ", the mod declares " + this.version + " but no migration from " + stored.version() + "."); String rebuilt = physical + "__migrating"; - List rows = ModTables.rows(connection, physical); SqlTable target = new SqlTable<>(ModTables.this.database, codec, rebuilt); ModTables.execute(connection, "DROP TABLE IF EXISTS " + SqlTable.quoted(rebuilt)); ModTables.create(connection, rebuilt, codec.columns()); - for (Row row : rows) + int migrated = ModTables.forEachRow(connection, physical, row -> { R record; @@ -240,13 +246,13 @@ public final class ModTables implements ModStorage catch (RuntimeException e) { throw new StorageException(table + ": the migration from version " + stored.version() + " failed for row '" + row.key() + "': " + e, e); } target.set(row.key(), record); - } + }); ModTables.execute(connection, "DROP TABLE " + SqlTable.quoted(physical)); ModTables.execute(connection, "ALTER TABLE " + SqlTable.quoted(rebuilt) + " RENAME TO " + SqlTable.quoted(physical)); ModTables.this.saveSchema(connection, this.name, this.version, codec.columns()); - ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + rows.size() + " row(s) from schema version " + stored.version() + " to " + this.version + "."); + ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + migrated + " row(s) from schema version " + stored.version() + " to " + this.version + "."); } } @@ -276,10 +282,15 @@ public final class ModTables implements ModStorage ModTables.execute(connection, "CREATE TABLE " + SqlTable.quoted(physical) + " (" + SqlTable.quoted(SqlTable.KEY) + " TEXT PRIMARY KEY NOT NULL" + definitions + ")"); } - /** Every row of {@code physical} with all its columns, sorted by key. */ - private static List rows(Connection connection, String physical) throws SQLException + /** + * Calls {@code action} for every row of {@code physical} with all its columns, sorted by key, + * reading one row at a time. + * + * @return the number of rows + */ + private static int forEachRow(Connection connection, String physical, RowAction action) throws SQLException { - List rows = new ArrayList<>(); + int count = 0; try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM " + SqlTable.quoted(physical) + " ORDER BY " + SqlTable.quoted(SqlTable.KEY))) { @@ -299,11 +310,12 @@ public final class ModTables implements ModStorage else values.put(column, value instanceof Integer number ? Long.valueOf(number) : value); } - rows.add(new StoredRow(key, values)); + action.accept(new StoredRow(key, values)); + count++; } } - return rows; + return count; } private static List tableNames(Connection connection, String mod) throws SQLException diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java index 1ce412a..1902866 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java @@ -102,7 +102,8 @@ final class RecordCodec if (stored == null && !column.nullable()) throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' is null in the database."); - arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored); + try { arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored); } + catch (RuntimeException e) { throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' holds '" + stored + "', which is not a valid '" + this.types[i].getSimpleName() + "': " + e, e); } } try { return this.type.cast(this.constructor.invokeWithArguments(arguments)); } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java index 2b29811..0641709 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java @@ -12,6 +12,8 @@ import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; +import java.time.Duration; +import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BooleanSupplier; @@ -32,6 +34,9 @@ public final class StorageDatabase implements AutoCloseable /** File name, in the world's save folder. */ public static final String FILE = "zomboidforge.db"; + /** Longest wait of a backup for the running storage operation. */ + static final Duration BACKUP_WAIT = Duration.ofSeconds(10); + /** Work with the connection that has a result; may throw {@link SQLException}. */ @FunctionalInterface public interface Work @@ -156,15 +161,30 @@ public final class StorageDatabase implements AutoCloseable } /** - * Blocks storage for a backup of the save folder: waits for the running operation, writes - * the WAL into the database file ({@code PRAGMA wal_checkpoint(TRUNCATE)}), and keeps the - * lock until {@link #backupFinished()} on the same thread. Other threads' storage calls wait. + * Blocks storage for a backup of the save folder: waits up to {@link #BACKUP_WAIT} for the + * running operation, writes the WAL into the database file + * ({@code PRAGMA wal_checkpoint(TRUNCATE)}), and keeps the lock until + * {@link #backupFinished()} on the same thread. Other threads' storage calls wait. + * + *

When the running operation takes longer, for example a transaction that waits for the + * thread making the backup, the backup runs without the lock and storage stays usable. * * @return a problem to log, or {@code null} */ - public @Nullable String backupStarted() + public @Nullable String backupStarted() { return this.backupStarted(StorageDatabase.BACKUP_WAIT); } + + @Nullable String backupStarted(Duration wait) { - this.lock.lock(); + try + { + if (!this.lock.tryLock(wait.toMillis(), TimeUnit.MILLISECONDS)) + return "Storage was busy for " + wait.toSeconds() + " s; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete."; + } + catch (InterruptedException e) + { + Thread.currentThread().interrupt(); + return "Interrupted while waiting for storage; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete."; + } Connection connection = this.connection; if (connection == null) return null; diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java index 416d58b..2019e7b 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/mods/ModVersionTest.java @@ -26,6 +26,15 @@ class ModVersionTest assertThrows(IllegalArgumentException.class, () -> ModVersion.parse("v1.0")); } + @Test + void rejectsNumbersOutsideTheIntRange() + { + assertEquals(new ModVersion(999999999, 0, 0, null), ModVersion.parse("999999999")); + assertTrue(ModVersion.tryParse("99999999999").isEmpty()); + assertTrue(ModVersion.tryParse("1.99999999999").isEmpty()); + assertTrue(ModVersion.tryParse("1.0.99999999999").isEmpty()); + } + @Test void preReleaseSortsBeforeRelease() { diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java index aa54a99..92dac79 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -13,6 +13,7 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -34,6 +35,8 @@ class ModTablesTest { private enum Mode { EASY, HARD } + private enum RenamedMode { SIMPLE, HARD } + private record Everything(String text, long big, int small, double ratio, float factor, boolean flag, byte[] bytes, UUID id, Instant when, Mode mode, @Nullable Long optional) {} private record Balance(long coins) {} @@ -46,6 +49,10 @@ class ModTablesTest private record Empty() {} + private record Difficulty(Mode mode) {} + + private record RenamedDifficulty(RenamedMode mode) {} + @TempDir Path directory; @@ -90,6 +97,18 @@ class ModTablesTest assertTrue(Files.isRegularFile(this.file), "the database is created on first use"); } + @Test + void reportsUnreadableStoredValuesAsStorageExceptions() + { + this.storage("shop").table("difficulties", Difficulty.class).set("a", new Difficulty(Mode.EASY)); + + Table renamed = this.storage("shop").table("difficulties", RenamedDifficulty.class); + + StorageException e = assertThrows(StorageException.class, () -> renamed.get("a")); + assertTrue(e.getMessage().startsWith("Column 'mode' of 'RenamedDifficulty' holds 'EASY', which is not a valid 'RenamedMode': "), e.getMessage()); + assertThrows(StorageException.class, () -> renamed.forEach((key, difficulty) -> {})); + } + @Test void readsAndWritesRows() { @@ -321,6 +340,38 @@ class ModTablesTest assertTrue(balances.contains("b")); } + @Test + void backupsDoNotWaitForeverForStorage() throws Exception + { + Table balances = this.storage("shop").table("balances", Balance.class); + balances.set("a", new Balance(1)); + + CountDownLatch inside = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = Thread.ofPlatform().start(() -> this.storage("shop").transaction(() -> { + inside.countDown(); + ModTablesTest.await(release); + })); + + assertTrue(inside.await(5, TimeUnit.SECONDS)); + + String problem = this.database.backupStarted(Duration.ofSeconds(1)); + assertEquals("Storage was busy for 1 s; the backup runs without pausing storage, so its copy of 'zomboidforge.db' may be incomplete.", problem); + this.database.backupFinished(); + + release.countDown(); + holder.join(); + + balances.set("b", new Balance(2)); + assertTrue(balances.contains("b"), "storage stays usable after the skipped pause"); + } + + private static void await(CountDownLatch latch) + { + try { latch.await(); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); } + } + @Test void rejectsBadNamesTypesAndUseAfterClose() { diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java index b0caa11..9fca239 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/DownloadGame.java @@ -32,7 +32,8 @@ public abstract class DownloadGame extends DefaultTask static final String JAR = "java/projectzomboid.jar"; private static final String APP_ID = "380870"; - private static final String IMAGE = "docker.io/steamcmd/steamcmd:latest"; + // The same image as the Dockerfile's server stage. + private static final String IMAGE = "docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"; private static final int MAX_ATTEMPTS = 3; @Internal diff --git a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java index 7584c04..62273bb 100644 --- a/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java +++ b/gradle-plugin/src/main/java/dev/overlord/zomboidforge/gradle/GenerateModDescriptor.java @@ -102,7 +102,7 @@ public abstract class GenerateModDescriptor extends DefaultTask if (!dependencies.isEmpty()) { toml.append("\n[dependencies]\n"); - dependencies.forEach((id, version) -> toml.append(id).append(" = ").append(GenerateModDescriptor.string(version)).append('\n')); + dependencies.forEach((id, version) -> toml.append(GenerateModDescriptor.string(id)).append(" = ").append(GenerateModDescriptor.string(version)).append('\n')); } return toml.toString(); @@ -110,6 +110,18 @@ public abstract class GenerateModDescriptor extends DefaultTask private static String list(List values) { return values.stream().map(GenerateModDescriptor::string).collect(Collectors.joining(", ", "[", "]")); } - /** A TOML basic string. */ - private static String string(String value) { return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; } + /** A TOML basic string, also used for keys: backslashes, quotes, and control characters are escaped. */ + private static String string(String value) + { + StringBuilder escaped = new StringBuilder("\""); + + for (char c : value.toCharArray()) + { + if (c == '\\' || c == '"') escaped.append('\\').append(c); + else if (c < 0x20 || c == 0x7F) escaped.append(String.format("\\u%04X", (int) c)); + else escaped.append(c); + } + + return escaped.append('"').toString(); + } } diff --git a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java index e402e36..67ce66d 100644 --- a/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java +++ b/gradle-plugin/src/test/java/dev/overlord/zomboidforge/gradle/ZomboidForgeModPluginTest.java @@ -177,7 +177,7 @@ class ZomboidForgeModPluginTest String toml = new String(jar.getInputStream(jar.getEntry("META-INF/zomboidforge/mod.toml")).readAllBytes(), StandardCharsets.UTF_8); assertTrue(toml.contains("game = [\"42.21\"]"), toml); - assertTrue(toml.contains("[dependencies]\neconomy = \"2.0\""), toml); + assertTrue(toml.contains("[dependencies]\n\"economy\" = \"2.0\""), toml); } } @@ -207,6 +207,22 @@ class ZomboidForgeModPluginTest assertTrue(result.getOutput().contains("is written by hand; the ZomboidForge plugin generates mod.toml from zomboidForge { }."), result.getOutput()); } + @Test + void writesAnyTextAsValidToml() throws IOException + { + this.modProject(""" + name = "Shop\\tMod \\"one\\"" + dependsOn("eco.nomy", "2.0") + """, ""); + + BuildResult result = this.runner("build").buildAndFail(); + + assertTrue(result.getOutput().contains("'dependencies' contains 'eco.nomy', which is not a valid mod id."), result.getOutput()); + + String toml = Files.readString(this.project.resolve("build/generated/zomboidforge/descriptor/META-INF/zomboidforge/mod.toml")); + assertTrue(toml.contains("name = \"Shop\\u0009Mod \\\"one\\\"\""), toml); + } + @Test void failsWhenTheEntryPointIsMissing() throws IOException { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 9580f83..6750488 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,6 +3,7 @@ asm = "9.10.1" junit = "6.1.3" jetbrains-annotations = "26.0.2" night-config = "3.9.0" +shadow = "9.6.1" sqlite-jdbc = "3.48.0.0" # Same version as the SQLite JDBC driver bundled in Project Zomboid (sqlite-jdbc.properties). [libraries] @@ -20,3 +21,6 @@ junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher [bundles] asm = ["asm", "asm-tree", "asm-commons", "asm-util"] + +[plugins] +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml new file mode 100644 index 0000000..d443efa --- /dev/null +++ b/gradle/verification-metadata.xml @@ -0,0 +1,884 @@ + + + + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9b7cb4a..d295f5e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,5 @@ distributionBase=GRADLE_USER_HOME +distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6c distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip networkTimeout=10000 diff --git a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java index f2b265a..e5942cd 100644 --- a/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java +++ b/mod-tools/src/main/java/dev/overlord/zomboidforge/tools/ModCheck.java @@ -174,7 +174,7 @@ public final class ModCheck if (descriptor == null) return new Result(null, null, problems); ModCheck.checkDefaultConfig(arguments.jar(), problems); - ModCheck.checkEntrypoint(arguments.jar(), descriptor, problems); + ModCheck.checkEntrypoint(arguments, descriptor, problems); List candidates = new ArrayList<>(); @@ -283,9 +283,14 @@ public final class ModCheck } } - /** The entry point and its superclasses inside the jar must lead to {@code Mod}. */ - private static void checkEntrypoint(Path jar, ModDescriptor descriptor, List problems) + /** + * The entry point must be in the jar, and its superclasses must lead to {@code Mod}. As in the + * server's class loader, superclasses come from the jar, its libraries, and then its + * dependencies. + */ + private static void checkEntrypoint(Arguments arguments, ModDescriptor descriptor, List problems) { + Path jar = arguments.jar(); String entrypoint = descriptor.entrypoint(); ClassNode type = ModCheck.classNode(jar, entrypoint.replace('.', '/'), problems); @@ -300,6 +305,11 @@ public final class ModCheck boolean constructor = type.methods.stream().anyMatch(ModCheck::isPublicNoArgConstructor); if (!constructor || (type.access & Opcodes.ACC_PUBLIC) == 0) problems.add("The entry point '" + entrypoint + "' needs to be public, with a public constructor without parameters."); + List visible = new ArrayList<>(); + visible.add(jar); + visible.addAll(arguments.libraries()); + visible.addAll(arguments.dependencies()); + ClassNode current = type; for (int depth = 0; depth < 32; depth++) @@ -309,7 +319,13 @@ public final class ModCheck if (ModCheck.MOD_CLASS.equals(superName)) return; if (superName == null) break; - ClassNode parent = ModCheck.classNode(jar, superName, problems); + ClassNode parent = ModCheck.classNode(visible, superName, problems); + + if (parent == null && !ModCheck.isJdkClass(superName)) { + problems.add("The entry point '" + entrypoint + "' extends '" + superName.replace('/', '.') + "', which is not in '" + jar.getFileName() + "', its libraries, or its dependencies."); + return; + } + if (parent == null) break; current = parent; @@ -344,6 +360,21 @@ public final class ModCheck } } + /** Whether {@code internalName} is a JDK class; none of them leads to {@code Mod}. */ + private static boolean isJdkClass(String internalName) { return ClassLoader.getPlatformClassLoader().getResource(internalName + ".class") != null; } + + /** The class from the first of {@code jars} that contains it. */ + private static @Nullable ClassNode classNode(List jars, String internalName, List problems) + { + for (Path jar : jars) + { + ClassNode node = ModCheck.classNode(jar, internalName, problems); + if (node != null) return node; + } + + return null; + } + private static @Nullable ClassNode classNode(Path jar, String internalName, List problems) { byte[] bytes = ModCheck.bytes(jar, internalName + ".class", problems); diff --git a/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java new file mode 100644 index 0000000..8506e21 --- /dev/null +++ b/mod-tools/src/test/java/dev/overlord/zomboidforge/tools/ModCheckTest.java @@ -0,0 +1,108 @@ +package dev.overlord.zomboidforge.tools; + +import org.jetbrains.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ModCheckTest +{ + private static final String MOD = "dev/overlord/zomboidforge/api/Mod"; + private static final String TOML = """ + id = "shop" + version = "1.0.0" + entrypoint = "a.Main" + api = "0.3" + """; + + @TempDir + Path directory; + + @Test + void findsEntryPointSuperclassesInLibraries() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "b/Base"))); + Path library = this.jar("base.jar", null, Map.of("b/Base", ModCheckTest.type("b/Base", ModCheckTest.MOD))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(library), List.of(), null)); + + assertEquals(List.of(), result.problems()); + } + + @Test + void reportsSuperclassesThatAreNowhere() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "b/Base"))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)); + + assertEquals(List.of("The entry point 'a.Main' extends 'b.Base', which is not in 'shop.jar', its libraries, or its dependencies."), result.problems()); + } + + @Test + void reportsEntryPointsThatDoNotExtendMod() throws IOException + { + Path mod = this.jar("shop.jar", ModCheckTest.TOML, Map.of("a/Main", ModCheckTest.type("a/Main", "java/lang/Thread"))); + + ModCheck.Result result = ModCheck.check(new ModCheck.Arguments(mod, null, List.of(), List.of(), null)); + + assertEquals(List.of("The entry point 'a.Main' does not extend 'dev.overlord.zomboidforge.api.Mod'."), result.problems()); + } + + /** A public class extending {@code superName} with a public constructor without parameters. */ + private static byte[] type(String name, String superName) + { + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + writer.visit(V25, ACC_PUBLIC, name, null, superName, null); + + 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); + + writer.visitEnd(); + return writer.toByteArray(); + } + + /** A jar with {@code mod.toml} (unless {@code null}) and {@code classes} (internal name to bytes). */ + private Path jar(String name, @Nullable String toml, Map classes) throws IOException + { + Path jar = this.directory.resolve(name); + + try (OutputStream file = Files.newOutputStream(jar); JarOutputStream out = new JarOutputStream(file)) + { + if (toml != null) { + out.putNextEntry(new JarEntry("META-INF/zomboidforge/mod.toml")); + out.write(toml.getBytes(StandardCharsets.UTF_8)); + out.closeEntry(); + } + + for (Map.Entry entry : classes.entrySet()) { + out.putNextEntry(new JarEntry(entry.getKey() + ".class")); + out.write(entry.getValue()); + out.closeEntry(); + } + } + + return jar; + } +} diff --git a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java index 46c67a1..b033515 100644 --- a/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java +++ b/patcher/src/main/java/dev/overlord/zomboidforge/patcher/JarPatcher.java @@ -8,6 +8,7 @@ import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import java.io.IOException; +import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; @@ -161,7 +162,7 @@ public final class JarPatcher { ZipEntry entry = entries.nextElement(); List patches = patchesByEntry.get(entry.getName()); - byte[] bytes = jar.getInputStream(entry).readAllBytes(); + byte[] bytes = JarPatcher.read(jar, entry); if (patches != null) { bytes = transform(jar, bytes, patches); @@ -227,7 +228,12 @@ public final class JarPatcher ZipEntry entry = jar.getEntry(entryName); if (entry == null) return null; - try { return jar.getInputStream(entry).readAllBytes(); } + try { return JarPatcher.read(jar, entry); } catch (IOException e) { throw new UncheckedIOException(e); } } + + private static byte[] read(ZipFile jar, ZipEntry entry) throws IOException + { + try (InputStream in = jar.getInputStream(entry)) { return in.readAllBytes(); } + } }