Merge branch 'release/v0.1.0-SNAPSHOT'
ci / image (42.21, public) (push) Successful in 13s

This commit is contained in:
Overlord committed 2026-09-30 16:38:18 +02:00
commit 484a253732
44 files changed
+2364 -55

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
*
!gradlew
!gradle/
!gradle.properties
!settings.gradle.kts
!build-logic/
!api/
!core/
!compat/
!agent/
!patcher/
!docker/
**/build/
**/.gradle/
+29
View File
@@ -0,0 +1,29 @@
# Builds and verifies the image for every supported Project Zomboid version.
# Requires a runner with a Docker (or Podman) CLI and access to its daemon.
name: ci
on:
push:
pull_request:
jobs:
image:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
# One entry per supported version; add older Steam version branches
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
- pz_version: "42.21"
steam_branch: public
steps:
- uses: actions/checkout@v4
- name: Build and verify
env:
IMAGE: zomboidforge-ci
PZ_VERSION: ${{ matrix.pz_version }}
PZ_BRANCH: ${{ matrix.steam_branch }}
PUBLISH: "false"
run: ci/release.sh
+38
View File
@@ -0,0 +1,38 @@
# Publishes an image for every new Steam build of each supported Project Zomboid
# version. Immutable tags are never overwritten (see ci/release.sh).
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
# package write access) and a runner with a Docker (or Podman) CLI.
name: release
on:
schedule:
- cron: "0 */6 * * *"
workflow_dispatch:
jobs:
image:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- pz_version: "42.21"
steam_branch: public
latest: "true"
steps:
- uses: actions/checkout@v4
- name: Log in to the registry
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: echo "${REGISTRY_TOKEN}" | docker login git.security-command.org --username "${REGISTRY_USER}" --password-stdin
- name: Build and publish
env:
IMAGE: git.security-command.org/overlord/zomboidforge
PZ_VERSION: ${{ matrix.pz_version }}
PZ_BRANCH: ${{ matrix.steam_branch }}
PUBLISH: "true"
LATEST: ${{ matrix.latest }}
run: ci/release.sh
+11 -54
View File
@@ -1,17 +1,14 @@
# ---> Java
# Compiled class file
*.class
*.md
!README.md
lib
.*/
!.gitea/
# Log file
build/
out/
*.class
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
@@ -19,51 +16,11 @@
*.zip
*.tar.gz
*.rar
!gradle/wrapper/gradle-wrapper.jar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> Lua
# Compiled Lua sources
luac.out
# luarocks build files
*.src.rock
*.zip
*.tar.gz
# Object files
*.o
*.os
*.ko
*.obj
*.elf
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
*.def
*.exp
# Shared objects (inc. Windows DLLs)
*.exe
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
.env
+101
View File
@@ -0,0 +1,101 @@
# ZomboidForge dedicated server image (linux/amd64).
#
# steamcmd downloads the vanilla server during the build; the repository
# contains no game files.
#
# podman build --platform linux/amd64 -t zomboidforge .
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
#
# Build arguments:
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
# server reports another one. Default: pz.version in gradle.properties
# STEAMCLIENT bundled (default) or steamcmd: replace the server's steamclient.so
# files with steamcmd's newer copies
# FORGE_VERSION Image label only; set by ci/release.sh
# STEAM_BUILDID Image label only; set by ci/release.sh
ARG PZ_BRANCH=public
ARG PZ_VERSION=""
ARG STEAMCLIENT=bundled
ARG FORGE_VERSION=""
ARG STEAM_BUILDID=""
# --- Stage 1: vanilla dedicated server -----------------------------------------
FROM docker.io/steamcmd/steamcmd:debian-13 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.
RUN steamcmd +quit
ARG PZ_BRANCH
ARG STEAMCLIENT
COPY docker/install-server.sh /usr/local/bin/install-server
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
# --- Stage 2: ZomboidForge build and server jar patching -----------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS build
WORKDIR /src
# Gradle distribution download, cached independently of the sources.
COPY gradlew gradle.properties settings.gradle.kts ./
COPY gradle gradle
RUN ./gradlew --no-daemon --version
COPY build-logic build-logic
COPY api api
COPY core core
COPY compat compat
COPY agent agent
COPY patcher patcher
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
# An empty PZ_VERSION keeps pz.version from gradle.properties.
ARG PZ_VERSION
RUN ./gradlew --no-daemon \
-Ppz.jar=/pz/projectzomboid.jar \
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
build :patcher:patchServerJar
# --- Stage 3: runtime ------------------------------------------------------------
FROM docker.io/library/debian:trixie-slim
# ca-certificates: required by steamclient.so to connect to Steam.
# sqlite3: the entrypoint checks the admin account in the server database.
# Unpinned so the image picks up current Debian security updates.
# hadolint ignore=DL3008
RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
&& rm --recursive --force /var/lib/apt/lists/*
RUN useradd --create-home --uid 1000 pz \
&& mkdir /data \
&& chown pz:pz /data
COPY --from=server /server /opt/pz
COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar
COPY --from=build /src/agent/build/libs/zomboidforge-agent-*.jar /opt/pz/zomboidforge-agent.jar
COPY docker/entrypoint.sh /usr/local/bin/entrypoint
# Steam downloads Workshop items into <install dir>/steamapps/workshop. /opt/pz is
# owned by root, so steamapps points into the data volume, which also keeps the
# downloads across container recreation.
RUN ln --symbolic /data/steamapps /opt/pz/steamapps
ARG PZ_BRANCH
ARG PZ_VERSION
ARG FORGE_VERSION
ARG STEAM_BUILDID
LABEL org.opencontainers.image.title="ZomboidForge" \
org.opencontainers.image.description="Project Zomboid dedicated server with Java mod support." \
org.opencontainers.image.version="${FORGE_VERSION}" \
dev.overlord.zomboidforge.pz-version="${PZ_VERSION}" \
dev.overlord.zomboidforge.steam-branch="${PZ_BRANCH}" \
dev.overlord.zomboidforge.steam-buildid="${STEAM_BUILDID}"
USER 1000:1000
VOLUME /data
# 16261/udp game, 16262/udp direct connect, 27015/tcp RCON
EXPOSE 16261/udp 16262/udp 27015/tcp
ENTRYPOINT ["/usr/local/bin/entrypoint"]
+79 -1
View File
@@ -1,3 +1,81 @@
# ZomboidForge
An official‑client‑compatible, container‑ready Project Zomboid dedicated server with first‑class support for custom Java mods and drop‑in server builds.
An official‑client‑compatible, container‑ready Project Zomboid dedicated server with
first‑class support for custom Java mods and drop‑in server builds.
## Building
The container image downloads the vanilla dedicated server (Steam app 380870) with an
anonymous steamcmd login while it builds, and patches it. No game files are part of this
repository. The build fails when the downloaded server is not the Project Zomboid
version in `gradle.properties` (`pz.version`).
```sh
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
```
| Build argument | Default | |
|---|---|---|
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable),
`<forge>-pz<pz>`, and `latest`.
## Running
```sh
podman run -d --name zomboidforge \
-e ADMIN_PASSWORD=... -e RCON_PASSWORD=... \
-p 16261:16261/udp -p 16262:16262/udp -p 127.0.0.1:27015:27015/tcp \
-v zomboid-data:/data zomboidforge
```
Unset variables keep the value in the server `.ini` (or the game default).
| Variable | Default | |
|---|---|---|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
| `PUBLIC_NAME` | | Name in the server browser |
| `PORT` | `16261` | Game port (`-port`) |
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
| `ADMIN_USERNAME` | `admin` | First start only |
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
| `JVM_MIN_HEAP` | | `-Xms` |
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
| `STEAM` | `1` | `0` runs the server without Steam |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
Notes:
- **Ports:** host and container ports must be the same. The server announces its own
port, so `-p 17000:16261/udp` is unreachable; set `PORT=17000` and publish
`17000:17000/udp` instead.
- **Data:** `/data` holds the server config, saves, database, logs, and downloaded Workshop
items (`/data/steamapps`). The server runs as UID 1000. A bind-mounted host directory
must be writable by UID 1000 (`chown 1000:1000 <dir>`); with rootless Podman, use
`--userns=keep-id:uid=1000,gid=1000` to map it to your own user.
- **Stopping:** `SIGTERM` triggers the game's own save-and-quit. Allow enough time for large
worlds (`podman stop -t 120`, `stop_grace_period` in compose).
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
## Development
Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla
server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz.jar=...`).
```sh
./gradlew build # compile + tests
./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar
```
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
`pz.version` in `gradle.properties` selects the targeted version.
+20
View File
@@ -0,0 +1,20 @@
// Java agent for runtime work (mod loading, live patches). Build-time patches are in :patcher.
plugins {
id("zomboidforge.java-conventions")
}
dependencies {
implementation(project(":api"))
implementation(project(":core"))
implementation(project(projectZomboid.compatProject("runtime")))
compileOnly(files(projectZomboid.serverJar))
}
tasks.jar {
archiveBaseName = "zomboidforge-agent"
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.
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
@@ -0,0 +1,24 @@
package dev.overlord.zomboidforge.agent;
import dev.overlord.zomboidforge.api.ZomboidForge;
import java.lang.instrument.Instrumentation;
public final class ForgeAgent
{
private static Instrumentation instrumentation;
private ForgeAgent() {}
/** Runs before {@code zombie.network.GameServer.main}; Project Zomboid's logging is not initialized yet. */
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
System.out.println("[ZomboidForge] Agent " + ZomboidForge.VERSION + " loaded.");
}
public static Instrumentation instrumentation() {
if (instrumentation == null) throw new IllegalStateException("ZomboidForge agent was not loaded via -javaagent");
return instrumentation;
}
}
+5
View File
@@ -0,0 +1,5 @@
// API for custom Java mods. Version-independent: no references to game classes.
plugins {
id("zomboidforge.java-conventions")
}
@@ -0,0 +1,13 @@
package dev.overlord.zomboidforge.api;
import java.util.Objects;
public final class ZomboidForge
{
/** Build version, from the manifest of the jar these classes were loaded from. */
public static final String VERSION = Objects.requireNonNullElse(
ZomboidForge.class.getPackage().getImplementationVersion(), "dev"
);
private ZomboidForge() {}
}
+3
View File
@@ -0,0 +1,3 @@
plugins {
`kotlin-dsl`
}
+7
View File
@@ -0,0 +1,7 @@
rootProject.name = "build-logic"
dependencyResolutionManagement {
repositories {
gradlePluginPortal()
}
}
@@ -0,0 +1,13 @@
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
abstract class ProjectZomboidExtension {
/** Vanilla dedicated server projectzomboid.jar. Not bundled or published. */
abstract val serverJar: RegularFileProperty
/** Targeted Project Zomboid version, e.g. "42.21" (gradle property pz.version). */
abstract val version: Property<String>
/** Path of a compat module of the targeted Build, e.g. ":compat:b42:runtime". */
fun compatProject(module: String): String = ":compat:b${version.get().substringBefore('.')}:$module"
}
@@ -0,0 +1,39 @@
plugins {
java
}
val projectZomboid = extensions.create<ProjectZomboidExtension>("projectZomboid")
projectZomboid.serverJar.convention(
layout.settingsDirectory.file(
providers.gradleProperty("pz.jar").orElse("lib/server/java/projectzomboid.jar")
)
)
projectZomboid.version.convention(providers.gradleProperty("pz.version"))
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
dependencies {
"compileOnly"(libs.findLibrary("jetbrains-annotations").get())
"testCompileOnly"(libs.findLibrary("jetbrains-annotations").get())
}
java {
// Project Zomboid ships and runs on Java 25 (bundled Zulu jre64; class version 69).
toolchain.languageVersion = JavaLanguageVersion.of(25)
}
tasks.withType<JavaCompile>().configureEach {
options.release = 25
options.encoding = "UTF-8"
options.compilerArgs.addAll(listOf("-Xlint:all", "-Xlint:-options", "-Xlint:-path"))
}
tasks.withType<Jar>().configureEach {
manifest.attributes(
"Implementation-Title" to "ZomboidForge",
"Implementation-Version" to project.version,
)
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
Executable
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env bash
#
# Builds the ZomboidForge image for one Project Zomboid version and optionally
# publishes it. Published tags:
#
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten
# <forge>-pz<pz> moves to the newest Steam build of that version
# latest only with LATEST=true
#
# Nothing is built when the immutable tag already exists in the registry.
#
# Environment:
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
# PZ_BRANCH Steam branch. Default: public
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
# PUBLISH true: push the tags. Default: false (build and verify only)
# LATEST true: also push "latest". Default: false
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
set -o errexit
set -o nounset
set -o pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly REPO_ROOT
readonly IMAGE="${IMAGE:?IMAGE is required}"
readonly PZ_BRANCH="${PZ_BRANCH:-public}"
readonly PUBLISH="${PUBLISH:-false}"
readonly LATEST="${LATEST:-false}"
log() {
echo "[release] $*" >&2
}
container_engine() {
if [[ -n "${CONTAINER_ENGINE:-}" ]]; then
echo "${CONTAINER_ENGINE}"
elif command -v docker > /dev/null; then
echo "docker"
else
echo "podman"
fi
}
# Prints the value of <key>=<value> in gradle.properties.
gradle_property() {
local key="$1"
local line
while IFS= read -r line; do
if [[ "${line}" == "${key}="* ]]; then
echo "${line#*=}"
return
fi
done < "${REPO_ROOT}/gradle.properties"
log "${key} not found in gradle.properties"
exit 1
}
image_exists() {
local reference="$1"
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
}
build_image() {
local reference="$1"
local forge_version="$2"
local pz_version="$3"
local build_id="$4"
"$(container_engine)" build \
--platform linux/amd64 \
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
--build-arg "PZ_VERSION=${pz_version}" \
--build-arg "FORGE_VERSION=${forge_version}" \
--build-arg "STEAM_BUILDID=${build_id}" \
--tag "${reference}" \
"${REPO_ROOT}"
}
# Steam can publish a new build between the build ID lookup and the download.
verify_build_id() {
local reference="$1"
local expected="$2"
local actual
actual="$("$(container_engine)" run --rm --entrypoint cat "${reference}" /opt/pz/steam-buildid)"
if [[ "${actual}" != "${expected}" ]]; then
log "Image contains Steam build ${actual}, expected ${expected}; Steam updated during the build."
exit 1
fi
}
push_as() {
local source="$1"
local target="$2"
"$(container_engine)" tag "${source}" "${target}"
"$(container_engine)" push "${target}"
log "Pushed ${target}"
}
main() {
local forge_version
local pz_version
local build_id
forge_version="$(gradle_property version)"
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}"
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
if [[ "${PUBLISH}" == true ]] && image_exists "${immutable_tag}"; then
log "${immutable_tag} is already published; nothing to do."
return
fi
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
verify_build_id "${immutable_tag}" "${build_id}"
if [[ "${PUBLISH}" != true ]]; then
log "Built ${immutable_tag} (PUBLISH is not true; nothing pushed)"
return
fi
"$(container_engine)" push "${immutable_tag}"
log "Pushed ${immutable_tag}"
push_as "${immutable_tag}" "${version_tag}"
if [[ "${LATEST}" == true ]]; then
push_as "${immutable_tag}" "${IMAGE}:latest"
fi
}
main
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
#
# Prints the current Steam build ID of a branch of the Project Zomboid
# dedicated server (app 380870), using steamcmd in a container.
#
# Usage: steam-buildid.sh <branch>
# <branch> Steam branch: public, unstable, or a version branch such as 42.19
#
# Environment:
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
set -o errexit
set -o nounset
set -o pipefail
readonly APP_ID="380870"
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13"
readonly BRANCH="$1"
log() {
echo "[steam-buildid] $*" >&2
}
container_engine() {
if [[ -n "${CONTAINER_ENGINE:-}" ]]; then
echo "${CONTAINER_ENGINE}"
elif command -v docker > /dev/null; then
echo "docker"
else
echo "podman"
fi
}
# Prints app_info for the app. The output is Valve KeyValues text; the
# "branches" section contains one block per branch with its "buildid".
print_app_info() {
"$(container_engine)" run --rm "${STEAMCMD_IMAGE}" \
+login anonymous \
+app_info_update 1 \
+app_info_print "${APP_ID}" \
+quit
}
# Reads the buildid of the branch block inside the "branches" section.
extract_build_id() {
awk -v branch="\"${BRANCH}\"" '
$1 == "\"branches\"" { in_branches = 1; next }
in_branches && $1 == branch { in_branch = 1; next }
in_branch && $1 == "\"buildid\"" { gsub(/"/, "", $2); print $2; exit }
in_branch && $1 == "}" { exit }
'
}
main() {
local app_info
local build_id
# Captured first: extract_build_id stops reading early, which would end
# print_app_info with SIGPIPE inside a pipeline.
app_info="$(print_app_info)"
build_id="$(extract_build_id <<< "${app_info}")"
if [[ -z "${build_id}" ]]; then
log "No build ID found for branch '${BRANCH}' of app ${APP_ID}"
exit 1
fi
echo "${build_id}"
}
main
+10
View File
@@ -0,0 +1,10 @@
// Build-time patches for Project Zomboid Build 42.
plugins {
id("zomboidforge.java-conventions")
}
dependencies {
implementation(project(":patcher"))
implementation(libs.bundles.asm)
}
@@ -0,0 +1,21 @@
package dev.overlord.zomboidforge.compat.b42.patches;
import dev.overlord.zomboidforge.patcher.ClassPatch;
import dev.overlord.zomboidforge.patcher.PatchSet;
import java.util.List;
/** Every build-time patch for Build 42, in application order. */
public final class B42PatchSet implements PatchSet {
private static final List<ClassPatch> PATCHES = List.of();
@Override
public int build() {
return 42;
}
@Override
public List<ClassPatch> patches() {
return PATCHES;
}
}
@@ -0,0 +1 @@
dev.overlord.zomboidforge.compat.b42.patches.B42PatchSet
+12
View File
@@ -0,0 +1,12 @@
// Runtime code for Project Zomboid Build 42: hooks called by patched game code, and
// adapters between game classes and the version-independent core and api.
plugins {
id("zomboidforge.java-conventions")
}
dependencies {
implementation(project(":core"))
implementation(project(":api"))
compileOnly(files(projectZomboid.serverJar))
}
@@ -0,0 +1,5 @@
/**
* Build 42 runtime code: hooks that patched game classes call, and adapters between
* game classes and the version-independent {@code core} and {@code api}.
*/
package dev.overlord.zomboidforge.compat.b42;
+35
View File
@@ -0,0 +1,35 @@
# Local test setup: `podman compose up --build`. Settings are read from the
# environment or from .env (gitignored); docker/entrypoint.sh lists all variables.
services:
zomboidforge:
build: .
image: localhost/zomboidforge:dev
platform: linux/amd64
environment:
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest}
SERVER_PASSWORD: ${SERVER_PASSWORD:-}
PUBLIC: ${PUBLIC:-}
PUBLIC_NAME: ${PUBLIC_NAME:-}
PORT: ${PORT:-16261}
UDP_PORT: ${UDP_PORT:-16262}
ADMIN_USERNAME: ${ADMIN_USERNAME:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
SERVER_PRESET: ${SERVER_PRESET:-}
MODS: ${MODS:-}
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
RCON_PASSWORD: ${RCON_PASSWORD:-}
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g}
ports:
# Host and container ports must be equal: the server reports its own port
# to Steam and to clients, so a remapped port is unreachable.
- "${PORT:-16261}:${PORT:-16261}/udp"
- "${UDP_PORT:-16262}:${UDP_PORT:-16262}/udp"
- "127.0.0.1:27015:27015/tcp"
volumes:
- zomboid-data:/data
# SIGTERM runs GameServer's shutdown hook, which queues a save-and-quit.
stop_grace_period: 2m
volumes:
zomboid-data:
+9
View File
@@ -0,0 +1,9 @@
// Version-independent runtime: mod loading, events, configuration. No game references.
plugins {
id("zomboidforge.java-conventions")
}
dependencies {
implementation(project(":api"))
}
@@ -0,0 +1,5 @@
/**
* Version-independent runtime: mod loading, events, configuration. Contains no
* references to game classes; game-specific code is in the compat modules.
*/
package dev.overlord.zomboidforge.core;
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env bash
#
# Container entrypoint: starts the patched Project Zomboid dedicated server
# with the ZomboidForge agent. Arguments are passed through to
# zombie.network.GameServer.
#
# Environment variables (unset or empty keep the value in the server .ini, or the game default):
#
# Server
# SERVER_NAME Server config name (/data/Server/<name>.ini). Default: zomboidforge
# SERVER_PASSWORD Password clients need to join (.ini Password)
# PUBLIC true/false: listed in the in-game server browser (.ini Public)
# PUBLIC_NAME Name in the server browser (.ini PublicName)
# PORT Game port (-port). Default: 16261
# UDP_PORT Direct connection port (-udpport). Default: 16262
# STEAM 1 = Steam mode (required for official Steam clients), 0 = no Steam. Default: 1
#
# Admin account
# ADMIN_USERNAME Admin account name (-adminusername), passed on every start.
# Project Zomboid creates the account when it does not exist. Default: admin
# ADMIN_PASSWORD Password for creating that account (-adminpassword). Required while
# the account does not exist; not passed once it does.
#
# New server
# SERVER_PRESET Sandbox preset from media/lua/shared/Sandbox (e.g. Apocalypse),
# copied to <name>_SandboxVars.lua when that file does not exist
#
# Mods
# MODS Semicolon-separated mod IDs (.ini Mods). Build 42 format: \ModA;\ModB
# WORKSHOP_ITEMS Semicolon-separated Workshop item IDs (.ini WorkshopItems)
#
# RCON
# RCON_PASSWORD Written into the .ini before every start. RCON is disabled when empty.
#
# JVM
# JVM_MIN_HEAP Value for -Xms. Default: JVM default
# JVM_MAX_HEAP Value for -Xmx. Default: 8g (the vanilla ProjectZomboid64.json value)
#
# Maintenance
# SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset).
# Intended for a single start; unset it afterwards.
set -o errexit
set -o nounset
set -o pipefail
readonly INSTALL_DIR="/opt/pz"
readonly DATA_DIR="/data"
readonly AGENT_JAR="${INSTALL_DIR}/zomboidforge-agent.jar"
readonly JAVA="${INSTALL_DIR}/jre64/bin/java"
readonly SANDBOX_PRESET_DIR="${INSTALL_DIR}/media/lua/shared/Sandbox"
readonly SERVER_NAME="${SERVER_NAME:-zomboidforge}"
readonly SERVER_PASSWORD="${SERVER_PASSWORD:-}"
readonly PUBLIC="${PUBLIC:-}"
readonly PUBLIC_NAME="${PUBLIC_NAME:-}"
readonly PORT="${PORT:-}"
readonly UDP_PORT="${UDP_PORT:-}"
readonly STEAM="${STEAM:-1}"
readonly ADMIN_USERNAME="${ADMIN_USERNAME:-}"
readonly ADMIN_PASSWORD="${ADMIN_PASSWORD:-}"
readonly SERVER_PRESET="${SERVER_PRESET:-}"
readonly MODS="${MODS:-}"
readonly WORKSHOP_ITEMS="${WORKSHOP_ITEMS:-}"
readonly RCON_PASSWORD="${RCON_PASSWORD:-}"
readonly JVM_MIN_HEAP="${JVM_MIN_HEAP:-}"
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-8g}"
readonly SOFT_RESET="${SOFT_RESET:-}"
readonly SERVER_INI="${DATA_DIR}/Server/${SERVER_NAME}.ini"
readonly SERVER_SANDBOX_VARS="${DATA_DIR}/Server/${SERVER_NAME}_SandboxVars.lua"
readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db"
# Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there.
readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps"
log() {
echo "[entrypoint] $*" >&2
}
fail() {
log "$*"
exit 1
}
# True for 1/true/yes, case-insensitive.
is_true() {
local value="${1,,}"
[[ "${value}" == "1" || "${value}" == "true" || "${value}" == "yes" ]]
}
# True for 0/false/no, case-insensitive.
is_false() {
local value="${1,,}"
[[ "${value}" == "0" || "${value}" == "false" || "${value}" == "no" ]]
}
# Same lookup as ServerWorldDatabase.create(), which prompts on stdin for a
# password when the admin account does not exist and no -adminpassword is given.
admin_account_exists() {
local username="${ADMIN_USERNAME:-admin}"
local escaped_username="${username//\'/\'\'}"
local account_id
if [[ ! -f "${SERVER_DB}" ]]; then
return 1
fi
account_id="$(sqlite3 -readonly "${SERVER_DB}" \
"SELECT id FROM whitelist WHERE username = '${escaped_username}';")"
[[ -n "${account_id}" ]]
}
# Sets <key>=<value> in the server .ini. Creates the file or the key if missing.
# Project Zomboid reads a partial .ini and writes the missing defaults on start.
set_ini_value() {
local key="$1"
local value="$2"
local temp_file="${SERVER_INI}.tmp"
local key_found=false
local line
mkdir --parents "$(dirname "${SERVER_INI}")"
: > "${temp_file}"
if [[ -f "${SERVER_INI}" ]]; then
while IFS= read -r line || [[ -n "${line}" ]]; do
if [[ "${line}" == "${key}="* ]]; then
printf '%s=%s\n' "${key}" "${value}" >> "${temp_file}"
key_found=true
else
printf '%s\n' "${line}" >> "${temp_file}"
fi
done < "${SERVER_INI}"
fi
if [[ "${key_found}" == false ]]; then
printf '%s=%s\n' "${key}" "${value}" >> "${temp_file}"
fi
mv "${temp_file}" "${SERVER_INI}"
}
# Sets <key>=<value> only when <value> is not empty.
set_ini_value_if_given() {
local key="$1"
local value="$2"
if [[ -n "${value}" ]]; then
set_ini_value "${key}" "${value}"
fi
}
apply_ini_settings() {
set_ini_value_if_given "Password" "${SERVER_PASSWORD}"
set_ini_value_if_given "PublicName" "${PUBLIC_NAME}"
set_ini_value_if_given "Mods" "${MODS}"
set_ini_value_if_given "WorkshopItems" "${WORKSHOP_ITEMS}"
if [[ -n "${PUBLIC}" ]]; then
if is_true "${PUBLIC}"; then
set_ini_value "Public" "true"
elif is_false "${PUBLIC}"; then
set_ini_value "Public" "false"
else
fail "PUBLIC must be true or false, got '${PUBLIC}'."
fi
fi
if [[ -n "${RCON_PASSWORD}" ]]; then
set_ini_value "RCONPassword" "${RCON_PASSWORD}"
else
log "RCON_PASSWORD is not set; RCON stays disabled unless the .ini sets RCONPassword."
fi
}
# Preset names, without SandboxVars.lua (which only references a preset).
list_sandbox_presets() {
local file
local names=()
for file in "${SANDBOX_PRESET_DIR}"/*.lua; do
file="$(basename "${file}" .lua)"
if [[ "${file}" != "SandboxVars" ]]; then
names+=("${file}")
fi
done
echo "${names[*]}"
}
# Presets start with "return {" and use CRLF line endings; the server's
# <name>_SandboxVars.lua starts with "SandboxVars = {".
install_sandbox_preset() {
local preset_file="${SANDBOX_PRESET_DIR}/${SERVER_PRESET}.lua"
local first_line=true
local line
if [[ -z "${SERVER_PRESET}" || -f "${SERVER_SANDBOX_VARS}" ]]; then
return
fi
if [[ "${SERVER_PRESET}" == "SandboxVars" || ! -f "${preset_file}" ]]; then
fail "Unknown SERVER_PRESET '${SERVER_PRESET}'. Available: $(list_sandbox_presets)"
fi
log "Creating ${SERVER_SANDBOX_VARS} from preset ${SERVER_PRESET}"
mkdir --parents "$(dirname "${SERVER_SANDBOX_VARS}")"
while IFS= read -r line || [[ -n "${line}" ]]; do
line="${line%$'\r'}"
if [[ "${first_line}" == true ]]; then
if [[ "${line}" != "return {" ]]; then
fail "Unexpected first line in ${preset_file}: '${line}'"
fi
line="SandboxVars = {"
first_line=false
fi
printf '%s\n' "${line}"
done < "${preset_file}" > "${SERVER_SANDBOX_VARS}"
}
# Sets needs_admin_password, used by build_server_args.
check_admin_account() {
if admin_account_exists; then
needs_admin_password=false
if [[ -n "${ADMIN_PASSWORD}" ]]; then
log "ADMIN_PASSWORD is ignored: the admin account '${ADMIN_USERNAME:-admin}' already exists."
fi
else
needs_admin_password=true
if [[ -z "${ADMIN_PASSWORD}" ]]; then
fail "The admin account '${ADMIN_USERNAME:-admin}' of '${SERVER_NAME}' does not exist yet: ADMIN_PASSWORD is required to create it."
fi
fi
}
# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh.
# Java runs directly instead of through the native ProjectZomboid64 launcher.
build_jvm_args() {
jvm_args=(
"-javaagent:${AGENT_JAR}"
"-Djava.awt.headless=true"
"--enable-native-access=ALL-UNNAMED"
"-Xmx${JVM_MAX_HEAP}"
"-XX:+UseZGC"
"-XX:-OmitStackTraceInFastThrow"
"-Dzomboid.steam=${STEAM}"
"-Dzomboid.znetlog=1"
"-Djava.library.path=linux64/"
"-Djava.security.egd=file:/dev/urandom"
"-cp" "java/:java/projectzomboid.jar"
)
if [[ -n "${JVM_MIN_HEAP}" ]]; then
jvm_args+=("-Xms${JVM_MIN_HEAP}")
fi
if [[ -n "${SOFT_RESET}" ]] && is_true "${SOFT_RESET}"; then
log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start."
jvm_args+=("-Dsoftreset")
fi
}
build_server_args() {
server_args=(
"-cachedir=${DATA_DIR}"
"-servername" "${SERVER_NAME}"
)
if [[ -n "${PORT}" ]]; then
server_args+=("-port" "${PORT}")
fi
if [[ -n "${UDP_PORT}" ]]; then
server_args+=("-udpport" "${UDP_PORT}")
fi
if [[ -n "${ADMIN_USERNAME}" ]]; then
server_args+=("-adminusername" "${ADMIN_USERNAME}")
fi
# Only while the account does not exist: the value is visible in the process arguments.
if [[ "${needs_admin_password}" == true ]]; then
server_args+=("-adminpassword" "${ADMIN_PASSWORD}")
fi
}
main() {
mkdir --parents "${STEAMAPPS_DIR}"
local needs_admin_password
check_admin_account
apply_ini_settings
install_sandbox_preset
local jvm_args
local server_args
build_jvm_args
build_server_args
# Native libraries: game (linux64/), Steam (install root), JVM (jre64/lib).
# libjsig.so chains signal handlers between the JVM and native libraries.
export LD_LIBRARY_PATH="${INSTALL_DIR}/linux64:${INSTALL_DIR}:${INSTALL_DIR}/jre64/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
export LD_PRELOAD="libjsig.so${LD_PRELOAD:+:${LD_PRELOAD}}"
cd "${INSTALL_DIR}"
exec "${JAVA}" "${jvm_args[@]}" zombie.network.GameServer "${server_args[@]}" "$@"
}
main "$@"
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env bash
#
# Installs the vanilla Project Zomboid dedicated server (Steam app 380870)
# with steamcmd, using an anonymous login. Runs in the steamcmd image during
# the Docker build.
#
# Usage: install-server.sh <install-dir> <branch> <steamclient>
# <branch> Steam branch: "public" (default branch), "unstable", or a
# version branch such as "42.19".
# <steamclient> "bundled" keeps the steamclient.so files shipped with the
# server; "steamcmd" replaces them with steamcmd's own, newer
# copies (a known workaround for failing Workshop downloads).
#
# Writes the installed Steam build ID to <install-dir>/steam-buildid.
set -o errexit
set -o nounset
set -o pipefail
readonly APP_ID="380870"
readonly MAX_ATTEMPTS=3
readonly STEAMCMD_DIR="${HOME}/.local/share/Steam/steamcmd"
readonly INSTALL_DIR="$1"
readonly BRANCH="$2"
readonly STEAMCLIENT="$3"
log() {
echo "[install-server] $*" >&2
}
install_app() {
local branch_args=()
if [[ "${BRANCH}" != "public" ]]; then
branch_args=("-beta" "${BRANCH}")
fi
# app_update can fail with "Missing configuration" right after steamcmd
# updated itself; a repeated attempt succeeds.
local attempt
for (( attempt = 1; attempt <= MAX_ATTEMPTS; attempt++ )); do
log "Installing app ${APP_ID} (branch ${BRANCH}), attempt ${attempt}/${MAX_ATTEMPTS}"
if steamcmd \
+force_install_dir "${INSTALL_DIR}" \
+login anonymous \
+app_update "${APP_ID}" "${branch_args[@]}" validate \
+quit
then
break
fi
log "steamcmd failed on attempt ${attempt}"
done
if [[ ! -f "${INSTALL_DIR}/java/projectzomboid.jar" ]]; then
log "Installation failed: ${INSTALL_DIR}/java/projectzomboid.jar not found"
exit 1
fi
}
# Copies the build ID from Steam's app manifest, which is removed afterwards.
record_build_id() {
local manifest="${INSTALL_DIR}/steamapps/appmanifest_${APP_ID}.acf"
local build_id
build_id="$(grep --max-count=1 '"buildid"' "${manifest}" | tr --delete --complement '0-9')"
if [[ -z "${build_id}" ]]; then
log "No buildid found in ${manifest}"
exit 1
fi
echo "${build_id}" > "${INSTALL_DIR}/steam-buildid"
log "Installed Steam build ${build_id}"
}
# The install root holds the 32-bit steamclient.so, linux64/ the 64-bit one.
replace_steamclient() {
case "${STEAMCLIENT}" in
bundled)
;;
steamcmd)
log "Replacing the bundled steamclient.so files with steamcmd's"
cp "${STEAMCMD_DIR}/linux32/steamclient.so" "${INSTALL_DIR}/steamclient.so"
cp "${STEAMCMD_DIR}/linux64/steamclient.so" "${INSTALL_DIR}/linux64/steamclient.so"
;;
*)
log "Unknown steamclient option '${STEAMCLIENT}' (expected: bundled, steamcmd)"
exit 1
;;
esac
}
main() {
install_app
record_build_id
replace_steamclient
# Steam's install metadata; not needed at runtime.
rm --recursive --force "${INSTALL_DIR}/steamapps"
}
main
+15
View File
@@ -0,0 +1,15 @@
group=dev.overlord.zomboidforge
version=0.1.0-SNAPSHOT
# Project Zomboid version the build targets. Selects compat/b<major>/, and
# :patcher:patchServerJar fails when the server jar reports another version.
# "42.21" matches every 42.21.x build; "42.21.0" matches exactly.
pz.version=42.21
# Vanilla dedicated server jar used for compilation and patching.
# Default: lib/server/java/projectzomboid.jar (relative to the root project).
# The Docker build sets -Ppz.jar.
#pz.jar=
org.gradle.configuration-cache=true
org.gradle.parallel=true
+18
View File
@@ -0,0 +1,18 @@
[versions]
asm = "9.10.1"
junit = "6.1.3"
jetbrains-annotations = "26.0.2"
[libraries]
#noinspection UnusedVersionCatalogEntry
jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" }
asm = { module = "org.ow2.asm:asm", version.ref = "asm" }
asm-tree = { module = "org.ow2.asm:asm-tree", version.ref = "asm" }
asm-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" }
asm-util = { module = "org.ow2.asm:asm-util", version.ref = "asm" }
junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" }
junit-platform-launcher = { module = "org.junit.platform:junit-platform-launcher" }
[bundles]
asm = ["asm", "asm-tree", "asm-commons", "asm-util"]
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/<unknown>/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+55
View File
@@ -0,0 +1,55 @@
// Build-time patching engine. The patches themselves are in compat/b<major>/patches.
plugins {
id("zomboidforge.java-conventions")
}
// Patch set of the targeted Build; only on the class path of patchServerJar.
val serverPatches = configurations.create("serverPatches") {
isCanBeConsumed = false
isCanBeResolved = true
}
dependencies {
implementation(libs.bundles.asm)
serverPatches(project(projectZomboid.compatProject("patches")))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testRuntimeOnly(libs.junit.platform.launcher)
}
tasks.test {
// Enables GameVersionReaderTest.readsTargetedVersionFromServerJar when the jar exists.
val serverJar = projectZomboid.serverJar
val targetedVersion = projectZomboid.version
inputs.property("pzVersion", targetedVersion)
jvmArgumentProviders.add(CommandLineArgumentProvider {
listOf(
"-Dpz.jar=${serverJar.get().asFile.absolutePath}",
"-Dpz.version=${targetedVersion.get()}",
)
})
}
tasks.register<JavaExec>("patchServerJar") {
description = "Applies the targeted Build's patches to the vanilla server jar."
group = "build"
val vanillaJar = projectZomboid.serverJar
val patchedJar = layout.buildDirectory.file("server/projectzomboid.jar")
val expectedVersion = projectZomboid.version
inputs.file(vanillaJar).withPropertyName("vanillaJar")
inputs.property("expectedVersion", expectedVersion)
outputs.file(patchedJar).withPropertyName("patchedJar")
classpath = sourceSets.main.get().runtimeClasspath + serverPatches
mainClass = "dev.overlord.zomboidforge.patcher.JarPatcher"
argumentProviders.add(CommandLineArgumentProvider {
listOf(
vanillaJar.get().asFile.absolutePath,
patchedJar.get().asFile.absolutePath,
expectedVersion.get(),
)
})
}
@@ -0,0 +1,22 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.tree.ClassNode;
/** A build-time change to one class of the vanilla server jar. */
public interface ClassPatch {
/** Internal name of the class to patch, e.g. {@code zombie/network/GameServer}. */
String target();
/**
* Whether the patch applies to the given game version. Patches that differ
* between minor versions of the same Build provide one implementation per
* version range. Default: every version.
*/
default boolean appliesTo(GameVersion version) { return true; }
/**
* Modifies {@code node} in place. Throws if the class does not match what the
* patch expects (e.g. after a Project Zomboid update).
*/
void apply(ClassNode node);
}
@@ -0,0 +1,72 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Project Zomboid version, e.g. 42.21.0 (Core.getGameAndBuildVersion()). */
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
{
private static final Pattern FORMAT = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?");
private static final Comparator<GameVersion> ORDER = Comparator
.comparingInt(GameVersion::major)
.thenComparingInt(GameVersion::minor)
.thenComparingInt(GameVersion::build);
//
/** Parses "42.21.0", or "42.21" as 42.21.0. */
public static GameVersion parse(String text)
{
Matcher matcher = FORMAT.matcher(text.trim());
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: " + text);
int build = matcher.group(3) == null
? 0
: Integer.parseInt(matcher.group(3));
return new GameVersion(
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
build
);
}
/**
* Whether this version satisfies an expected version: "42.21" matches every
* 42.21.x build, "42.21.0" matches only 42.21.0.
*/
public boolean matches(String expected)
{
GameVersion other = parse(expected);
boolean buildGiven = expected.trim().chars().filter(c -> c == '.').count() == 2;
return
major == other.major &&
minor == other.minor &&
(!buildGiven || build == other.build);
}
//
public boolean isAtLeast(int major, int minor) {
return compareTo(new GameVersion(major, minor, 0)) >= 0;
}
public boolean isBefore(int major, int minor) {
return compareTo(new GameVersion(major, minor, 0)) < 0;
}
@Override
public int compareTo(@NotNull GameVersion other) {
return ORDER.compare(this, other);
}
@Override
public @NotNull String toString() {
return major + "." + minor + "." + build;
}
}
@@ -0,0 +1,94 @@
package dev.overlord.zomboidforge.patcher;
import org.jetbrains.annotations.Contract;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.util.ArrayList;
import java.util.List;
/**
* Reads the game version from the bytes of zombie/core/Core.class.
*
* <p>Core's static initializer contains {@code gameVersion = new GameVersion(major, minor, "")},
* and {@code buildVersion} is a compile-time constant; together they form
* Core.getGameAndBuildVersion().
*/
public final class GameVersionReader
{
public static final String CORE_CLASS = "zombie/core/Core";
private static final String GAME_VERSION_CLASS = "zombie/core/GameVersion";
private static final String GAME_VERSION_FIELD = "gameVersion";
private static final String BUILD_VERSION_FIELD = "buildVersion";
private GameVersionReader() {}
public static GameVersion read(byte[] coreClass)
{
ClassNode core = new ClassNode();
new ClassReader(coreClass).accept(core, 0);
MethodNode staticInitializer = core.methods.stream()
.filter(m -> m.name.equals("<clinit>"))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Core has no static initializer."));
int[] majorMinor = readGameVersionConstructorArguments(staticInitializer);
return new GameVersion(majorMinor[0], majorMinor[1], readBuildVersion(core));
}
/** Finds the two int constants passed to the GameVersion constructor stored in Core.gameVersion. */
private static int[] readGameVersionConstructorArguments(MethodNode staticInitializer)
{
List<Integer> intConstants = new ArrayList<>();
for (AbstractInsnNode insn : staticInitializer.instructions)
{
if (insn.getOpcode() == Opcodes.NEW) intConstants.clear();
Integer constant = intConstant(insn);
if (constant != null) intConstants.add(constant);
if
(
insn instanceof MethodInsnNode call
&& call.owner.equals(GAME_VERSION_CLASS)
&& call.name.equals("<init>")
&& isGameVersionStore(call.getNext())
&& intConstants.size() == 2
)
{ return new int[]{intConstants.get(0), intConstants.get(1)}; }
}
throw new IllegalStateException("Core.gameVersion initialization not found.");
}
private static boolean isGameVersionStore(AbstractInsnNode insn) {
return insn instanceof FieldInsnNode field
&& field.getOpcode() == Opcodes.PUTSTATIC
&& field.name.equals(GAME_VERSION_FIELD);
}
private static int readBuildVersion(ClassNode core) {
return core.fields.stream()
.filter(f -> f.name.equals(BUILD_VERSION_FIELD) && f.value instanceof Integer)
.map(f -> (Integer) f.value)
.findFirst()
.orElseThrow(() -> new IllegalStateException("Core.buildVersion constant not found."));
}
private static Integer intConstant(AbstractInsnNode insn)
{
int opcode = insn.getOpcode();
if (opcode >= Opcodes.ICONST_M1 && opcode <= Opcodes.ICONST_5) return opcode - Opcodes.ICONST_0;
if ((opcode == Opcodes.BIPUSH || opcode == Opcodes.SIPUSH) && insn instanceof IntInsnNode push) return push.operand;
return null;
}
}
@@ -0,0 +1,75 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* {@link ClassWriter} that computes frames from class bytes instead of loading
* classes. The game classes are not on the patcher's class path, and loading
* them would run their static initializers.
*/
final class HierarchyClassWriter extends ClassWriter {
private static final String OBJECT = "java/lang/Object";
private record Header(String superName, boolean isInterface) {}
private final Function<String, byte[]> jarClasses;
private final Map<String, Header> headers = new HashMap<>();
/** @param jarClasses bytes of a class in the jar being patched, or {@code null} */
HierarchyClassWriter(Function<String, byte[]> jarClasses) {
super(COMPUTE_FRAMES);
this.jarClasses = jarClasses;
}
@Override
protected String getCommonSuperClass(String type1, String type2)
{
if (header(type1).isInterface() || header(type2).isInterface()) return OBJECT;
Set<String> supers1 = new HashSet<>();
for (String c = type1; c != null; c = header(c).superName()) {
supers1.add(c);
}
for (String c = type2; c != null; c = header(c).superName()) {
if (supers1.contains(c)) {
return c;
}
}
return OBJECT;
}
private Header header(String internalName) {
return headers.computeIfAbsent(internalName, name -> {
ClassReader reader = new ClassReader(bytes(name));
return new Header(reader.getSuperName(), (reader.getAccess() & Opcodes.ACC_INTERFACE) != 0);
});
}
private byte[] bytes(String internalName)
{
byte[] bytes = jarClasses.apply(internalName);
if (bytes != null) return bytes;
// JDK (or other non-jar) class.
try (InputStream in = ClassLoader.getSystemResourceAsStream(internalName + ".class"))
{
if (in == null) throw new IllegalStateException("Class not found while computing frames: '" + internalName + "'.");
return in.readAllBytes();
}
catch (IOException e) { throw new UncheckedIOException(e); }
}
}
@@ -0,0 +1,194 @@
package dev.overlord.zomboidforge.patcher;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Copies a jar, applying {@link ClassPatch}es to their target classes. Every
* other entry is copied through unchanged.
*/
public final class JarPatcher
{
private static final String VERSIONED_PREFIX = "META-INF/versions/";
private final Map<String, List<ClassPatch>> patchesByEntry = new LinkedHashMap<>();
public JarPatcher(Collection<? extends ClassPatch> patches) {
for (ClassPatch patch : patches) {
patchesByEntry.computeIfAbsent(patch.target() + ".class", k -> new ArrayList<>()).add(patch);
}
}
//
/**
* Usage: {@code JarPatcher <vanilla.jar> <patched.jar> <expected-version>}. Loads the
* single {@link PatchSet} on the class path and applies every patch that applies to
* the jar's game version.
*/
static void main(String[] args) throws IOException
{
if (args.length != 3) {
System.err.println("Usage: JarPatcher <vanilla.jar> <patched.jar> <expected-version>");
System.exit(2);
}
Path vanillaJar = Path.of(args[0]);
Path patchedJar = Path.of(args[1]);
String expectedVersion = args[2];
GameVersion version = readGameVersion(vanillaJar);
if (!version.matches(expectedVersion)) {
throw new IllegalStateException(
"Server jar is Project Zomboid " + version +
", but the build targets " + expectedVersion +
" (gradle property pz.version)"
);
}
PatchSet patchSet = loadPatchSet();
List<ClassPatch> applicable = applicablePatches(patchSet, version);
int patchedClasses = new JarPatcher(applicable).patch(vanillaJar, patchedJar);
System.out.println(
"Project Zomboid " + version + ": patched " + patchedClasses + " class(es) with "
+ applicable.size() + " of " + patchSet.patches().size() + " patch(es) -> " + patchedJar
);
}
/** Reads the game version from zombie/core/Core.class in the jar. */
public static GameVersion readGameVersion(Path jar) throws IOException
{
try (ZipFile zip = new ZipFile(jar.toFile()))
{
byte[] core = read(zip, GameVersionReader.CORE_CLASS + ".class");
if (core == null) throw new IllegalStateException("'" + jar + "' contains no " + GameVersionReader.CORE_CLASS + ".class");
return GameVersionReader.read(core);
}
}
/** Patches of {@code patchSet} that apply to {@code version}, in application order. */
public static List<ClassPatch> applicablePatches(PatchSet patchSet, GameVersion version)
{
if (patchSet.build() != version.major()) {
throw new IllegalStateException(
"Patch set is for Build " + patchSet.build()
+ ", but the server jar is Project Zomboid " + version
);
}
return patchSet.patches().stream()
.filter(patch -> patch.appliesTo(version))
.toList();
}
private static PatchSet loadPatchSet()
{
List<PatchSet> patchSets = ServiceLoader.load(PatchSet.class)
.stream()
.map(ServiceLoader.Provider::get)
.toList();
if (patchSets.size() != 1) throw new IllegalStateException("Expected exactly one PatchSet on the class path, found: " + patchSets.size());
return patchSets.getFirst();
}
/** @return the number of classes that were patched */
public int patch(Path in, Path out) throws IOException
{
Path parent = out.toAbsolutePath().getParent();
if (parent != null) Files.createDirectories(parent);
try (
ZipFile jar = new ZipFile(in.toFile());
ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(out))
) {
checkTargets(jar);
int patched = 0;
for (Enumeration<? extends ZipEntry> entries = jar.entries(); entries.hasMoreElements();)
{
ZipEntry entry = entries.nextElement();
List<ClassPatch> patches = patchesByEntry.get(entry.getName());
byte[] bytes = jar.getInputStream(entry).readAllBytes();
if (patches != null) {
bytes = transform(jar, bytes, patches);
patched++;
}
ZipEntry copy = new ZipEntry(entry.getName());
copy.setTime(entry.getTime());
zip.putNextEntry(copy);
zip.write(bytes);
zip.closeEntry();
}
return patched;
}
}
/** Fails if a target is missing or shadowed by an unpatched multi-release override. */
private void checkTargets(ZipFile jar)
{
List<String> problems = new ArrayList<>();
for (String name : patchesByEntry.keySet()) {
if (jar.getEntry(name) == null) {
problems.add("'" + name + "' not found in jar.");
}
}
jar.stream()
.map(ZipEntry::getName)
.filter(n -> n.startsWith(VERSIONED_PREFIX))
.filter(n -> patchesByEntry.containsKey(n.substring(n.indexOf('/', VERSIONED_PREFIX.length()) + 1)))
.forEach(n -> problems.add("'" + n + "' overrides a patched class."));
if (!problems.isEmpty()) {
throw new IllegalStateException("Cannot patch '" + jar.getName() + "':\n " + String.join("\n ", problems));
}
}
private static byte[] transform(ZipFile jar, byte[] bytes, List<ClassPatch> patches)
{
ClassNode node = new ClassNode();
new ClassReader(bytes).accept(node, 0);
for (ClassPatch patch : patches) {
patch.apply(node);
}
HierarchyClassWriter writer = new HierarchyClassWriter(name -> read(jar, name + ".class"));
node.accept(writer);
return writer.toByteArray();
}
private static byte[] read(ZipFile jar, String entryName)
{
ZipEntry entry = jar.getEntry(entryName);
if (entry == null) return null;
try { return jar.getInputStream(entry).readAllBytes(); }
catch (IOException e) { throw new UncheckedIOException(e); }
}
}
@@ -0,0 +1,15 @@
package dev.overlord.zomboidforge.patcher;
import java.util.List;
/**
* All build-time patches of one Project Zomboid Build, provided by a compat module
* (compat/b&lt;major&gt;/patches) through {@link java.util.ServiceLoader}.
*/
public interface PatchSet {
/** Project Zomboid major version (Build) the patches are written for, e.g. 42. */
int build();
/** Patches in application order. */
List<ClassPatch> patches();
}
@@ -0,0 +1,61 @@
package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ApplicablePatchesTest {
private static ClassPatch patch(String name, int sinceMinor) {
return new ClassPatch() {
@Override
public String target() {
return name;
}
@Override
public boolean appliesTo(GameVersion version) {
return version.isAtLeast(42, sinceMinor);
}
@Override
public void apply(ClassNode node) {
}
};
}
private static PatchSet build42(List<ClassPatch> patches) {
return new PatchSet() {
@Override
public int build() {
return 42;
}
@Override
public List<ClassPatch> patches() {
return patches;
}
};
}
@Test
void keepsOrderAndSkipsPatchesForOtherVersions() {
ClassPatch old = patch("t/Old", 0);
ClassPatch fromTwenty = patch("t/New", 20);
ClassPatch fromTwentyTwo = patch("t/Newer", 22);
PatchSet patchSet = build42(List.of(old, fromTwenty, fromTwentyTwo));
assertEquals(List.of(old, fromTwenty), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 21, 0)));
assertEquals(List.of(old), JarPatcher.applicablePatches(patchSet, new GameVersion(42, 19, 2)));
}
@Test
void rejectsPatchSetOfAnotherBuild() {
PatchSet patchSet = build42(List.of());
assertThrows(IllegalStateException.class,
() -> JarPatcher.applicablePatches(patchSet, new GameVersion(43, 0, 0)));
}
}
@@ -0,0 +1,61 @@
package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
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.BIPUSH;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.PUTSTATIC;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class GameVersionReaderTest {
@Test
void readsVersionFromCoreStaticInitializer() {
assertEquals(new GameVersion(42, 21, 2), GameVersionReader.read(coreClass(42, 21, 2)));
}
/** Runs when the Gradle build passes the server jar (pz.jar) and targeted version (pz.version). */
@Test
void readsTargetedVersionFromServerJar() throws Exception {
String jar = System.getProperty("pz.jar", "");
assumeTrue(!jar.isEmpty() && Files.isRegularFile(Path.of(jar)), "server jar not available");
GameVersion version = JarPatcher.readGameVersion(Path.of(jar));
assertTrue(version.matches(System.getProperty("pz.version")), "server jar is " + version);
}
/** Mirrors Core: {@code gameVersion = new GameVersion(major, minor, "")} plus a buildVersion constant. */
private static byte[] coreClass(int major, int minor, int build) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(V25, ACC_PUBLIC, GameVersionReader.CORE_CLASS, null, "java/lang/Object", null);
cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "gameVersion", "Lzombie/core/GameVersion;", null, null);
cw.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, "buildVersion", "I", null, build);
MethodVisitor clinit = cw.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
clinit.visitTypeInsn(NEW, "zombie/core/GameVersion");
clinit.visitInsn(DUP);
clinit.visitIntInsn(BIPUSH, major);
clinit.visitIntInsn(BIPUSH, minor);
clinit.visitLdcInsn("");
clinit.visitMethodInsn(INVOKESPECIAL, "zombie/core/GameVersion", "<init>", "(IILjava/lang/String;)V", false);
clinit.visitFieldInsn(PUTSTATIC, GameVersionReader.CORE_CLASS, "gameVersion", "Lzombie/core/GameVersion;");
clinit.visitInsn(RETURN);
clinit.visitMaxs(0, 0);
cw.visitEnd();
return cw.toByteArray();
}
}
@@ -0,0 +1,37 @@
package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
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;
class GameVersionTest {
@Test
void parsesTwoAndThreePartVersions() {
assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21"));
assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3"));
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42"));
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("b42.21"));
}
@Test
void twoPartExpectationMatchesEveryBuild() {
GameVersion version = new GameVersion(42, 21, 3);
assertTrue(version.matches("42.21"));
assertTrue(version.matches("42.21.3"));
assertFalse(version.matches("42.21.0"));
assertFalse(version.matches("42.20"));
}
@Test
void comparesNumerically() {
GameVersion version = new GameVersion(42, 21, 0);
assertTrue(version.isAtLeast(42, 9));
assertTrue(version.isAtLeast(42, 21));
assertFalse(version.isAtLeast(42, 22));
assertTrue(version.isBefore(43, 0));
assertFalse(version.isBefore(42, 21));
}
}
@@ -0,0 +1,181 @@
package dev.overlord.zomboidforge.patcher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
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;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.ALOAD;
import static org.objectweb.asm.Opcodes.ARETURN;
import static org.objectweb.asm.Opcodes.DUP;
import static org.objectweb.asm.Opcodes.GOTO;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.ILOAD;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.NEW;
import static org.objectweb.asm.Opcodes.RETURN;
import static org.objectweb.asm.Opcodes.V25;
class JarPatcherTest
{
@TempDir
Path dir;
/** Adds {@code static Object pick(boolean)} returning a new A or B; frame computation at the merge point requires Base as common superclass. */
private static final ClassPatch ADD_PICK = new ClassPatch()
{
@Override
public String target() {
return "t/Target";
}
@Override
public void apply(ClassNode node)
{
MethodNode m = new MethodNode(ACC_PUBLIC | ACC_STATIC, "pick", "(Z)Ljava/lang/Object;", null, null);
Label elseBranch = new Label();
Label end = new Label();
m.visitVarInsn(ILOAD, 0);
m.visitJumpInsn(IFEQ, elseBranch);
newInstance(m, "t/A");
m.visitJumpInsn(GOTO, end);
m.visitLabel(elseBranch);
newInstance(m, "t/B");
m.visitLabel(end);
m.visitInsn(ARETURN);
node.methods.add(m);
}
};
//
@Test
void patchesTargetAndCopiesEverythingElse() throws Exception
{
Path in = jar(Map.of(
"t/Base.class", classBytes("t/Base", "java/lang/Object"),
"t/A.class", classBytes("t/A", "t/Base"),
"t/B.class", classBytes("t/B", "t/Base"),
"t/Target.class", classBytes("t/Target", "java/lang/Object"),
"media/readme.txt", "untouched".getBytes()
));
Path out = dir.resolve("out/patched.jar");
assertEquals(1, new JarPatcher(List.of(ADD_PICK)).patch(in, out));
try (JarFile original = new JarFile(in.toFile()); JarFile patched = new JarFile(out.toFile()))
{
for (String name : List.of("t/Base.class", "t/A.class", "t/B.class", "media/readme.txt"))
{
assertArrayEquals(
read(original, name),
read(patched, name),
name
);
}
}
try (URLClassLoader loader = new URLClassLoader(new URL[]{out.toUri().toURL()}, null))
{
Class<?> target = loader.loadClass("t.Target");
Object picked = target.getMethod("pick", boolean.class).invoke(null, true);
assertEquals("t.A", picked.getClass().getName());
}
}
@Test
void failsWhenTargetIsMissing() throws IOException
{
Path in = jar(Map.of("t/Other.class", classBytes("t/Other", "java/lang/Object")));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(ADD_PICK)).patch(in, dir.resolve("out.jar"))
);
assertTrue(e.getMessage().contains("'t/Target.class' not found"), e.getMessage());
}
@Test
void failsWhenTargetHasMultiReleaseOverride() throws IOException
{
byte[] target = classBytes("t/Target", "java/lang/Object");
Path in = jar(Map.of("t/Target.class", target, "META-INF/versions/21/t/Target.class", target));
IllegalStateException e = assertThrows(
IllegalStateException.class,
() -> new JarPatcher(List.of(ADD_PICK)).patch(in, dir.resolve("out.jar"))
);
assertTrue(e.getMessage().contains("overrides a patched class"), e.getMessage());
}
private static void newInstance(MethodVisitor m, String type) {
m.visitTypeInsn(NEW, type);
m.visitInsn(DUP);
m.visitMethodInsn(INVOKESPECIAL, type, "<init>", "()V", false);
}
private static byte[] classBytes(String name, String superName)
{
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(V25, ACC_PUBLIC, name, null, superName, null);
MethodVisitor init = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
init.visitVarInsn(ALOAD, 0);
init.visitMethodInsn(INVOKESPECIAL, superName, "<init>", "()V", false);
init.visitInsn(RETURN);
init.visitMaxs(0, 0);
cw.visitEnd();
return cw.toByteArray();
}
private Path jar(Map<String, byte[]> entries) throws IOException
{
Path jar = Files.createTempFile(dir, "in", ".jar");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(jar)))
{
for (Map.Entry<String, byte[]> e : entries.entrySet()) {
zip.putNextEntry(new ZipEntry(e.getKey()));
zip.write(e.getValue());
zip.closeEntry();
}
}
return jar;
}
private static byte[] read(JarFile jar, String name) throws IOException {
return jar.getInputStream(jar.getEntry(name)).readAllBytes();
}
}
+18
View File
@@ -0,0 +1,18 @@
pluginManagement {
includeBuild("build-logic")
}
dependencyResolutionManagement {
repositories {
mavenCentral()
}
}
rootProject.name = "ZomboidForge"
include("api", "core", "agent", "patcher")
// Only the compat modules of the selected Project Zomboid Build are part of the build.
// Each of them compiles against that Build's server jar.
val pzBuild = providers.gradleProperty("pz.version").get().substringBefore('.')
include(":compat:b$pzBuild:patches", ":compat:b$pzBuild:runtime")