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

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

No files matched your search

+2
View File
@@ -5,6 +5,8 @@
!settings.gradle.kts !settings.gradle.kts
!build-logic/ !build-logic/
!api/ !api/
!core/
!compat/
!agent/ !agent/
!patcher/ !patcher/
!docker/ !docker/
+1
View File
@@ -2,6 +2,7 @@
!README.md !README.md
lib lib
.*/ .*/
!.gitea/
build/ build/
out/ out/
+46 -6
View File
@@ -4,9 +4,22 @@
# contains no game files. # contains no game files.
# #
# podman build --platform linux/amd64 -t zomboidforge . # podman build --platform linux/amd64 -t zomboidforge .
# podman build --build-arg PZ_BRANCH=unstable ... # non-public Steam branch # 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_BRANCH=public
ARG PZ_VERSION=""
ARG STEAMCLIENT=bundled
ARG FORGE_VERSION=""
ARG STEAM_BUILDID=""
# --- Stage 1: vanilla dedicated server ----------------------------------------- # --- Stage 1: vanilla dedicated server -----------------------------------------
FROM docker.io/steamcmd/steamcmd:debian-13 AS server FROM docker.io/steamcmd/steamcmd:debian-13 AS server
@@ -16,8 +29,9 @@ FROM docker.io/steamcmd/steamcmd:debian-13 AS server
RUN steamcmd +quit RUN steamcmd +quit
ARG PZ_BRANCH ARG PZ_BRANCH
ARG STEAMCLIENT
COPY docker/install-server.sh /usr/local/bin/install-server COPY docker/install-server.sh /usr/local/bin/install-server
RUN install-server /server "${PZ_BRANCH}" RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
# --- Stage 2: ZomboidForge build and server jar patching ----------------------- # --- Stage 2: ZomboidForge build and server jar patching -----------------------
FROM docker.io/library/eclipse-temurin:25-jdk AS build FROM docker.io/library/eclipse-temurin:25-jdk AS build
@@ -30,19 +44,28 @@ RUN ./gradlew --no-daemon --version
COPY build-logic build-logic COPY build-logic build-logic
COPY api api COPY api api
COPY core core
COPY compat compat
COPY agent agent COPY agent agent
COPY patcher patcher COPY patcher patcher
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
RUN ./gradlew --no-daemon -Ppz.jar=/pz/projectzomboid.jar build :patcher:patchServerJar
# 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 ------------------------------------------------------------ # --- Stage 3: runtime ------------------------------------------------------------
FROM docker.io/library/debian:trixie-slim FROM docker.io/library/debian:trixie-slim
# ca-certificates: required by steamclient.so to connect to Steam. Unpinned so # ca-certificates: required by steamclient.so to connect to Steam.
# the image picks up the current Debian CA bundle. # sqlite3: the entrypoint checks the admin account in the server database.
# Unpinned so the image picks up current Debian security updates.
# hadolint ignore=DL3008 # hadolint ignore=DL3008
RUN apt-get update \ RUN apt-get update \
&& apt-get install --yes --no-install-recommends ca-certificates \ && apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
&& rm --recursive --force /var/lib/apt/lists/* && rm --recursive --force /var/lib/apt/lists/*
RUN useradd --create-home --uid 1000 pz \ RUN useradd --create-home --uid 1000 pz \
@@ -54,6 +77,23 @@ COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/proj
COPY --from=build /src/agent/build/libs/zomboidforge-agent-*.jar /opt/pz/zomboidforge-agent.jar COPY --from=build /src/agent/build/libs/zomboidforge-agent-*.jar /opt/pz/zomboidforge-agent.jar
COPY docker/entrypoint.sh /usr/local/bin/entrypoint 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 USER 1000:1000
VOLUME /data VOLUME /data
# 16261/udp game, 16262/udp direct connect, 27015/tcp RCON # 16261/udp game, 16262/udp direct connect, 27015/tcp RCON
+43 -5
View File
@@ -7,30 +7,65 @@ first‑class support for custom Java mods and drop‑in server builds.
The container image downloads the vanilla dedicated server (Steam app 380870) with an 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 anonymous steamcmd login while it builds, and patches it. No game files are part of this
repository. repository. The build fails when the downloaded server is not the Project Zomboid
version in `gradle.properties` (`pz.version`).
```sh ```sh
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ... 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 ## Running
```sh ```sh
podman run -d --name zomboidforge \ podman run -d --name zomboidforge \
-e ADMIN_PASSWORD=... -e RCON_PASSWORD=... \ -e ADMIN_PASSWORD=... -e RCON_PASSWORD=... \
-p 16261:16261/udp -p 16262:16262/udp -p 27015:27015/tcp \ -p 16261:16261/udp -p 16262:16262/udp -p 127.0.0.1:27015:27015/tcp \
-v zomboid-data:/data zomboidforge -v zomboid-data:/data zomboidforge
``` ```
Unset variables keep the value in the server `.ini` (or the game default).
| Variable | Default | | | Variable | Default | |
|---|---|---| |---|---|---|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) | | `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
| `ADMIN_PASSWORD` | | Required on the first start, when the admin account is created | | `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
| `RCON_PASSWORD` | | Written into the server ini on every start; RCON is disabled without it | | `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` | | `JVM_MAX_HEAP` | `8g` | `-Xmx` |
| `STEAM` | `1` | `0` runs the server without Steam | | `STEAM` | `1` | `0` runs the server without Steam |
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
For local testing there is `compose.yaml` (`podman compose up --build`, passwords from `.env`). 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 ## Development
@@ -41,3 +76,6 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
./gradlew build # compile + tests ./gradlew build # compile + tests
./gradlew :patcher:patchServerJar # -> patcher/build/server/projectzomboid.jar ./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() {}
}
@@ -1,6 +1,13 @@
import org.gradle.api.file.RegularFileProperty import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
abstract class ProjectZomboidExtension { abstract class ProjectZomboidExtension {
/** Vanilla dedicated server projectzomboid.jar. Not bundled or published. */ /** Vanilla dedicated server projectzomboid.jar. Not bundled or published. */
abstract val serverJar: RegularFileProperty 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"
} }
@@ -8,6 +8,13 @@ projectZomboid.serverJar.convention(
providers.gradleProperty("pz.jar").orElse("lib/server/java/projectzomboid.jar") 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 { java {
// Project Zomboid ships and runs on Java 25 (bundled Zulu jre64; class version 69). // Project Zomboid ships and runs on Java 25 (bundled Zulu jre64; class version 69).
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;
+17 -5
View File
@@ -1,5 +1,5 @@
# Local test setup: `podman compose up --build`. Passwords are read from the # Local test setup: `podman compose up --build`. Settings are read from the
# environment or from .env (gitignored). # environment or from .env (gitignored); docker/entrypoint.sh lists all variables.
services: services:
zomboidforge: zomboidforge:
build: . build: .
@@ -7,13 +7,25 @@ services:
platform: linux/amd64 platform: linux/amd64
environment: environment:
SERVER_NAME: ${SERVER_NAME:-zomboidforgetest} 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:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
SERVER_PRESET: ${SERVER_PRESET:-}
MODS: ${MODS:-}
WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-}
RCON_PASSWORD: ${RCON_PASSWORD:-} RCON_PASSWORD: ${RCON_PASSWORD:-}
JVM_MIN_HEAP: ${JVM_MIN_HEAP:-}
JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g} JVM_MAX_HEAP: ${JVM_MAX_HEAP:-8g}
ports: ports:
- "16261:16261/udp" # Host and container ports must be equal: the server reports its own port
- "16262:16262/udp" # to Steam and to clients, so a remapped port is unreachable.
- "27015:27015/tcp" - "${PORT:-16261}:${PORT:-16261}/udp"
- "${UDP_PORT:-16262}:${UDP_PORT:-16262}/udp"
- "127.0.0.1:27015:27015/tcp"
volumes: volumes:
- zomboid-data:/data - zomboid-data:/data
# SIGTERM runs GameServer's shutdown hook, which queues a save-and-quit. # SIGTERM runs GameServer's shutdown hook, which queues a save-and-quit.
+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;
+206 -23
View File
@@ -4,12 +4,41 @@
# with the ZomboidForge agent. Arguments are passed through to # with the ZomboidForge agent. Arguments are passed through to
# zombie.network.GameServer. # zombie.network.GameServer.
# #
# Environment variables: # 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_NAME Server config name (/data/Server/<name>.ini). Default: zomboidforge
# ADMIN_PASSWORD Admin account password. Required on the first start only. # SERVER_PASSWORD Password clients need to join (.ini Password)
# RCON_PASSWORD Written into the server .ini before every start. RCON is disabled when empty. # PUBLIC true/false: listed in the in-game server browser (.ini Public)
# JVM_MAX_HEAP Value for -Xmx. Default: 8g (the vanilla ProjectZomboid64.json value) # 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 # 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 errexit
set -o nounset set -o nounset
@@ -19,20 +48,67 @@ readonly INSTALL_DIR="/opt/pz"
readonly DATA_DIR="/data" readonly DATA_DIR="/data"
readonly AGENT_JAR="${INSTALL_DIR}/zomboidforge-agent.jar" readonly AGENT_JAR="${INSTALL_DIR}/zomboidforge-agent.jar"
readonly JAVA="${INSTALL_DIR}/jre64/bin/java" 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_NAME="${SERVER_NAME:-zomboidforge}"
readonly ADMIN_PASSWORD="${ADMIN_PASSWORD:-}" readonly SERVER_PASSWORD="${SERVER_PASSWORD:-}"
readonly RCON_PASSWORD="${RCON_PASSWORD:-}" readonly PUBLIC="${PUBLIC:-}"
readonly JVM_MAX_HEAP="${JVM_MAX_HEAP:-8g}" readonly PUBLIC_NAME="${PUBLIC_NAME:-}"
readonly PORT="${PORT:-}"
readonly UDP_PORT="${UDP_PORT:-}"
readonly STEAM="${STEAM:-1}" 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_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" 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() { log() {
echo "[entrypoint] $*" >&2 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. # 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. # Project Zomboid reads a partial .ini and writes the missing defaults on start.
set_ini_value() { set_ini_value() {
@@ -63,30 +139,101 @@ set_ini_value() {
mv "${temp_file}" "${SERVER_INI}" mv "${temp_file}" "${SERVER_INI}"
} }
apply_rcon_password() { # Sets <key>=<value> only when <value> is not empty.
if [[ -z "${RCON_PASSWORD}" ]]; then 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." 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 return
fi fi
set_ini_value "RCONPassword" "${RCON_PASSWORD}" 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}"
} }
# Without -adminpassword, Project Zomboid blocks on an interactive prompt to # Sets needs_admin_password, used by build_server_args.
# create the admin account on the first start. check_admin_account() {
check_admin_password() { if admin_account_exists; then
if [[ -z "${ADMIN_PASSWORD}" && ! -f "${SERVER_DB}" ]]; then needs_admin_password=false
log "First start of '${SERVER_NAME}': ADMIN_PASSWORD is required to create the admin account." if [[ -n "${ADMIN_PASSWORD}" ]]; then
exit 1 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 fi
} }
main() {
apply_rcon_password
check_admin_password
# Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh. # Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh.
# Java runs directly instead of through the native ProjectZomboid64 launcher. # Java runs directly instead of through the native ProjectZomboid64 launcher.
local jvm_args=( build_jvm_args() {
jvm_args=(
"-javaagent:${AGENT_JAR}" "-javaagent:${AGENT_JAR}"
"-Djava.awt.headless=true" "-Djava.awt.headless=true"
"--enable-native-access=ALL-UNNAMED" "--enable-native-access=ALL-UNNAMED"
@@ -100,13 +247,49 @@ main() {
"-cp" "java/:java/projectzomboid.jar" "-cp" "java/:java/projectzomboid.jar"
) )
local server_args=( 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}" "-cachedir=${DATA_DIR}"
"-servername" "${SERVER_NAME}" "-servername" "${SERVER_NAME}"
) )
if [[ -n "${ADMIN_PASSWORD}" ]]; then
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}") server_args+=("-adminpassword" "${ADMIN_PASSWORD}")
fi 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). # Native libraries: game (linux64/), Steam (install root), JVM (jre64/lib).
# libjsig.so chains signal handlers between the JVM and native libraries. # libjsig.so chains signal handlers between the JVM and native libraries.
+48 -3
View File
@@ -4,8 +4,14 @@
# with steamcmd, using an anonymous login. Runs in the steamcmd image during # with steamcmd, using an anonymous login. Runs in the steamcmd image during
# the Docker build. # the Docker build.
# #
# Usage: install-server.sh <install-dir> <branch> # Usage: install-server.sh <install-dir> <branch> <steamclient>
# <branch> Steam branch; "public" is the default branch. # <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 errexit
set -o nounset set -o nounset
@@ -13,15 +19,17 @@ set -o pipefail
readonly APP_ID="380870" readonly APP_ID="380870"
readonly MAX_ATTEMPTS=3 readonly MAX_ATTEMPTS=3
readonly STEAMCMD_DIR="${HOME}/.local/share/Steam/steamcmd"
readonly INSTALL_DIR="$1" readonly INSTALL_DIR="$1"
readonly BRANCH="$2" readonly BRANCH="$2"
readonly STEAMCLIENT="$3"
log() { log() {
echo "[install-server] $*" >&2 echo "[install-server] $*" >&2
} }
main() { install_app() {
local branch_args=() local branch_args=()
if [[ "${BRANCH}" != "public" ]]; then if [[ "${BRANCH}" != "public" ]]; then
branch_args=("-beta" "${BRANCH}") branch_args=("-beta" "${BRANCH}")
@@ -47,6 +55,43 @@ main() {
log "Installation failed: ${INSTALL_DIR}/java/projectzomboid.jar not found" log "Installation failed: ${INSTALL_DIR}/java/projectzomboid.jar not found"
exit 1 exit 1
fi 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. # Steam's install metadata; not needed at runtime.
rm --recursive --force "${INSTALL_DIR}/steamapps" rm --recursive --force "${INSTALL_DIR}/steamapps"
+5
View File
@@ -1,6 +1,11 @@
group=dev.overlord.zomboidforge group=dev.overlord.zomboidforge
version=0.1.0-SNAPSHOT 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. # Vanilla dedicated server jar used for compilation and patching.
# Default: lib/server/java/projectzomboid.jar (relative to the root project). # Default: lib/server/java/projectzomboid.jar (relative to the root project).
# The Docker build sets -Ppz.jar. # The Docker build sets -Ppz.jar.
+3
View File
@@ -1,8 +1,11 @@
[versions] [versions]
asm = "9.10.1" asm = "9.10.1"
junit = "6.1.3" junit = "6.1.3"
jetbrains-annotations = "26.0.2"
[libraries] [libraries]
#noinspection UnusedVersionCatalogEntry
jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" }
asm = { module = "org.ow2.asm:asm", version.ref = "asm" } asm = { module = "org.ow2.asm:asm", version.ref = "asm" }
asm-tree = { module = "org.ow2.asm:asm-tree", 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-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" }
+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();
}
+6 -1
View File
@@ -10,4 +10,9 @@ dependencyResolutionManagement {
rootProject.name = "ZomboidForge" rootProject.name = "ZomboidForge"
include("api", "agent", "patcher") 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")