13 Commits
Author SHA1 Message Date
aidan c5ca0f8a20 Update README.md 2026-11-11 01:37:03 +02:00
aidanandClaude Opus 5.5 05d169a2dd Sync local working tree: injector, engine, mixin and build updates
Add compatibility notes, resource-provider and hook checks, and payload
bundling script. Remove generated engine mixin stubs, engine target lists
and prebuilt binaries now produced by the build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-10 17:27:24 -06:00
aidan 6d94493e58 Upload files to "/" 2026-11-11 01:20:27 +02:00
aidan 06269f1f65 Delete OpenPrestige-1.21.1-1.21.11-windows-x64.zip 2026-11-11 01:19:28 +02:00
aidan b3e3b26973 Upload files to "/" 2026-11-11 01:18:03 +02:00
aidan da2ae3a45c Upload files to "/" 2026-11-11 01:16:57 +02:00
aidan 40a82405e5 Update README.md 2026-11-11 01:16:32 +02:00
bbldrizzy 9b36349e1a Update README.md 2026-11-05 10:29:46 +01:00
bbldrizzy 2d6b2a3cd1 Build offline OpenPrestige release bundles
Rename the injector and package it with an embedded payload for Windows, Linux, and macOS x64/ARM64. Add a core-only ImGui native build, multi-platform CI and release packaging, and shared per-user storage with legacy config migration.
2026-11-03 18:45:13 +00:00
bbldrizzy 5152e6e0a6 make fabric entry points wired through an adapter 2026-11-03 11:46:46 +00:00
bbldrizzy 0abefe7a04 Merge branch 'main' of https://codeberg.org/SkidSolutions/OpenPrestige 2026-11-03 11:42:12 +00:00
bbldrizzy 036b24f2ae Improve launcher injection and hook reliability
Find Fabric through the render thread's class loader and make bytecode transformations safer for launcher-provided class definitions. Improve hook reporting, process-picker refresh behavior, and self-destruct cleanup; document Dawn and Lunar 1.21.11 setup.
2026-11-03 11:40:43 +00:00
bbldrizzy 41d3e4a65e Update README.md 2026-10-28 11:27:50 +01:00
244 changed files with 3637 additions and 1490 deletions

No files matched your search

+105 -21
View File
@@ -6,74 +6,158 @@ on:
paths:
- "injector/**"
- "src/**"
- "scripts/**"
- "build.gradle"
- "settings.gradle"
- "stonecutter.gradle"
- "gradle.properties"
- "versions/**/gradle.properties"
- "gradle/**"
- "check/**"
- ".github/workflows/injector.yml"
jobs:
payload:
name: Payload jar
runs-on: ubuntu-latest
core-imgui:
name: ImGui (${{ matrix.platform }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
platform: windows-x86_64
toolchain: windows-x86_64
- os: ubuntu-latest
platform: windows-aarch64
toolchain: windows-aarch64
- os: ubuntu-latest
platform: linux-x86_64
- os: ubuntu-latest
platform: linux-aarch64
toolchain: linux-aarch64
- os: macos-14
platform: macos-universal
toolchain: macos-universal
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- name: Install native build tools
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y cmake g++ g++-aarch64-linux-gnu
- name: Install Windows cross compiler
if: startsWith(matrix.platform, 'windows-')
run: |
curl -fL --retry 3 https://github.com/mstorsjo/llvm-mingw/releases/download/20261020/llvm-mingw-20261020-ucrt-ubuntu-22.04-x86_64.tar.xz -o "$RUNNER_TEMP/llvm-mingw.tar.xz"
tar -xf "$RUNNER_TEMP/llvm-mingw.tar.xz" -C "$RUNNER_TEMP"
echo "$RUNNER_TEMP/llvm-mingw-20261020-ucrt-ubuntu-22.04-x86_64/bin" >> "$GITHUB_PATH"
- name: Build core-only ImGui
env:
TOOLCHAIN: ${{ matrix.toolchain }}
run: |
if [ -n "$TOOLCHAIN" ]; then
python3 scripts/build_imgui_core.py --output "build/core-natives/${{ matrix.platform }}" --toolchain "scripts/imgui-core/toolchains/$TOOLCHAIN.cmake"
else
python3 scripts/build_imgui_core.py --output "build/core-natives/${{ matrix.platform }}"
fi
- name: Exercise core JNI with the UI font
if: matrix.platform == 'linux-x86_64' || matrix.platform == 'macos-universal'
run: |
java -Dimgui.library.path="$PWD/build/core-natives/${{ matrix.platform }}" -cp build/imgui-core/deps/imgui-java-binding-1.92.7.1.jar scripts/imgui-core/SmokeTest.java src/main/resources/prestige_ui/fonts/DMSans-Regular.ttf
- uses: actions/upload-artifact@v4
with:
name: imgui-${{ matrix.platform }}
path: build/core-natives/*
if-no-files-found: error
payload:
name: Payload jar
needs: core-imgui
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check release packaging
run: |
python3 scripts/test_release.py
python3 check/bundle_payloads_check.py
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
- uses: actions/download-artifact@v4
with:
pattern: imgui-*
merge-multiple: true
path: build/core-natives
- name: Build remapped jar
run: |
chmod +x ./gradlew
./gradlew remapJar --console=plain
./gradlew bundlePayloads -PpythonExecutable=python3 --console=plain
- name: Upload jar
uses: actions/upload-artifact@v4
with:
name: payload-jar # also the Fabric mod: drop prestige-*.jar into mods/
path: |
build/libs/prestige-*.jar
!build/libs/*-dev.jar
!build/libs/*-sources.jar
name: payload-bundle
path: build/bundle
if-no-files-found: error
injector:
name: Injector (${{ matrix.target }})
name: OpenPrestige (${{ matrix.platform.target }})
needs: payload
runs-on: ${{ matrix.os }}
runs-on: ${{ matrix.platform.os }}
strategy:
fail-fast: false
matrix:
include:
platform:
- os: windows-latest
target: x86_64-pc-windows-msvc
name: windows-x86_64
files: |
injector/target/release/PrestigeInjector.exe
injector/target/release/OpenPrestigeInjector.exe
injector/target/release/prestige_native.dll
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
name: linux-x86_64
files: |
injector/target/release/PrestigeInjector
injector/target/release/OpenPrestigeInjector
injector/target/release/libprestige_native.so
- os: windows-11-arm
target: aarch64-pc-windows-msvc
name: windows-aarch64
files: |
injector/target/release/OpenPrestigeInjector.exe
injector/target/release/prestige_native.dll
- os: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
name: linux-aarch64
files: |
injector/target/release/OpenPrestigeInjector
injector/target/release/libprestige_native.so
- os: macos-13
target: x86_64-apple-darwin
name: macos-x86_64
files: |
injector/target/release/PrestigeInjector
injector/target/release/OpenPrestigeInjector
injector/target/release/libprestige_native.dylib
- os: macos-14
target: aarch64-apple-darwin
name: macos-aarch64
files: |
injector/target/release/PrestigeInjector
injector/target/release/OpenPrestigeInjector
injector/target/release/libprestige_native.dylib
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
targets: ${{ matrix.platform.target }}
- name: Download payload jar
uses: actions/download-artifact@v4
with:
name: payload-jar
path: build/libs
name: payload-bundle
path: build/bundle
- name: Build
run: cargo build --release --manifest-path injector/Cargo.toml
- name: Test
@@ -81,6 +165,6 @@ jobs:
- name: Upload injector
uses: actions/upload-artifact@v4
with:
name: injector-${{ matrix.name }}
path: ${{ matrix.files }}
name: openprestige-${{ matrix.platform.name }}
path: ${{ matrix.platform.files }}
if-no-files-found: error
+6
View File
@@ -17,5 +17,11 @@ hs_err_pid*
openvape.zip
/dist/
/work/
/injector/target/
/tools
/examples
# Python build helpers
__pycache__/
*.pyc
+94
View File
@@ -0,0 +1,94 @@
# Minecraft multi-version compatibility
Implemented targets: every release from **1.21.1 through 1.21.11**. The editor
version remains 1.21.11; Stonecutter 0.9.8 produces eleven exact-version variants
from the shared source tree. Dependencies are pinned in each version directory.
## Verified on Windows x64, JDK 21
- All eleven variants compile, remap, and pass access-widener validation.
- Every variant passes bytecode checks of ClassTransform target classes, shadow
fields, method selectors, callback parameters, and invocation targets.
- Every variant launches a development client, initializes all applicable
modules, loads every engine target, and exits normally.
- The release contains one injector and one native library. The native library
embeds one common JAR and eleven version payloads, selecting the exact target
from Fabric metadata before loading it.
- Native loading tests on 1.21.1 and 1.21.11 select and extract the correct
payload plus the common JAR. These tests run with the mod already present,
so bootstrap deliberately skips installing a second set of hooks.
- Recombining each thin payload with common.jar reproduces every original
remapped JAR entry byte for byte. Exact-version guard and bundle reconstruction
checks pass.
- The split payloads total 46,889,252 bytes, versus 174,127,644 bytes for the
eleven standalone JARs. The Windows release ZIP is 45,882,051 bytes.
| Minecraft | Initialized modules | Loaded engine targets | Startup |
| --- | ---: | ---: | --- |
| 1.21.1 | 117 | 40 | Passed |
| 1.21.2 | 117 | 41 | Passed |
| 1.21.3 | 117 | 41 | Passed |
| 1.21.4 | 117 | 41 | Passed |
| 1.21.5 | 117 | 41 | Passed |
| 1.21.6 | 117 | 41 | Passed |
| 1.21.7 | 117 | 41 | Passed |
| 1.21.8 | 117 | 41 | Passed |
| 1.21.9 | 117 | 42 | Passed |
| 1.21.10 | 117 | 42 | Passed |
| 1.21.11 | 121 | 42 | Passed |
Spear modules are omitted before 1.21.11 because those game versions do not
contain spears. Their manifest and UI entries are omitted as well. Engine
anchors, transformer lists, and named/intermediary target lists are generated
from each version’s compiled annotations and Yarn mappings.
## Runtime limits
The user reports Dawn 1.21.11 working. The checks above are development Fabric
clients; full Dawn injection and world gameplay have not been tested separately
on every patch version. Startup checks do not exercise every module.
The existing nonfatal prestige:inter font JSON warning remains. Previous
isolated-loader injection self-tests had hierarchy-related failures; this work
does not claim to resolve those self-test limitations. ARM64, Linux, and macOS
build scripts are updated but were not built or hardware-tested in this Windows
session.
Only the eleven listed versions are selected. Minecraft 1.21, snapshots, and
unrecognized versions are rejected rather than assigned the nearest payload.
## Build and use
```powershell
./gradlew :1.21.1:build # one standalone Fabric mod
./gradlew bundlePayloads # all variants, checks, shared bundle
./build-injector.ps1 # offline Windows injector ZIP
```
Use JDK 21, Python 3, and Rust with MSVC build tools. Override the Python command
with `build-injector.ps1 -Python <python.exe>` or
`./gradlew bundlePayloads -PpythonExecutable=<python.exe>` when needed.
Extract the complete release ZIP. Keep OpenPrestigeInjector.exe and
prestige_native.dll together, start a supported game, then select its JVM in the
injector. The native release needs no loose payload JARs or runtime downloads.
Use either injection or a standalone Fabric mod, and start a fresh game process
when testing a replacement native release.
Per-version standalone mods are in `versions/<minecraft>/build/libs/`. The
`build/bundle/*.jar` files are split injector inputs and must not be installed
as standalone mods. Per-version development worlds live in separate run
directories.
```powershell
./gradlew validateHooks
python check/bundle_payloads_check.py
python scripts/test_release.py
./gradlew -I check/resource-provider.gradle :1.21.11:resourceProviderCheck
cargo test --manifest-path injector/Cargo.toml -p prestige_native --offline
```
The resource-provider regression retains the generated-class fallback used by
the Dawn fix. Single-target developer builds can explicitly set
`PRESTIGE_PAYLOAD`; normal native builds require the complete bundle and never
pick an arbitrary newest JAR.
+34 -5
View File
@@ -1,12 +1,15 @@
# Open Prestige
A semi deobfuscated, IntelliJ-ready, runnable open sourced version of the Prestige client for Fabric 1.21.11.
**Minecraft 1.21.1 through 1.21.11:** shared sources are built with Stonecutter.
See [COMPATIBILITY.md](COMPATIBILITY.md) for verification and runtime limits.
This repository builds the fully offline OpenPrestige CLI with its payload embedded in the native library. The graphical launcher and runtime downloads are maintained in the separate Prestige repository. See [injector build instructions](injector/README.md).
A fully deobfuscated, IntelliJ-ready, runnable open sourced version of the Prestige client for Fabric 1.21.1–1.21.11.
---
- we will work on removing the param obf and also renaming vars in the coming days. stay tuned!
- if vikas wants to pay me to remove this, make ticket in discord and we can negotiate.
@ 1500 discord members, we will release injector
<p align="center">
<img src="docs/img/deobf-bird.png" width="260" alt="Deobf?">
@@ -36,15 +39,41 @@ run.bat
Open in IntelliJ: File > Open > this folder (`build.gradle`), "Open as Project", Gradle JVM = JDK 21,
then use the generated **Minecraft Client** run configuration.
Build a self-contained mod jar (imgui-java + natives and ClassTransform are bundled):
Build one exact-version Fabric mod (replace the version as needed):
```
gradlew build
gradlew :1.21.1:build
```
Build all eleven variants and the shared-library payload bundle:
```
gradlew bundlePayloads
```
Build the offline Windows injector ZIP with all versions embedded:
```powershell
./build-injector.ps1
```
The native library selects the exact game version before loading the client.
ImGui, native libraries, ClassTransform, and identical assets are stored once.
Standalone mod JARs remain in `versions/<minecraft>/build/libs/`; install only the
one matching your game. `build/bundle/*.jar` are split injector inputs, not mods.
JDK 21, Python 3, and Rust with platform build tools are required. If Python is not
on PATH, use `build-injector.ps1 -Python <python.exe>` or Gradle's
`-PpythonExecutable=<python.exe>`. Linux/macOS host builds use `build-injector.sh`.
Stonecutter's active editor version is 1.21.11. Each version has its own dev run
folder; do not move test worlds between game versions.
## Credits
- **technix**: sourcing / Frida scripts
- **stutheguyy**: fixing
- **bynbang / nitrogenoliquido**: ZKM transformers
- **dario**: AI models
- **aidan**: so sexy and helped with dawn client / version support 1.21.1 to 1.21.11
- **downrizz**: aidan is just so sexy
+17 -14
View File
@@ -1,14 +1,17 @@
# Builds the Prestige payload jar (remapped for the production Fabric runtime), then the Rust injector and loader DLL,
# and collects PrestigeInjector.exe + prestige_native.dll in dist\.
# native tools write progress/notes to stderr; failures are detected through $LASTEXITCODE instead
$ErrorActionPreference = 'Continue'
Set-Location $PSScriptRoot
if (Test-Path 'C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot') { $env:JAVA_HOME = 'C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot' }
& .\gradlew.bat remapJar --console=plain
if ($LASTEXITCODE -ne 0) { throw 'gradle remapJar failed' }
cargo build --release --manifest-path injector\Cargo.toml
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }
New-Item -ItemType Directory -Force dist | Out-Null
Copy-Item injector\target\release\PrestigeInjector.exe, injector\target\release\prestige_native.dll dist\ -Force
Get-ChildItem build\libs\prestige-*.jar | Where-Object { $_.Name -notmatch '-(dev|sources)\.jar$' } | Copy-Item -Destination dist\ -Force
Write-Host 'Done: dist\PrestigeInjector.exe + dist\prestige_native.dll + dist\prestige-*.jar (Fabric mod)'
# Build OpenPrestige and collect the host binaries in dist/.
param([string]$Python = 'python')
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot
if (Test-Path 'C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot') { $env:JAVA_HOME = 'C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot' }
& .\gradlew.bat bundlePayloads "-PpythonExecutable=$Python" --console=plain
if ($LASTEXITCODE -ne 0) { throw 'gradle bundlePayloads failed' }
$env:PRESTIGE_PAYLOAD = $null
$env:PRESTIGE_BUNDLE = Join-Path $PSScriptRoot 'build/bundle'
cargo build --release --manifest-path injector\Cargo.toml
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }
New-Item -ItemType Directory -Force dist | Out-Null
Copy-Item injector\target\release\OpenPrestigeInjector.exe, injector\target\release\prestige_native.dll dist\ -Force
$version = (Get-Content gradle.properties | Where-Object { $_ -like 'mod_version=*' }) -replace '^mod_version=', ''
& $Python scripts/package_release.py offline dist $version windows-x86_64 dist/OpenPrestigeInjector.exe dist/prestige_native.dll build/bundle/common.jar
if ($LASTEXITCODE -ne 0) { throw 'release packaging failed' }
Write-Host 'Done: dist contains the offline multi-version Windows bundle'
+13 -21
View File
@@ -1,34 +1,26 @@
#!/bin/sh
# Builds the Prestige payload jar (remapped for the production Fabric runtime), then the Rust injector and loader
# library, and collects PrestigeInjector + libprestige_native.{so,dylib} in dist/.
# Optional: set JAVA_HOME to pick the JDK used by Gradle.
# Build OpenPrestige for the current host. Optional JAVA_HOME selects the Gradle JDK.
set -eu
cd "$(dirname "$0")"
case "$(uname -s)" in
Linux) LIB=libprestige_native.so ;;
Linux) LIB=libprestige_native.so ;;
Darwin) LIB=libprestige_native.dylib ;;
*) echo "unsupported OS: $(uname -s) (use build-injector.ps1 on Windows)" >&2; exit 1 ;;
*) echo "Use build-injector.ps1 on Windows" >&2; exit 1 ;;
esac
if [ -n "${JAVA_HOME:-}" ]; then
export JAVA_HOME
PATH="$JAVA_HOME/bin:$PATH"
export PATH
fi
./gradlew remapJar --console=plain
./gradlew bundlePayloads "-PpythonExecutable=${PYTHON:-python3}" --console=plain
unset PRESTIGE_PAYLOAD
export PRESTIGE_BUNDLE="$PWD/build/bundle"
cargo build --release --manifest-path injector/Cargo.toml
mkdir -p dist
cp -f "injector/target/release/PrestigeInjector" "injector/target/release/$LIB" dist/
chmod +x dist/PrestigeInjector
# the same remapped jar is the Fabric mod (drop it into mods/)
for jar in build/libs/prestige-*.jar; do
case "$jar" in *-dev.jar|*-sources.jar) continue ;; esac
cp -f "$jar" dist/
done
echo "Done: dist/PrestigeInjector + dist/$LIB + dist/prestige-*.jar (Fabric mod)"
cp -f "injector/target/release/OpenPrestigeInjector" "injector/target/release/$LIB" dist/
chmod +x dist/OpenPrestigeInjector
VERSION=$(sed -n 's/^mod_version=//p' gradle.properties)
case "$(uname -s)" in Linux) PLATFORM=linux ;; Darwin) PLATFORM=macos ;; esac
case "$(uname -m)" in x86_64) ARCH=x86_64 ;; arm64|aarch64) ARCH=aarch64 ;; *) echo 'Unsupported architecture' >&2; exit 1 ;; esac
"${PYTHON:-python3}" scripts/package_release.py offline dist "$VERSION" "$PLATFORM-$ARCH" dist/OpenPrestigeInjector "dist/$LIB" build/bundle/common.jar
echo "Done: dist contains the offline multi-version host bundle"
+81 -86
View File
@@ -1,86 +1,81 @@
@echo off
rem Builds release zips for every platform into dist\release\ (run on Windows):
rem prestige-<ver>-windows-x86_64.zip PrestigeInjector.exe + prestige_native.dll + mod jar
rem prestige-<ver>-linux-x86_64.zip PrestigeInjector + libprestige_native.so + mod jar (glibc 2.17+, any distro)
rem prestige-<ver>-macos-universal.zip PrestigeInjector + libprestige_native.dylib + mod jar (Intel + Apple Silicon)
rem prestige-<ver>.jar the Fabric mod on its own
rem SHA256SUMS.txt
rem Linux and macOS are cross-compiled with cargo-zigbuild + zig; both are installed on first run if missing.
rem Requires: Rust (rustup), Python 3, JDK 21.
setlocal EnableExtensions
cd /d "%~dp0"
set "SELF=%~f0"
set "OUT=%CD%\dist\release"
if exist "C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot" set "JAVA_HOME=C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot"
for /f "tokens=1,* delims==" %%a in ('findstr /b /c:"mod_version=" gradle.properties') do set "VERSION=%%b"
if not defined VERSION set "VERSION=dev"
echo === Prestige %VERSION% release build
rem ---- tools -------------------------------------------------------------
where cargo >nul 2>&1 || (echo cargo not found: install Rust from https://rustup.rs & goto :fail)
where python >nul 2>&1 || (echo python not found: install Python 3 from https://python.org & goto :fail)
python -m ziglang version >nul 2>&1 || (
echo === Installing zig ^(pip ziglang^)
python -m pip install --user ziglang || goto :fail
)
where cargo-zigbuild >nul 2>&1 || (
echo === Installing cargo-zigbuild
cargo install --locked cargo-zigbuild || goto :fail
)
rustup target add x86_64-pc-windows-msvc x86_64-unknown-linux-gnu x86_64-apple-darwin aarch64-apple-darwin || goto :fail
rem zigbuild's linker wrappers break on paths with spaces, so keep its cache on the 8.3 short path
if not exist "%LOCALAPPDATA%\cargo-zigbuild" mkdir "%LOCALAPPDATA%\cargo-zigbuild"
for %%I in ("%LOCALAPPDATA%\cargo-zigbuild") do set "CARGO_ZIGBUILD_CACHE_DIR=%%~sI"
rem ---- payload jar -------------------------------------------------------
echo === Building payload jar
call "%CD%\gradlew.bat" remapJar --console=plain || goto :fail
set "JAR="
for /f "delims=" %%j in ('dir /b /o-d "build\libs\prestige-*.jar" ^| findstr /v /i /c:"-dev.jar" /c:"-sources.jar"') do if not defined JAR set "JAR=%CD%\build\libs\%%j"
if not defined JAR (echo no remapped jar in build\libs & goto :fail)
rem every target embeds this exact jar
set "PRESTIGE_PAYLOAD=%JAR%"
if exist "%OUT%" rmdir /s /q "%OUT%"
mkdir "%OUT%" || goto :fail
rem ---- native builds -----------------------------------------------------
echo === Windows x86_64
cargo build --release --manifest-path injector\Cargo.toml --target x86_64-pc-windows-msvc || goto :fail
call :package windows-x86_64 x86_64-pc-windows-msvc PrestigeInjector.exe prestige_native.dll || goto :fail
echo === Linux x86_64 (glibc 2.17+)
cargo zigbuild --release --manifest-path injector\Cargo.toml --target x86_64-unknown-linux-gnu.2.17 || goto :fail
call :package linux-x86_64 x86_64-unknown-linux-gnu PrestigeInjector libprestige_native.so || goto :fail
echo === macOS universal (x86_64 + arm64)
cargo zigbuild --release --manifest-path injector\Cargo.toml --target universal2-apple-darwin || goto :fail
call :package macos-universal universal2-apple-darwin PrestigeInjector libprestige_native.dylib || goto :fail
copy /y "%JAR%" "%OUT%\" >nul || goto :fail
python scripts\package_release.py checksums "%OUT%" || goto :fail
echo.
echo === Done: %OUT%
dir /b "%OUT%"
call :maybe_pause
exit /b 0
rem %1 platform name, %2 cargo target dir, %3 injector file, %4 library file
:package
python scripts\package_release.py zip "%OUT%" "%VERSION%" %1 "injector\target\%~2\release\%~3" "injector\target\%~2\release\%~4" "%JAR%"
exit /b %ERRORLEVEL%
:fail
echo.
echo *** Release build FAILED
call :maybe_pause
exit /b 1
rem keep the window open when started by double-click
:maybe_pause
echo %cmdcmdline% | find /i "%SELF%" >nul && pause
exit /b 0
@echo off
rem Builds fully offline OpenPrestige bundles.
rem OpenPrestige CLI + native library with embedded payload
rem Requires Rust with MSVC x64/ARM64 tools, Python 3 and JDK 21.
rem Fetches pinned ImGui sources and cross-compiles the small JNI libraries.
setlocal EnableExtensions
cd /d "%~dp0"
set "SELF=%~f0"
set "OUT=%CD%\dist\release"
if exist "C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot" set "JAVA_HOME=C:\Program Files\Eclipse Adoptium\jdk-21.0.12.101-hotspot"
for /f "tokens=1,* delims==" %%a in ('findstr /b /c:"mod_version=" gradle.properties') do set "VERSION=%%b"
if not defined VERSION set "VERSION=dev"
echo === Prestige %VERSION% release build
rem ---- tools -------------------------------------------------------------
where cargo >nul 2>&1 || (echo cargo not found: install Rust from https://rustup.rs & goto :fail)
where python >nul 2>&1 || (echo python not found: install Python 3 from https://python.org & goto :fail)
python -m ziglang version >nul 2>&1 || (
echo === Installing zig ^(pip ziglang^)
python -m pip install --user ziglang==0.16.0 || goto :fail
)
where cargo-zigbuild >nul 2>&1 || (
echo === Installing cargo-zigbuild
cargo install --locked cargo-zigbuild || goto :fail
)
rustup target add x86_64-pc-windows-msvc aarch64-pc-windows-msvc x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu x86_64-apple-darwin aarch64-apple-darwin || goto :fail
rem zigbuild's linker wrappers break on paths with spaces, so keep its cache on the 8.3 short path
if not exist "%LOCALAPPDATA%\cargo-zigbuild" mkdir "%LOCALAPPDATA%\cargo-zigbuild"
for %%I in ("%LOCALAPPDATA%\cargo-zigbuild") do set "CARGO_ZIGBUILD_CACHE_DIR=%%~sI"
rem ---- core ImGui JNI libraries ------------------------------------------
echo === Fetching sources and building small ImGui libraries
python scripts\build_release_imgui.py || goto :fail
rem ---- payload jar -------------------------------------------------------
echo === Building payload jar
call "%CD%\gradlew.bat" bundlePayloads --console=plain || goto :fail
set "JAR=%CD%\build\bundle\common.jar"
set "PRESTIGE_PAYLOAD="
set "PRESTIGE_BUNDLE=%CD%\build\bundle"
if not exist "%OUT%" mkdir "%OUT%" || goto :fail
rem ---- native builds -----------------------------------------------------
call :build windows-x86_64 x86_64-pc-windows-msvc OpenPrestigeInjector.exe prestige_native.dll build || goto :fail
call :build windows-aarch64 aarch64-pc-windows-msvc OpenPrestigeInjector.exe prestige_native.dll build || goto :fail
call :build linux-x86_64 x86_64-unknown-linux-gnu OpenPrestigeInjector libprestige_native.so zigbuild x86_64-unknown-linux-gnu.2.17 || goto :fail
call :build linux-aarch64 aarch64-unknown-linux-gnu OpenPrestigeInjector libprestige_native.so zigbuild aarch64-unknown-linux-gnu.2.17 || goto :fail
call :build macos-universal universal2-apple-darwin OpenPrestigeInjector libprestige_native.dylib zigbuild || goto :fail
rem Standalone Fabric mods are in versions\*\build\libs.
python scripts\package_release.py checksums "%OUT%" || goto :fail
echo.
echo === Done: %OUT%
call :maybe_pause
exit /b 0
rem platform, target directory, executable, library, cargo command, optional versioned target
:build
set "BUILD_TARGET=%~2"
if not "%~6"=="" set "BUILD_TARGET=%~6"
echo === OpenPrestige %~1 (offline)
cargo %~5 --release --manifest-path injector\Cargo.toml --target "%BUILD_TARGET%" || exit /b 1
python scripts\package_release.py offline "%OUT%" "%VERSION%" %~1 "injector\target\%~2\release\%~3" "injector\target\%~2\release\%~4" "%JAR%"
exit /b %ERRORLEVEL%
:fail
echo.
echo *** Release build FAILED
call :maybe_pause
exit /b 1
rem keep the window open when started by double-click
:maybe_pause
echo %cmdcmdline% | find /i "%SELF%" >nul && pause
exit /b 0
+233 -103
View File
@@ -1,103 +1,233 @@
plugins {
id 'net.fabricmc.fabric-loom-remap' version '1.17.21'
}
version = project.mod_version
group = project.maven_group
base {
archivesName = project.archives_base_name
}
loom {
accessWidenerPath = file('src/main/resources/prestige-client.accesswidener')
runs {
client {
client()
ideConfigGenerated(true)
runDir 'run'
programArg '--offlineDeveloperMode'
// dev command file / screenshot facility of the overlay: ./gradlew runClient -PuiCmd=<path>
if (project.hasProperty('uiCmd')) vmArg "-Dprestige.ui.cmd=${project.property('uiCmd')}"
// dev: -PdumpClasses=ap,C,c9 forces class init of instrumented classes (tools/java/ClinitDump.java, bridge/DumpHook)
if (project.hasProperty('dumpClasses')) vmArg "-Dprestige.dump=${project.property('dumpClasses')}"
// engine test driver (engine/EngineDev): ./gradlew runClient -PengineCmd=<command file> [-PengineReport=<seconds>] [-PquickPlay=<world>]
if (project.hasProperty('engineCmd')) vmArg "-Dprestige.engine.cmd=${project.property('engineCmd')}"
if (project.hasProperty('engineReport')) vmArg "-Dprestige.engine.report=${project.property('engineReport')}"
if (project.hasProperty('quickPlay')) { programArg '--quickPlaySingleplayer'; programArg project.property('quickPlay') }
}
}
mods {
"prestige" {
sourceSet sourceSets.main
}
}
}
configurations {
// Libraries copied (unpacked) into the final mod jar so it is self-contained.
shade
implementation.extendsFrom shade
engineMappings
}
repositories {
mavenCentral()
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// Dear ImGui. The binding contains the Java classes, lwjgl3 the GL3/GLFW backend and
// natives-* the imgui-java64 libraries (extracted from the jar at runtime by imgui-java).
// Linux natives are x86_64 only; the macOS dylib is universal (x86_64 + arm64).
shade "io.github.spair:imgui-java-binding:${project.imgui_version}"
// imgui-java-lwjgl3 pulls LWJGL 3.4.1 transitively, which replaces Minecraft's 3.3.3 jars and breaks world saving
shade("io.github.spair:imgui-java-lwjgl3:${project.imgui_version}") { exclude group: 'org.lwjgl' }
shade "io.github.spair:imgui-java-natives-windows:${project.imgui_version}"
shade "io.github.spair:imgui-java-natives-linux:${project.imgui_version}"
shade "io.github.spair:imgui-java-natives-macos:${project.imgui_version}"
// ClassTransform (net.lenni0451, customised build); engine/EnginePlugin uses it to apply the client's @CTransformer hooks.
shade files('libs/classtransform-bundled.jar')
// Yarn tiny shipped as prestige-engine/mappings.tiny for the production (Intermediary) runtime
engineMappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
}
processResources {
inputs.property "version", project.version
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = "UTF-8"
options.release = 21
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
withSourcesJar()
}
jar {
// Unpack the shaded libs (imgui classes + native dll, ClassTransform) into the mod jar.
from({
configurations.shade.collect { it.isDirectory() ? it : zipTree(it) }
}) {
exclude 'META-INF/MANIFEST.MF', 'META-INF/*.SF', 'META-INF/*.RSA', 'META-INF/*.DSA'
exclude 'module-info.class', 'META-INF/versions/**'
}
from({ zipTree(configurations.engineMappings.singleFile) }) {
include 'mappings/mappings.tiny'
eachFile { it.relativePath = new RelativePath(true, 'prestige-engine', 'mappings.tiny') }
includeEmptyDirs = false
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
plugins {
id 'net.fabricmc.fabric-loom-remap' version '1.17.21'
}
version = "${project.mod_version}+${project.minecraft_version}"
group = project.maven_group
base {
archivesName = project.archives_base_name
}
def accessWidener = stonecutter.eval(stonecutter.current.version, '>=1.21.11')
? 'prestige-client.accesswidener' : 'prestige-client-legacy.accesswidener'
loom {
accessWidenerPath = rootProject.file("src/main/resources/${accessWidener}")
runs {
client {
client()
ideConfigGenerated(true)
runDir 'run'
programArg '--offlineDeveloperMode'
// dev command file / screenshot facility of the overlay: ./gradlew runClient -PuiCmd=<path>
if (project.hasProperty('uiCmd')) vmArg "-Dprestige.ui.cmd=${project.property('uiCmd')}"
// dev: -PdumpClasses=ap,C,c9 forces class init of instrumented classes (tools/java/ClinitDump.java, bridge/DumpHook)
if (project.hasProperty('dumpClasses')) vmArg "-Dprestige.dump=${project.property('dumpClasses')}"
// engine test driver (engine/EngineDev): ./gradlew runClient -PengineCmd=<command file> [-PengineReport=<seconds>] [-PquickPlay=<world>]
if (project.hasProperty('engineCmd')) vmArg "-Dprestige.engine.cmd=${project.property('engineCmd')}"
if (project.hasProperty('engineReport')) vmArg "-Dprestige.engine.report=${project.property('engineReport')}"
if (project.hasProperty('quickPlay')) { programArg '--quickPlaySingleplayer'; programArg project.property('quickPlay') }
}
}
mods {
"prestige" {
sourceSet sourceSets.main
}
}
}
configurations {
// Libraries copied (unpacked) into the final mod jar so it is self-contained.
shade
implementation.extendsFrom shade
engineMappings
}
repositories {
mavenCentral()
}
dependencies {
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// Dear ImGui. The binding contains the Java classes, lwjgl3 the GL3/GLFW backend and
// natives-* the imgui-java64 libraries (extracted from the jar at runtime by imgui-java).
// Linux natives are x86_64 only; the macOS dylib is universal (x86_64 + arm64).
shade "io.github.spair:imgui-java-binding:${project.imgui_version}"
// imgui-java-lwjgl3 pulls LWJGL 3.4.1 transitively, which replaces Minecraft's 3.3.3 jars and breaks world saving
shade("io.github.spair:imgui-java-lwjgl3:${project.imgui_version}") { exclude group: 'org.lwjgl' }
shade "io.github.spair:imgui-java-natives-windows:${project.imgui_version}"
shade "io.github.spair:imgui-java-natives-linux:${project.imgui_version}"
shade "io.github.spair:imgui-java-natives-macos:${project.imgui_version}"
// ClassTransform (net.lenni0451, customised build); engine/EnginePlugin uses it to apply the client's @CTransformer hooks.
shade files(rootProject.file('libs/classtransform-bundled.jar'))
// Yarn tiny shipped as prestige-engine/mappings.tiny for the production (Intermediary) runtime
engineMappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
}
processResources {
exclude { it.name.endsWith('.accesswidener') && it.name != accessWidener }
inputs.property "version", project.version
inputs.property "minecraft_version", project.minecraft_version
filteringCharset "UTF-8"
filesMatching("fabric.mod.json") {
expand "version": project.version, "minecraft_version": project.minecraft_version, "access_widener": accessWidener
}
filesMatching("prestige-engine/minecraft-version.txt") {
expand "minecraft_version": project.minecraft_version
}
if (stonecutter.eval(stonecutter.current.version, '<1.21.11')) {
doLast {
def manifestFile = new File(destinationDir, 'prestige_ui/manifest_live.json')
def manifest = new groovy.json.JsonSlurper().parse(manifestFile)
def unavailable = manifest.modules.findAll { it['class'].contains('.module.spear.') }.collect { it.name }.toSet()
manifest.modules.removeAll { unavailable.contains(it.name) }
manifestFile.text = groovy.json.JsonOutput.toJson(manifest)
['modules.tsv', 'settings.tsv'].each { name ->
def table = new File(destinationDir, "prestige_ui/${name}")
table.text = table.readLines('UTF-8').findAll { row ->
!unavailable.contains(row.split('\t', -1)[name == 'modules.tsv' ? 1 : 0])
}.join('\n') + '\n'
}
}
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = "UTF-8"
options.release = 21
options.compilerArgs += ['-Xmaxerrs', '1000']
}
// Each version's compiled transformer annotations own the target set. Generate
// anchors from them so renamed/merged game classes cannot leave stale targets.
def engineSources = layout.buildDirectory.dir('generated/engine/java')
def engineResources = layout.buildDirectory.dir('generated/engine/resources')
def generateEngineMetadata = tasks.register('generateEngineMetadata') {
dependsOn tasks.named('compileJava')
inputs.files(tasks.named('compileJava').flatMap { it.destinationDirectory })
inputs.files(configurations.engineMappings)
outputs.dirs(engineSources, engineResources)
doLast {
def namedToIntermediary = [:]
new java.util.zip.ZipFile(configurations.engineMappings.singleFile).withCloseable { zip ->
zip.getInputStream(zip.getEntry('mappings/mappings.tiny')).withReader('UTF-8') { reader ->
reader.eachLine { line ->
def fields = line.split('\t')
if (fields[0] == 'c') namedToIntermediary[fields[2]] = fields[1]
}
}
}
def targets = new TreeSet<String>()
def transformers = new TreeSet<String>()
fileTree(tasks.named('compileJava').get().destinationDirectory).matching {
include 'dev/zprestige/prestige/mixin/*.class'
}.each { file ->
def node = new org.objectweb.asm.tree.ClassNode()
new org.objectweb.asm.ClassReader(file.bytes).accept(node, org.objectweb.asm.ClassReader.SKIP_CODE)
def annotation = (node.visibleAnnotations ?: []).find { it.desc == 'Lnet/lenni0451/classtransform/annotations/CTransformer;' }
if (annotation == null) annotation = (node.invisibleAnnotations ?: []).find { it.desc == 'Lnet/lenni0451/classtransform/annotations/CTransformer;' }
if (annotation != null) {
transformers.add(node.name.replace('/', '.'))
def values = annotation.values
for (int i = 0; i < values.size(); i += 2) {
if (values[i] == 'value') values[i + 1].each { targets.add(it.internalName) }
if (values[i] == 'name') values[i + 1].each { targets.add(it.replace('.', '/')) }
}
}
}
def sourceRoot = engineSources.get().asFile
def sources = new File(sourceRoot, 'dev/zprestige/prestige/engine/mixin')
def resources = new File(engineResources.get().asFile, 'prestige-engine')
assert sourceRoot.canonicalPath.startsWith(layout.buildDirectory.get().asFile.canonicalPath + File.separator)
delete sourceRoot
sources.mkdirs()
resources.mkdirs()
def named = targets.toList()
def intermediary = named.collect { target ->
if (!namedToIntermediary.containsKey(target)) throw new GradleException("No intermediary mapping for ${target}")
namedToIntermediary[target]
}
['N': named, 'I': intermediary].each { prefix, names ->
names.eachWithIndex { target, index ->
def name = String.format('%s%02d', prefix, index)
new File(sources, "${name}.java").text = """package dev.zprestige.prestige.engine.mixin;
@org.spongepowered.asm.mixin.Mixin(targets = "${target.replace('/', '.')}", remap = false, priority = 2000)
public abstract class ${name} {}
"""
}
}
new File(resources, 'targets.named.list').text = named.collect { it.replace('/', '.') }.join('\n') + '\n'
new File(resources, 'targets.intermediary.list').text = intermediary.collect { it.replace('/', '.') }.join('\n') + '\n'
new File(resources, 'transformers.list').text = transformers.join('\n') + '\n'
}
}
def compileEngineAnchors = tasks.register('compileEngineAnchors', JavaCompile) {
dependsOn generateEngineMetadata
source engineSources
classpath = sourceSets.main.compileClasspath
destinationDirectory = layout.buildDirectory.dir('classes/engine')
}
sourceSets.main.output.dir(engineResources, builtBy: generateEngineMetadata)
sourceSets.main.output.dir(compileEngineAnchors.flatMap { it.destinationDirectory }, builtBy: compileEngineAnchors)
processResources {
exclude 'prestige-engine/targets.named.list', 'prestige-engine/targets.intermediary.list', 'prestige-engine/transformers.list'
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
withSourcesJar()
}
tasks.named('sourcesJar') {
dependsOn generateEngineMetadata
from engineSources
}
// Applied scripts do not inherit plugin implementation classes; pass ASM operations
// from Loom's existing classpath instead of adding another dependency.
ext.hookAsm = [
node: { new org.objectweb.asm.tree.ClassNode() },
reader: { data -> new org.objectweb.asm.ClassReader(data) },
arguments: { descriptor -> org.objectweb.asm.Type.getArgumentTypes(descriptor).toList() },
methodInstruction: { instruction -> instruction instanceof org.objectweb.asm.tree.MethodInsnNode }
]
apply from: rootProject.file('gradle/hook-check.gradle')
jar {
// Optional custom native builds take precedence over the upstream binaries.
from(rootProject.file('build/core-natives')) {
into 'prestige-natives'
}
from(rootProject.file('build/arm-natives')) {
into 'prestige-natives'
}
// Unpack the shaded libs (imgui classes + native dll, ClassTransform) into the mod jar.
from({
configurations.shade.collect { it.isDirectory() ? it : zipTree(it) }
}) {
exclude 'META-INF/MANIFEST.MF', 'META-INF/*.SF', 'META-INF/*.RSA', 'META-INF/*.DSA'
exclude 'module-info.class', 'META-INF/versions/**'
exclude 'imgui/extension/**'
if (rootProject.file('build/core-natives/windows-x86_64/imgui-java64.dll').isFile()) {
exclude 'io/imgui/java/native-bin/imgui-java64.dll'
}
if (rootProject.file('build/core-natives/linux-x86_64/libimgui-java64.so').isFile()) {
exclude 'io/imgui/java/native-bin/libimgui-java64.so'
}
if (rootProject.file('build/core-natives/macos-universal/libimgui-java64.dylib').isFile()) {
exclude 'io/imgui/java/native-bin/libimgui-java64.dylib'
}
}
from({ zipTree(configurations.engineMappings.singleFile) }) {
include 'mappings/mappings.tiny'
eachFile { it.relativePath = new RelativePath(true, 'prestige-engine', 'mappings.tiny') }
includeEmptyDirs = false
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
+45
View File
@@ -0,0 +1,45 @@
"""Run with python check/bundle_payloads_check.py."""
import importlib.util
import tempfile
import zipfile
from pathlib import Path
spec = importlib.util.spec_from_file_location('bundle_payloads', Path(__file__).resolve().parents[1] / 'scripts/bundle_payloads.py')
bundle = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bundle)
def entries(path):
with zipfile.ZipFile(path) as jar:
return {name: jar.read(name) for name in jar.namelist()}
test_root = Path(__file__).resolve().parents[1] / 'work'
test_root.mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=test_root) as temporary:
directory = Path(temporary)
inputs = {}
for version in ('1.21.1', '1.21.11'):
path = directory / f'input-{version}.jar'
with zipfile.ZipFile(path, 'w') as jar:
jar.writestr('prestige-engine/minecraft-version.txt', version)
jar.writestr('imgui/ImGui.class', b'shared library')
jar.writestr('library/Different.class', version.encode())
jar.writestr('dev/zprestige/Prestige.class', b'keep game code local')
jar.writestr('fabric.mod.json', b'keep metadata local')
inputs[version] = path
output = directory / 'output'
bundle.pack(inputs, output)
common = entries(output / 'common.jar')
assert common == {'imgui/ImGui.class': b'shared library'}
for version, original in inputs.items():
variant = entries(output / f'{version}.jar')
assert not common.keys() & variant.keys()
assert common | variant == entries(original), 'Split must reconstruct every original entry exactly'
try:
bundle.pack({'1.21.2': inputs['1.21.1']}, directory / 'bad')
except ValueError:
pass
else:
raise AssertionError('Mismatched payload target accepted')
print('Bundle reconstruction and target checks passed')
@@ -0,0 +1,70 @@
package dev.zprestige.prestige.engine;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import net.lenni0451.classtransform.utils.tree.IClassProvider;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
/** Exercises an actual resource-less generated class without requiring native injection. */
public final class ResourceClassProviderCheck {
public static void main(String[] args) throws Exception {
String name = "prestige.check.GeneratedLocalRef";
String internal = name.replace('.', '/');
ClassWriter writer = new ClassWriter(0);
writer.visit(Opcodes.V21, Opcodes.ACC_PUBLIC, internal, null, "java/lang/Object", null);
MethodVisitor init = writer.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
init.visitCode();
init.visitTypeInsn(Opcodes.NEW, "java/lang/AssertionError");
init.visitInsn(Opcodes.DUP);
init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/AssertionError", "<init>", "()V", false);
init.visitInsn(Opcodes.ATHROW);
init.visitMaxs(2, 0);
init.visitEnd();
writer.visitEnd();
byte[] definition = writer.toByteArray();
class GeneratedLoader extends ClassLoader {
GeneratedLoader() { super(ResourceClassProviderCheck.class.getClassLoader()); }
Class<?> define() { return defineClass(name, definition, 0, definition.length); }
}
GeneratedLoader loader = new GeneratedLoader();
Class<?> generated = loader.define();
if (loader.getResourceAsStream(internal + ".class") != null) throw new AssertionError("fixture has a resource");
AtomicInteger calls = new AtomicInteger();
Function<Class<?>, byte[]> live = type -> {
calls.incrementAndGet();
if (type != generated) throw new AssertionError("wrong generated class");
return definition;
};
IClassProvider provider = provider(loader, null, live);
if (!Arrays.equals(definition, provider.getClass(name))) throw new AssertionError("wrong live bytes");
provider.getClass("java.lang.String");
if (calls.get() != 1) throw new AssertionError("resource-backed classes must not use live capture");
String tiny = "tiny\t2\t0\tintermediary\tnamed\nc\t" + internal + "\tprestige/check/NamedLocalRef\n";
if (!Arrays.equals(definition, provider(loader, tiny.getBytes(StandardCharsets.UTF_8), live)
.getClass("prestige.check.NamedLocalRef"))) throw new AssertionError("mapped fallback failed");
rejects(provider(loader, null, null), name);
rejects(provider(loader, null, type -> null), name);
rejects(provider(loader, null, type -> new byte[0]), name);
rejects(provider(loader, null, live), "prestige.check.MissingClass");
System.out.println("Generated-class resource fallback checks passed (class was not initialized)");
}
private static IClassProvider provider(ClassLoader loader, byte[] tiny, Function<Class<?>, byte[]> live) throws Exception {
Class<?> type = Class.forName("dev.zprestige.prestige.engine.EnginePlugin$ResourceClassProvider");
Constructor<?> constructor = type.getDeclaredConstructor(ClassLoader.class, Set.class, byte[].class, Function.class);
constructor.setAccessible(true);
return (IClassProvider) constructor.newInstance(loader, Set.of(), tiny, live);
}
private static void rejects(IClassProvider provider, String name) throws Exception {
try { provider.getClass(name); }
catch (ClassNotFoundException expected) { return; }
throw new AssertionError("accepted unavailable bytes for " + name);
}
}
@@ -0,0 +1,28 @@
package dev.zprestige.prestige.inject;
/** JDK-only check; no game, Fabric runtime or native injection required. */
public final class MinecraftTargetCheck {
public static void main(String[] args) {
for (int patch = 1; patch <= 11; patch++) {
String target = "1.21." + patch;
MinecraftTarget.require(target, target);
for (int other = 1; other <= 11; other++) {
if (patch != other) rejects(target, "1.21." + other);
}
}
rejects("1.21.11", "1.21.11-pre1");
rejects("1.21.11", "1.21.110");
rejects("", "");
System.out.println("Minecraft target checks passed");
}
private static void rejects(String target, String actual) {
try {
MinecraftTarget.require(target, actual);
} catch (IllegalStateException expected) {
if (!expected.getMessage().contains(actual)) throw new AssertionError(expected);
return;
}
throw new AssertionError("Accepted mismatched target " + target + " / " + actual);
}
}
+17
View File
@@ -0,0 +1,17 @@
// Run with: gradlew -I check/resource-provider.gradle resourceProviderCheck
gradle.projectsEvaluated {
def project = gradle.rootProject.project(':1.21.11')
def compileCheck = project.tasks.register('compileResourceProviderCheck', JavaCompile) {
dependsOn project.tasks.named('classes')
source project.rootProject.file('check/dev/zprestige/prestige/engine/ResourceClassProviderCheck.java')
classpath = project.sourceSets.main.runtimeClasspath
destinationDirectory = project.layout.buildDirectory.dir('checks/resource-provider')
options.release = 21
options.encoding = 'UTF-8'
}
project.tasks.register('resourceProviderCheck', JavaExec) {
dependsOn compileCheck
classpath = project.files(compileCheck.flatMap { it.destinationDirectory }) + project.sourceSets.main.runtimeClasspath
mainClass = 'dev.zprestige.prestige.engine.ResourceClassProviderCheck'
}
}
+2 -3
View File
@@ -1,10 +1,9 @@
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
org.gradle.workers.max=2
dev.kikugie.stonecutter.hard_mode=true
# Fabric (https://modmuss50.me/fabric.html)
minecraft_version=1.21.11
yarn_mappings=1.21.11+build.4
loader_version=0.19.2
fabric_version=0.141.6+1.21.11
# Mod
mod_version=0.1.0
maven_group=dev.prestige
+94
View File
@@ -0,0 +1,94 @@
// Compile-time Java checks cannot see the string descriptors used by ClassTransform.
tasks.register('validateHooks') {
dependsOn tasks.named('compileJava')
inputs.files(tasks.named('compileJava').flatMap { it.destinationDirectory }, sourceSets.main.compileClasspath)
def report = layout.buildDirectory.file('reports/hooks.txt')
outputs.file(report)
doLast {
def jars = sourceSets.main.compileClasspath.files.findAll { it.name.endsWith('.jar') }
.collect { new java.util.zip.ZipFile(it) }
try {
def cache = [:]
Closure readClass = { String name ->
if (cache.containsKey(name)) return cache[name]
def zip = jars.find { it.getEntry("${name}.class") != null }
if (zip == null) return null
def node = hookAsm.node()
hookAsm.reader(zip.getInputStream(zip.getEntry("${name}.class"))).accept(node, 0)
cache[name] = node
node
}
def annotations = { node -> (node.visibleAnnotations ?: []) + (node.invisibleAnnotations ?: []) }
def properties = { annotation ->
def result = [:]
def values = annotation.values ?: []
for (int i = 0; i < values.size(); i += 2) result[values[i]] = values[i + 1]
result
}
def errors = []
int handlers = 0
fileTree(tasks.named('compileJava').get().destinationDirectory).matching {
include 'dev/zprestige/prestige/mixin/*.class', 'dev/zprestige/prestige/inject/hooks/*.class'
}.each { file ->
def hook = hookAsm.node()
hookAsm.reader(file.bytes).accept(hook, 0)
def transformer = annotations(hook).find { it.desc.endsWith('/CTransformer;') }
if (transformer == null) return
def targets = properties(transformer).value.collect { readClass(it.internalName) }
if (targets.any { it == null }) errors.add("${hook.name}: missing target class")
targets.findAll { it != null }.each { target ->
hook.fields.each { field ->
def shadow = annotations(field).find { it.desc.endsWith('/CShadow;') }
if (shadow != null) {
def name = properties(shadow).value ?: field.name
def owner = target
def found = false
while (owner != null && !found) {
found = owner.fields.any { it.name == name && it.desc == field.desc }
owner = found ? null : readClass(owner.superName)
}
if (!found) errors.add("${hook.name}.${field.name}: missing shadow ${target.name}.${name} ${field.desc}")
}
}
hook.methods.each { method ->
annotations(method).findAll { it.desc.contains('/annotations/injection/') }.each { annotation ->
def config = properties(annotation)
(config.method ?: []).each { selector ->
def matches = target.methods.findAll {
selector.contains('(') ? it.name + it.desc == selector : it.name == selector
}
handlers++
if (matches.isEmpty()) errors.add("${hook.name}.${method.name}: missing ${target.name}.${selector}")
if (annotation.desc.endsWith('/CInject;')) {
def parameters = hookAsm.arguments(method.desc).toList()
if (parameters && parameters.last().descriptor == 'Lnet/lenni0451/classtransform/InjectionCallback;') parameters.removeLast()
if (parameters && !matches.any { hookAsm.arguments(it.desc).toList() == parameters }) {
errors.add("${hook.name}.${method.name}: callback parameters ${parameters} do not match ${target.name}.${selector} ${matches.collect { it.desc }}")
}
}
def points = config.target instanceof List ? config.target : config.target ? [config.target] : []
points.each { point ->
def injection = properties(point)
if (injection.value == 'INVOKE') {
def expected = injection.target
def found = matches.any { candidate -> candidate.instructions.any { instruction ->
hookAsm.methodInstruction(instruction) && "L${instruction.owner};${instruction.name}${instruction.desc}" == expected
} }
if (!found) errors.add("${hook.name}.${method.name}: missing invocation ${expected} in ${target.name}.${selector}")
}
}
}
}
}
}
}
report.get().asFile.parentFile.mkdirs()
report.get().asFile.text = "Checked ${handlers} handlers for Minecraft ${project.minecraft_version}\n" + errors.join('\n') + '\n'
if (errors) throw new GradleException("${errors.size()} hook compatibility errors; see ${report.get().asFile}")
logger.lifecycle("Verified ${handlers} hook handlers for Minecraft ${project.minecraft_version}")
} finally {
jars.each { it.close() }
}
}
}
tasks.named('check') { dependsOn tasks.named('validateHooks') }
+1 -1
View File
@@ -3,7 +3,7 @@
version = 4
[[package]]
name = "prestige-injector"
name = "openprestige-injector"
version = "0.1.0"
[[package]]
+74 -74
View File
@@ -1,96 +1,96 @@
# Prestige injector (Rust)
# OpenPrestige offline injector
`PrestigeInjector` loads the native loader library (`prestige_native.dll` / `libprestige_native.so` / `libprestige_native.dylib`)
into a running Minecraft **1.21.11 Fabric** JVM (64-bit, Fabric Loader 0.19.x, Fabric API installed). It uses the same overall
method as the openvape bundle, written from scratch in Rust with no external crates.
## Supported platforms
| OS | Architectures | Injector binary | Loader library |
|---------|--------------------|-----------------------|-----------------------------|
| Windows | x86_64 | `PrestigeInjector.exe`| `prestige_native.dll` |
| Linux | x86_64 | `PrestigeInjector` | `libprestige_native.so` |
| macOS | x86_64, arm64 | `PrestigeInjector` | `libprestige_native.dylib` |
The injector and library must be built for the same architecture as the target JVM.
## How it works
1. **Injector** lists the running Fabric client JVMs, then loads the library into the chosen process.
- **Windows:** lists visible `java.exe`/`javaw.exe` windows (refreshed every 750 ms), then runs `LoadLibraryW` in the chosen
process through `CreateRemoteThread` and confirms the module is mapped.
- **Linux / macOS:** uses the HotSpot attach protocol (the same mechanism as `jcmd <pid> JVMTI.agent_load`). The injector
creates `.attach_pid<pid>` and sends `SIGQUIT` to the JVM, connects to its attach socket (`/tmp/.java_pid<pid>`, under
`$TMPDIR` on macOS) and asks it to load the library. The JVM `dlopen`s `libprestige_native` and calls its
`Agent_OnAttach` entry point. No ptrace, no root, no per-architecture shellcode.
Processes are found via `/proc` (Linux) or `ps` (macOS); there are no window titles, so the picker shows the pid and
instance name.
2. **The native library** only spawns a worker thread from its entry point (`DllMain` on Windows, `Agent_OnAttach` on
unix, which also hands over the `JavaVM*`). The worker:
- waits for the JVM (Windows: `jvm.dll`, `JNI_GetCreatedJavaVMs`), attaches, acquires the JVMTI redefine/retransform capabilities;
- writes the embedded payload jar (the remapped `prestige-*.jar`) to the temp directory under `PrestigeLoader`;
- `FabricLauncherBase.getLauncher().addToClassPath(jar)` so payload and game classes share the Knot class loader;
- registers `NativeBridge.classBytes` / `NativeBridge.redefine` and calls `Bootstrap.start()`.
3. **`Bootstrap`** (Java) waits for the client window, then for every ClassTransform hook target gets the current class bytes
(JVMTI retransform capture), runs the hooks through `InPlaceTransformer` and redefines the class. The bundled ClassTransform
inlines hook handlers into the target methods, so normally nothing is added to the class and a plain redefine works. If a
transformer ever does add methods (a running JVM cannot), they are moved into generated `dev.zprestige.prestige.hooks.H*`
helper classes, call sites become `invokestatic`, and private member access goes through `Access` MethodHandles.
Finally the Prestige and ClickGUI entrypoints run on the client thread.
This repository contains the original CLI injector, native library with embedded payload and game
sources. The graphical launcher and runtime downloader are maintained in the separate Prestige
repository. There is no GUI or HTTP dependency in this injector and no edition build flag.
## Build
The payload jar is embedded with `include_bytes!`, so each target needs its own build. Both scripts below build for the host OS only and run
`gradlew remapJar`, `cargo build --release`, and copy the results to `dist/`.
Run `build-injector.ps1` on Windows or `build-injector.sh` on Linux/macOS. Both build the Fabric JAR,
then the native library and CLI, collecting the results and a host ZIP in `dist/`.
Stonecutter compiles every target from 1.21.1 through 1.21.11. `bundlePayloads`
requires every variant to build and pass access-widener and hook checks before
splitting the JARs into `build/bundle/common.jar` and eleven exact-version payloads.
The native library embeds those files, sharing byte-identical libraries and assets
once. Versioned game classes, hooks, mappings, and metadata stay in each payload.
Standalone Fabric mods are available in `versions/<minecraft>/build/libs/`.
```powershell
.\build-injector.ps1 # Windows: dist\PrestigeInjector.exe + dist\prestige_native.dll
Run `build-release.bat` on Windows to build all platforms. `dist/release/` contains:
```text
openprestige-<version>-windows-x86_64.zip
openprestige-<version>-windows-aarch64.zip
openprestige-<version>-linux-x86_64.zip
openprestige-<version>-linux-aarch64.zip
openprestige-<version>-macos-universal.zip
SHA256SUMS.txt
```
```sh
./build-injector.sh # Linux/macOS: dist/PrestigeInjector + dist/libprestige_native.{so,dylib}
```
To build release zips for every platform from Windows, run `build-release.bat`. It cross-compiles Linux (x86_64,
glibc 2.17+, so one build covers every mainstream distro) and macOS (universal x86_64 + arm64) with `cargo-zigbuild`, installing
zig and cargo-zigbuild on first run, and writes `dist\release\prestige-<ver>-{windows-x86_64,linux-x86_64,macos-universal}.zip`,
the bare mod jar and `SHA256SUMS.txt`.
Set `JAVA_HOME` beforehand to choose the JDK for Gradle (`build-injector.sh` honours it). The GitHub Actions workflow
`.github/workflows/injector.yml` builds and tests all four targets (Windows x86_64, Linux x86_64, macOS x86_64, macOS arm64)
and uploads them as artifacts.
Each ZIP contains `OpenPrestigeInjector` (or `.exe`), the native library, and a README.
The CI injector workflow builds only OpenPrestige. Build dependencies require internet access;
the resulting release bundle needs no runtime downloads.
## Use
Start a Fabric 1.21.11 instance, then run:
Extract the complete platform ZIP, start Minecraft, then run:
```sh
PrestigeInjector # interactive: pick the game from the list
PrestigeInjector <pid> [lib path] # inject into a specific pid, optionally with an explicit library path
OpenPrestigeInjector # Up/Down selects, Enter injects, Esc quits
OpenPrestigeInjector <pid> [lib path] # optional explicit library path
```
On Windows this is `PrestigeInjector.exe`. By default the library is looked up beside the injector.
Keep the native library beside the executable. The CLI uses that library and never looks in
Prestige's downloaded runtime cache. It has no update checks or `--download` command.
The library reads Fabric metadata, rejects unsupported targets, then extracts the
shared JAR and only the matching version payload so the JVM can load them. No external JAR is needed for
injection. Linux/macOS require a terminal, the same user as the game, and JVM attach enabled.
## Install as a mod instead
## Platforms and requirements
The payload jar is also a normal Fabric mod. Put `prestige-*.jar` (from `dist/` or the CI `payload-jar` artifact) in the
`mods/` folder of a Fabric Loader 0.19+ / Fabric API / Minecraft 1.21.11 instance; no injector is needed, on any OS.
Do not use both: if the mod is already loaded, the injector's bootstrap logs "already loaded as a Fabric mod" and skips.
Windows and Linux support x86_64 and ARM64. macOS supports Intel and Apple Silicon.
The injector, library and JVM architectures must match. ARM64 execution needs hardware testing.
The game code targets Minecraft 1.21.1 through 1.21.11 Fabric, Fabric Loader 0.19+
and a Fabric API build matching the game. Spear modules are included only on 1.21.11.
## Requirements (Linux / macOS)
Build tools require Rust, Python 3 and JDK 21. On Windows, the full release build also requires
MSVC build tools for x64 and ARM64. `build-release.bat` fetches pinned ImGui sources and builds
the small JNI libraries before building the remapped JAR. It installs Zig and cargo-zigbuild if
needed, then cross-compiles Linux x64/ARM64 and universal macOS.
- Run the injector as the **same user** as the game.
- The attach mechanism must be enabled: the game must not be started with `-XX:+DisableAttachMechanism`.
- The JVM architecture must match the injector build. On Apple Silicon use an arm64 JVM, or use the x86_64 build for JVMs
running under Rosetta.
- Sandboxed launchers (Flatpak, Snap) hide the attach socket and are not supported.
Both repositories currently start from the same game sources and use the compatible `.openprestige`
configuration and log locations. They are independent repositories, without submodules, shared
working files or edition build flags. Game code fixes must be ported between repositories explicitly.
## Known limits
## User data
- On Linux/macOS the library stays loaded after self-destruct: hooks are removed and natives unregistered, but the library is
not `dlclose`d (unmapping code the thread is still returning into would crash the JVM). On Windows the library is freed.
- Linux and macOS support is compile-checked in CI; test on a real host before relying on it.
| OS | Location |
| --- | --- |
| Windows | `%APPDATA%\.openprestige` |
| macOS | `~/Library/Application Support/.openprestige` |
| Linux | `$XDG_DATA_HOME/.openprestige` or `~/.local/share/.openprestige` |
## Log
Configs live in `configs/`, logs in `logs/`, and local runtime files in `runtime/`.
`prestige-native.log` is written beside the loader library, plus `[Prestige-Inject]` lines in the game log.
## Developer checks
```powershell
./gradlew validateHooks
python check/bundle_payloads_check.py
python scripts/test_release.py
./gradlew -I check/resource-provider.gradle :1.21.11:resourceProviderCheck
```
`validateHooks` checks target classes, shadow fields, method selectors, callback
parameters, and invocation targets against each version's mapped game bytecode.
Engine anchor classes and target lists are generated from compiled transformer
annotations and that version's Yarn mappings.
Normal Cargo builds require the complete `build/bundle` directory. Set
`PRESTIGE_BUNDLE` to use a different complete bundle directory. An explicit
`PRESTIGE_PAYLOAD=<fat-remapped.jar>` remains available for single-target developer
builds, with the Java exact-target guard retained. There is no newest-JAR fallback.
Windows-only native loading smoke tests can use the existing engine command file
with `loadnative <absolute DLL path>`, followed by `wait 40` and `exit`. In a dev
client already running Prestige as a Fabric mod, bootstrap skips installing a
second set of hooks. This exercises native metadata lookup and payload selection.
+2 -2
View File
@@ -1,8 +1,8 @@
[package]
name = "prestige-injector"
name = "openprestige-injector"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "PrestigeInjector"
name = "OpenPrestigeInjector"
path = "src/main.rs"
+11
View File
@@ -0,0 +1,11 @@
fn main() {
let properties = "../../../gradle.properties";
println!("cargo:rerun-if-changed={properties}");
let contents = std::fs::read_to_string(properties).expect("read gradle.properties");
let version = contents
.lines()
.find_map(|line| line.strip_prefix("mod_version="))
.expect("mod_version is required")
.trim();
println!("cargo:rustc-env=PRESTIGE_VERSION={version}");
}
+171 -85
View File
@@ -1,10 +1,12 @@
//! PrestigeInjector: lists the running Minecraft (javaw/java) processes and loads the native library
//! OpenPrestigeInjector: lists the running Minecraft (javaw/java) processes and loads the native library
//! (prestige_native.dll / libprestige_native.so / libprestige_native.dylib) into the selected one: a remote LoadLibraryW
//! thread on Windows, the HotSpot attach protocol on Linux and macOS. The library does everything else once it is inside
//! the JVM; the injector tails its log so every stage (transforming, injecting, initialising) is visible.
//!
//! PrestigeInjector interactive process picker (Up/Down, Enter, Esc)
//! PrestigeInjector <pid> [lib path] non-interactive
//! OpenPrestigeInjector interactive process picker (Up/Down, Enter, Esc)
//! OpenPrestigeInjector <pid> [lib path] non-interactive
#[path = "../../paths.rs"]
mod paths;
mod platform;
use std::fs;
@@ -15,7 +17,6 @@ use std::time::{Duration, Instant};
/// The one credit line, shown once at the top of the screen.
const CREDIT: &str = "Cracked by Skid Solutions - https://discord.gg/x2FJyGrDNg";
const INVITE_URL: &str = "https://discord.gg/x2FJyGrDNg";
/// How long to follow the DLL's progress after it has been loaded.
const FOLLOW_TIMEOUT: Duration = Duration::from_secs(180);
@@ -26,11 +27,15 @@ const GREEN: &str = "\x1b[92m";
const YELLOW: &str = "\x1b[93m";
const RED: &str = "\x1b[91m";
fn default_dll() -> PathBuf {
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|dir| dir.join(platform::LIB_NAME)))
.unwrap_or_else(|| PathBuf::from(platform::LIB_NAME))
fn prepare_runtime(_offline: bool, _ask_for_updates: bool) -> Result<PathBuf, String> {
let path = std::env::current_exe()
.map_err(|error| error.to_string())?
.with_file_name(platform::LIB_NAME);
if path.is_file() {
Ok(path)
} else {
Err(format!("OpenPrestige requires {} beside the CLI executable. Extract the complete offline bundle.", platform::LIB_NAME))
}
}
fn banner() -> String {
@@ -38,26 +43,53 @@ fn banner() -> String {
out.push_str(&format!("{CYAN} ___ ___ ___ ___ _____ ___ ___ ___ \n"));
out.push_str(" | _ \\ _ \\ __/ __|_ _|_ _/ __| __|\n");
out.push_str(" | _/ / _|\\__ \\ | | | | (_ | _| \n");
out.push_str(&format!(" |_| |_|_\\___|___/ |_| |___\\___|___|{RESET} injector\n"));
out.push_str(&format!(
" |_| |_|_\\___|___/ |_| |___\\___|___|{RESET} injector\n"
));
out.push_str(&format!("{YELLOW} {CREDIT}{RESET}\n\n"));
out.push_str("OpenPrestige - offline CLI\n\n");
out
}
fn step(label: &str, message: &str) {
println!("{DIM}[{:>7}]{RESET} {CYAN}{label:<12}{RESET} {message}", clock());
println!(
"{DIM}[{:>7}]{RESET} {CYAN}{label:<12}{RESET} {message}",
clock()
);
log_launcher(label, message);
}
fn ok(label: &str, message: &str) {
println!("{DIM}[{:>7}]{RESET} {GREEN}{label:<12}{RESET} {message}", clock());
println!(
"{DIM}[{:>7}]{RESET} {GREEN}{label:<12}{RESET} {message}",
clock()
);
log_launcher(label, message);
}
fn fail(label: &str, message: &str) {
println!("{DIM}[{:>7}]{RESET} {RED}{label:<12}{RESET} {message}", clock());
println!(
"{DIM}[{:>7}]{RESET} {RED}{label:<12}{RESET} {message}",
clock()
);
log_launcher(label, message);
}
fn log_launcher(label: &str, message: &str) {
let path = paths::root()
.join("logs")
.join(format!("launcher-{}.log", std::process::id()));
if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(file, "[{}] {label} {message}", clock());
}
}
/// Seconds since the injector started, for the log prefix.
fn clock() -> String {
use std::sync::OnceLock;
static START: OnceLock<Instant> = OnceLock::new();
format!("{:.1}s", START.get_or_init(Instant::now).elapsed().as_secs_f32())
format!(
"{:.1}s",
START.get_or_init(Instant::now).elapsed().as_secs_f32()
)
}
fn main() -> ExitCode {
@@ -70,27 +102,47 @@ fn real_main() -> ExitCode {
platform::enable_ansi();
let _ = clock();
let args: Vec<String> = std::env::args().skip(1).collect();
let interactive = args.is_empty();
if let Err(error) = paths::initialize() {
fail("storage", &error.to_string());
return ExitCode::from(1);
}
let interactive = args.is_empty()
|| matches!(args.as_slice(), [flag] if flag == "--console" || flag == "--offline");
let (pid, dll): (Option<u32>, PathBuf) = match args.as_slice() {
[] => {
open_invite_once();
(pick_process(), default_dll())
let (pid, dll): (Option<u32>, Result<PathBuf, String>) = match args.as_slice() {
_ if interactive => {
let library = prepare_runtime(args.iter().any(|arg| arg == "--offline"), true);
if let Err(error) = &library {
fail("runtime", error);
return ExitCode::from(1);
}
(pick_process(), library)
}
[pid] => (parse_pid(pid), default_dll()),
[pid, dll] => (parse_pid(pid), PathBuf::from(dll)),
[pid] => (parse_pid(pid), prepare_runtime(true, false)),
[pid, dll] => (parse_pid(pid), Ok(PathBuf::from(dll))),
_ => {
eprintln!("usage: PrestigeInjector [<pid> [lib path]]");
eprintln!("usage: OpenPrestigeInjector [--console | --offline | <pid> [lib path]]");
return ExitCode::from(2);
}
};
let Some(pid) = pid else {
// interactive mode quit with Esc, or an unparsable pid was given
return if interactive { ExitCode::SUCCESS } else { ExitCode::from(2) };
return if interactive {
ExitCode::SUCCESS
} else {
ExitCode::from(2)
};
};
if !interactive {
print!("{}", banner());
}
let dll = match dll {
Ok(path) => path,
Err(error) => {
fail("runtime", &error);
return ExitCode::from(1);
}
};
let code = run(pid, &dll);
if interactive {
@@ -121,35 +173,58 @@ fn run(pid: u32, dll: &Path) -> ExitCode {
let dll_display = dll_display.trim_start_matches(r"\\?\").to_string();
step("loader", &dll_display);
// The library appends to prestige-native.log beside itself; remember where it ends so only this run's lines are shown.
let log_path = dll.with_file_name("prestige-native.log");
let log_start = fs::metadata(&log_path).map(|m| m.len()).unwrap_or(0);
let log_path = paths::native_log(pid);
let logs = [log_path.clone(), dll.with_file_name("prestige-native.log")];
let starts = logs
.each_ref()
.map(|path| fs::metadata(path).map(|m| m.len()).unwrap_or(0));
step("checking", "64-bit JVM, process access, library not already loaded");
step(
"checking",
"64-bit JVM, process access, library not already loaded",
);
step("injecting", "loading the native library into the JVM");
match platform::inject(pid, &dll) {
Ok(()) => ok("injected", &format!("{} is loaded in the game process", platform::LIB_NAME)),
Ok(()) => ok(
"injected",
&format!("{} is loaded in the game process", platform::LIB_NAME),
),
Err(e) => {
fail("failed", &e);
return ExitCode::from(1);
}
}
step("transforming", "following the loader log (attach, class loader, hook transformer)...");
match follow_log(&log_path, log_start) {
step(
"transforming",
"following the loader log (attach, class loader, hook transformer)...",
);
match follow_log(&logs, starts) {
Outcome::Done => {
println!();
ok("success", "successfully injected - Prestige is running in the game");
ok(
"success",
"successfully injected - Prestige is running in the game",
);
ExitCode::SUCCESS
}
Outcome::Failed(line) => {
fail("failed", &format!("injection did not complete: {line}"));
println!("{DIM} details: {} and the game's latest.log{RESET}", log_path.display());
println!(
"{DIM} details: {} and the game's latest.log{RESET}",
log_path.display()
);
ExitCode::from(1)
}
Outcome::TimedOut => {
fail("timeout", "no completion message from the loader within 3 minutes");
println!("{DIM} check {} and the game's latest.log{RESET}", log_path.display());
fail(
"timeout",
"no completion message from the loader within 3 minutes",
);
println!(
"{DIM} check {} and the game's latest.log{RESET}",
log_path.display()
);
ExitCode::from(1)
}
}
@@ -162,76 +237,77 @@ enum Outcome {
}
/// Prints the lines the loader/bootstrap append to the log until they report success or failure.
fn follow_log(path: &Path, start: u64) -> Outcome {
fn follow_log(paths: &[PathBuf; 2], mut offsets: [u64; 2]) -> Outcome {
let deadline = Instant::now() + FOLLOW_TIMEOUT;
let mut offset = start;
let mut pending = String::new();
let mut pending = [String::new(), String::new()];
while Instant::now() < deadline {
if let Ok(mut file) = fs::File::open(path) {
if file.seek(SeekFrom::Start(offset)).is_ok() {
let mut chunk = String::new();
if let Ok(n) = file.read_to_string(&mut chunk) {
offset += n as u64;
pending.push_str(&chunk);
for (index, path) in paths.iter().enumerate() {
let offset = &mut offsets[index];
let pending = &mut pending[index];
if let Ok(mut file) = fs::File::open(path) {
if file.seek(SeekFrom::Start(*offset)).is_ok() {
let mut chunk = String::new();
if let Ok(n) = file.read_to_string(&mut chunk) {
*offset += n as u64;
pending.push_str(&chunk);
}
}
}
}
while let Some(end) = pending.find('\n') {
let line: String = pending.drain(..=end).collect();
let line = line.trim_end();
// lines look like "[unix seconds] message"
let message = line.split_once("] ").map(|(_, m)| m).unwrap_or(line);
let lower = message.to_ascii_lowercase();
// Per-hook failures ("[java] hook failed for ...") are not fatal: Bootstrap keeps the hooks that applied.
let fatal = message.starts_with("FAILED:") || lower.contains("start failed") || lower.contains("client init failed") || lower.contains("could not hook");
if fatal {
fail("loader", message);
return Outcome::Failed(message.to_string());
while let Some(end) = pending.find('\n') {
let line: String = pending.drain(..=end).collect();
// Keep the output from older runtime bundles in the shared log too.
if index == 1 {
if let Ok(mut log) = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&paths[0])
{
if log.write_all(line.as_bytes()).is_ok() {
offsets[0] += line.len() as u64;
}
}
}
let line = line.trim_end();
// lines look like "[unix seconds] message"
let message = line.split_once("] ").map(|(_, m)| m).unwrap_or(line);
let lower = message.to_ascii_lowercase();
// Per-hook failures ("[java] hook failed for ...") are not fatal: Bootstrap keeps the hooks that applied.
let fatal = message.starts_with("FAILED:")
|| lower.contains("start failed")
|| lower.contains("client init failed")
|| lower.contains("could not hook");
if fatal {
fail("loader", message);
return Outcome::Failed(message.to_string());
}
if message.contains("client initialised") {
ok("loader", message);
return Outcome::Done;
}
step("loader", message);
}
if message.contains("client initialised") {
ok("loader", message);
return Outcome::Done;
}
step("loader", message);
}
std::thread::sleep(Duration::from_millis(200));
}
Outcome::TimedOut
}
fn config_path() -> Option<PathBuf> {
platform::config_dir().map(|dir| dir.join("PrestigeInjector").join("settings.txt"))
}
/// Opens the Discord invite on the very first launch only (no prompt); afterwards only the credit line shows it.
fn open_invite_once() {
let Some(path) = config_path() else { return };
if path.exists() {
return;
}
let _ = platform::open_url(INVITE_URL);
if let Some(dir) = path.parent() {
let _ = fs::create_dir_all(dir);
}
let _ = fs::write(&path, "invite_opened=true\n");
}
/// Interactive list of Minecraft JVM windows, refreshed every 750 ms. Returns the chosen pid.
fn pick_process() -> Option<u32> {
let mut selected = 0usize;
let mut processes = platform::java_processes();
let mut last_refresh = Instant::now();
draw(&processes, selected);
loop {
if selected >= processes.len() {
selected = processes.len().saturating_sub(1);
}
draw(&processes, selected);
let deadline = Instant::now() + Duration::from_millis(50);
while Instant::now() < deadline {
if let Some(key) = platform::poll_key() {
let previous = selected;
match key {
platform::Key::Up => selected = selected.saturating_sub(1),
platform::Key::Down => selected = (selected + 1).min(processes.len().saturating_sub(1)),
platform::Key::Down => {
selected = (selected + 1).min(processes.len().saturating_sub(1))
}
platform::Key::Enter => {
if let Some(p) = processes.get(selected) {
return Some(p.pid);
@@ -239,12 +315,19 @@ fn pick_process() -> Option<u32> {
}
platform::Key::Escape => return None,
}
draw(&processes, selected);
if selected != previous {
draw(&processes, selected);
}
}
std::thread::sleep(Duration::from_millis(10));
}
if last_refresh.elapsed() >= Duration::from_millis(750) {
processes = platform::java_processes();
let refreshed = platform::java_processes();
if refreshed != processes {
processes = refreshed;
selected = selected.min(processes.len().saturating_sub(1));
draw(&processes, selected);
}
last_refresh = Instant::now();
}
}
@@ -259,7 +342,10 @@ fn draw(processes: &[platform::JavaProcess], selected: usize) {
}
for (i, p) in processes.iter().enumerate() {
let marker = if i == selected { ">" } else { " " };
out.push_str(&format!("{marker} [{:>6}] {} ({})\n", p.pid, p.title, p.exe));
out.push_str(&format!(
"{marker} [{:>6}] {} ({})\n",
p.pid, p.title, p.exe
));
}
print!("{out}");
let _ = io::stdout().flush();
+3 -22
View File
@@ -1,8 +1,8 @@
//! Platform backends of the injector. Each backend exposes the same functions:
//! enable_ansi, poll_key, java_processes, inject, open_url, restore_terminal.
use std::path::PathBuf;
//! enable_ansi, poll_key, java_processes, inject, restore_terminal.
/// A running Minecraft JVM shown in the picker.
#[derive(PartialEq)]
pub struct JavaProcess {
pub pid: u32,
pub title: String,
@@ -32,7 +32,7 @@ pub use unix_attach::inject;
#[cfg(unix)]
pub use unix_procs::java_processes;
#[cfg(unix)]
pub use unix_term::{enable_ansi, open_url, poll_key, restore_terminal};
pub use unix_term::{enable_ansi, poll_key, restore_terminal};
#[cfg(windows)]
pub const LIB_NAME: &str = "prestige_native.dll";
@@ -40,22 +40,3 @@ pub const LIB_NAME: &str = "prestige_native.dll";
pub const LIB_NAME: &str = "libprestige_native.dylib";
#[cfg(all(unix, not(target_os = "macos")))]
pub const LIB_NAME: &str = "libprestige_native.so";
/// Per-user configuration directory: APPDATA, $XDG_CONFIG_HOME or ~/.config, ~/Library/Application Support.
pub fn config_dir() -> Option<PathBuf> {
#[cfg(windows)]
{
std::env::var_os("APPDATA").map(PathBuf::from)
}
#[cfg(target_os = "macos")]
{
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library").join("Application Support"))
}
#[cfg(all(unix, not(target_os = "macos")))]
{
match std::env::var_os("XDG_CONFIG_HOME") {
Some(dir) if !dir.is_empty() => Some(PathBuf::from(dir)),
_ => std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")),
}
}
}
@@ -1,4 +1,4 @@
//! Terminal input and URL opening on Linux and macOS. std only (no termios structs).
//! Terminal input on Linux and macOS. std only (no termios structs).
//!
//! Raw mode is entered lazily on the first `poll_key` call via `stty -icanon -echo min 1 time 0`
//! on /dev/tty (ISIG stays on, so Ctrl-C still raises SIGINT). A reader thread blocks on the tty
@@ -37,8 +37,15 @@ fn tty_stdin() -> Stdio {
}
fn stty(args: &[&str]) -> Option<String> {
let out = Command::new("stty").args(args).stdin(tty_stdin()).stderr(Stdio::null()).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
let out = Command::new("stty")
.args(args)
.stdin(tty_stdin())
.stderr(Stdio::null())
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
}
/// Nothing to do on unix (terminals understand ANSI); raw mode is entered lazily by `poll_key`.
@@ -113,7 +120,9 @@ pub fn poll_key() -> Option<Key> {
27 => {
let ms30 = Duration::from_millis(30);
match rx.recv_timeout(ms30) {
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => return Some(Key::Escape),
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {
return Some(Key::Escape)
}
Ok(b'[') | Ok(b'O') => match rx.recv_timeout(ms30) {
Ok(b'A') => return Some(Key::Up),
Ok(b'B') => return Some(Key::Down),
@@ -134,19 +143,3 @@ pub fn restore_terminal() {
stty(&[&s]);
}
}
/// Opens a URL in the default browser (xdg-open / open). Returns whether the spawn succeeded.
pub fn open_url(url: &str) -> bool {
#[cfg(target_os = "macos")]
let opener = "open";
#[cfg(not(target_os = "macos"))]
let opener = "xdg-open";
Command::new(opener)
.arg(url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map(|_| true)
.unwrap_or(false)
}
+167 -30
View File
@@ -39,16 +39,43 @@ struct ModuleEntry32W {
extern "system" {
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
fn CloseHandle(h: Handle) -> i32;
fn VirtualAllocEx(process: Handle, address: *mut c_void, size: usize, alloc_type: u32, protect: u32) -> *mut c_void;
fn VirtualAllocEx(
process: Handle,
address: *mut c_void,
size: usize,
alloc_type: u32,
protect: u32,
) -> *mut c_void;
fn VirtualFreeEx(process: Handle, address: *mut c_void, size: usize, free_type: u32) -> i32;
fn WriteProcessMemory(process: Handle, address: *mut c_void, buf: *const c_void, size: usize, written: *mut usize) -> i32;
fn CreateRemoteThread(process: Handle, attrs: *mut c_void, stack: usize, start: *mut c_void, param: *mut c_void, flags: u32, id: *mut u32) -> Handle;
fn WriteProcessMemory(
process: Handle,
address: *mut c_void,
buf: *const c_void,
size: usize,
written: *mut usize,
) -> i32;
fn CreateRemoteThread(
process: Handle,
attrs: *mut c_void,
stack: usize,
start: *mut c_void,
param: *mut c_void,
flags: u32,
id: *mut u32,
) -> Handle;
fn WaitForSingleObject(h: Handle, ms: u32) -> u32;
fn GetExitCodeThread(h: Handle, code: *mut u32) -> i32;
fn GetModuleHandleW(name: *const u16) -> Handle;
fn GetProcAddress(module: Handle, name: *const u8) -> *mut c_void;
fn IsWow64Process(process: Handle, wow64: *mut i32) -> i32;
fn QueryFullProcessImageNameW(process: Handle, flags: u32, buf: *mut u16, size: *mut u32) -> i32;
fn IsWow64Process2(process: Handle, process_machine: *mut u16, native_machine: *mut u16)
-> i32;
fn GetCurrentProcess() -> Handle;
fn QueryFullProcessImageNameW(
process: Handle,
flags: u32,
buf: *mut u16,
size: *mut u32,
) -> i32;
fn GetLastError() -> u32;
fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> Handle;
fn Module32FirstW(snapshot: Handle, entry: *mut ModuleEntry32W) -> i32;
@@ -66,11 +93,6 @@ extern "system" {
fn GetWindowThreadProcessId(hwnd: Handle, pid: *mut u32) -> u32;
}
#[link(name = "shell32")]
extern "system" {
fn ShellExecuteW(hwnd: Handle, verb: *const u16, file: *const u16, params: *const u16, dir: *const u16, show: i32) -> isize;
}
extern "C" {
fn _kbhit() -> i32;
fn _getch() -> i32;
@@ -109,7 +131,10 @@ pub fn poll_key() -> Option<Key> {
}
fn wide(path: &Path) -> Vec<u16> {
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
path.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect()
}
fn image_name(pid: u32) -> Option<String> {
@@ -145,7 +170,7 @@ unsafe extern "system" fn collect(hwnd: Handle, param: isize) -> i32 {
1
}
/// Visible top-level windows that belong to java.exe / javaw.exe, one entry per process.
/// Visible JVM windows, including clients that embed HotSpot in their own executable.
pub fn java_processes() -> Vec<JavaProcess> {
let mut windows: Vec<(u32, String)> = Vec::new();
unsafe {
@@ -156,9 +181,14 @@ pub fn java_processes() -> Vec<JavaProcess> {
if out.iter().any(|w| w.pid == pid) {
continue;
}
let Some(path) = image_name(pid) else { continue };
let Some(path) = image_name(pid) else {
continue;
};
let exe = path.rsplit(['\\', '/']).next().unwrap_or("").to_string();
if exe.eq_ignore_ascii_case("javaw.exe") || exe.eq_ignore_ascii_case("java.exe") {
if exe.eq_ignore_ascii_case("javaw.exe")
|| exe.eq_ignore_ascii_case("java.exe")
|| module_loaded(pid, "jvm.dll")
{
out.push(JavaProcess { pid, title, exe });
}
}
@@ -181,7 +211,11 @@ fn module_loaded(pid: u32, file_name: &str) -> bool {
let mut found = false;
let mut ok = Module32FirstW(snapshot, &mut entry);
while ok != 0 {
let len = entry.sz_module.iter().position(|&c| c == 0).unwrap_or(entry.sz_module.len());
let len = entry
.sz_module
.iter()
.position(|&c| c == 0)
.unwrap_or(entry.sz_module.len());
if String::from_utf16_lossy(&entry.sz_module[..len]).eq_ignore_ascii_case(file_name) {
found = true;
break;
@@ -196,10 +230,16 @@ fn module_loaded(pid: u32, file_name: &str) -> bool {
/// LoadLibraryW(dll) in the target process through CreateRemoteThread.
pub fn inject(pid: u32, dll: &Path) -> Result<(), String> {
unsafe {
let access = PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ;
let access = PROCESS_CREATE_THREAD
| PROCESS_QUERY_INFORMATION
| PROCESS_VM_OPERATION
| PROCESS_VM_WRITE
| PROCESS_VM_READ;
let process = OpenProcess(access, 0, pid);
if process.is_null() {
return Err(last_error("OpenProcess (run as the same user, or as administrator)"));
return Err(last_error(
"OpenProcess (run as the same user, or as administrator)",
));
}
let result = inject_into(process, pid, dll);
CloseHandle(process);
@@ -208,18 +248,50 @@ pub fn inject(pid: u32, dll: &Path) -> Result<(), String> {
}
unsafe fn inject_into(process: Handle, pid: u32, dll: &Path) -> Result<(), String> {
let mut wow64 = 0;
if IsWow64Process(process, &mut wow64) != 0 && wow64 != 0 {
return Err("the target is a 32-bit JVM; only 64-bit JVMs are supported".into());
unsafe fn machine(process: Handle) -> Result<u16, String> {
let mut emulated = 0;
let mut native = 0;
if IsWow64Process2(process, &mut emulated, &mut native) == 0 {
return Err(last_error("IsWow64Process2"));
}
Ok(if emulated == 0 { native } else { emulated })
}
let file_name = dll.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let target = machine(process)?;
let injector = machine(GetCurrentProcess())?;
if target != injector {
return Err(format!("JVM architecture {target:#06x} differs from injector {injector:#06x}. Use matching x64 or ARM64 builds."));
}
let image = std::fs::read(dll).map_err(|error| format!("read loader: {error}"))?;
let pe = image
.get(0x3c..0x40)
.and_then(|bytes| bytes.try_into().ok())
.map(u32::from_le_bytes)
.ok_or("invalid loader PE header")? as usize;
let library = image
.get(pe + 4..pe + 6)
.and_then(|bytes| bytes.try_into().ok())
.map(u16::from_le_bytes)
.ok_or("invalid loader machine")?;
if library != target {
return Err("The loader DLL and JVM architectures differ.".into());
}
let file_name = dll
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if module_loaded(pid, &file_name) {
return Err(format!("{file_name} is already loaded in process {pid}"));
}
let path = wide(dll);
let bytes = path.len() * 2;
let remote = VirtualAllocEx(process, std::ptr::null_mut(), bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
let remote = VirtualAllocEx(
process,
std::ptr::null_mut(),
bytes,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE,
);
if remote.is_null() {
return Err(last_error("VirtualAllocEx"));
}
@@ -227,7 +299,14 @@ unsafe fn inject_into(process: Handle, pid: u32, dll: &Path) -> Result<(), Strin
VirtualFreeEx(process, remote, 0, MEM_RELEASE);
Err(err)
};
if WriteProcessMemory(process, remote, path.as_ptr() as *const c_void, bytes, std::ptr::null_mut()) == 0 {
if WriteProcessMemory(
process,
remote,
path.as_ptr() as *const c_void,
bytes,
std::ptr::null_mut(),
) == 0
{
return cleanup(last_error("WriteProcessMemory"));
}
@@ -237,7 +316,15 @@ unsafe fn inject_into(process: Handle, pid: u32, dll: &Path) -> Result<(), Strin
if load_library.is_null() {
return cleanup(last_error("resolve LoadLibraryW"));
}
let thread = CreateRemoteThread(process, std::ptr::null_mut(), 0, load_library, remote, 0, std::ptr::null_mut());
let thread = CreateRemoteThread(
process,
std::ptr::null_mut(),
0,
load_library,
remote,
0,
std::ptr::null_mut(),
);
if thread.is_null() {
return cleanup(last_error("CreateRemoteThread"));
}
@@ -261,10 +348,60 @@ unsafe fn inject_into(process: Handle, pid: u32, dll: &Path) -> Result<(), Strin
Err(format!("LoadLibraryW returned {exit:#x} but {file_name} is not mapped (missing dependency or blocked by security software?)"))
}
/// Opens a URL in the default web browser.
pub fn open_url(url: &str) -> bool {
let verb: Vec<u16> = "open".encode_utf16().collect();
let target: Vec<u16> = url.encode_utf16().chain(std::iter::once(0)).collect();
// ShellExecute returns a value greater than 32 on success
unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), 1) > 32 }
#[cfg(test)]
mod tests {
use super::*;
extern "system" {
fn LoadLibraryExW(path: *const u16, file: Handle, flags: u32) -> Handle;
fn FreeLibrary(module: Handle) -> i32;
}
#[link(name = "user32")]
extern "system" {
fn CreateWindowExW(ex: u32, class: *const u16, title: *const u16, style: u32,
x: i32, y: i32, width: i32, height: i32, parent: Handle, menu: Handle,
instance: Handle, param: *mut c_void) -> Handle;
fn DestroyWindow(window: Handle) -> i32;
}
struct Fixture { window: Handle, library: Handle }
impl Drop for Fixture {
fn drop(&mut self) {
unsafe {
if !self.window.is_null() { DestroyWindow(self.window); }
if !self.library.is_null() { FreeLibrary(self.library); }
}
}
}
#[test]
fn discovers_a_custom_executable_only_when_it_hosts_a_jvm() {
let pid = std::process::id();
let image = image_name(pid).expect("read test executable path");
assert!(!image.ends_with("\\java.exe") && !image.ends_with("\\javaw.exe"));
let home = std::env::var_os("JAVA_HOME").expect("set JAVA_HOME to a 64-bit JDK for this test");
let jvm = Path::new(&home).join("bin/server/jvm.dll");
assert!(jvm.is_file(), "missing {}", jvm.display());
unsafe {
let mut fixture = Fixture { window: std::ptr::null_mut(), library: std::ptr::null_mut() };
// The picker requires a visible window; place this 1px fixture off-screen.
fixture.window = CreateWindowExW(0, wide(Path::new("STATIC")).as_ptr(),
wide(Path::new("OpenPrestige JVM discovery test")).as_ptr(), 0x90000000,
-32000, -32000, 1, 1, std::ptr::null_mut(), std::ptr::null_mut(),
GetModuleHandleW(std::ptr::null()), std::ptr::null_mut());
assert!(!fixture.window.is_null(), "{}", last_error("CreateWindowExW"));
assert!(!module_loaded(pid, "jvm.dll"));
assert!(!java_processes().iter().any(|process| process.pid == pid));
fixture.library = LoadLibraryExW(wide(&jvm).as_ptr(), std::ptr::null_mut(), 0x00001100);
assert!(!fixture.library.is_null(), "{}", last_error("LoadLibraryExW(jvm.dll)"));
assert!(module_loaded(pid, "JVM.DLL"));
assert!(!module_loaded(pid, "openprestige-missing-test-module.dll"));
let processes = java_processes();
let found = processes.iter().find(|process| process.pid == pid)
.expect("custom executable hosting HotSpot was not listed");
assert_eq!(found.title, "OpenPrestige JVM discovery test");
}
}
}
+28 -30
View File
@@ -1,35 +1,33 @@
//! Locates the remapped Prestige payload jar (built by `gradlew remapJar`) so lib.rs can embed it with include_bytes!.
use std::env;
use std::fs;
use std::path::PathBuf;
//! Embed exact-version payloads and one copy of their common libraries.
use std::{env, fs, path::{Path, PathBuf}};
fn include(path: &Path) -> String {
let path = path.canonicalize().unwrap_or_else(|e| panic!("{}: {e}", path.display()));
println!("cargo:rerun-if-changed={}", path.display());
format!("include_bytes!({:?})", path.to_str().expect("UTF-8 payload path"))
}
fn main() {
println!("cargo:rerun-if-env-changed=PRESTIGE_PAYLOAD");
let jar = match env::var("PRESTIGE_PAYLOAD") {
Ok(p) => PathBuf::from(p),
Err(_) => newest_remapped_jar(),
};
if !jar.is_file() {
panic!("payload jar not found: {} (run `gradlew remapJar` or set PRESTIGE_PAYLOAD)", jar.display());
}
println!("cargo:rerun-if-changed={}", jar.display());
println!("cargo:rustc-env=PRESTIGE_PAYLOAD_JAR={}", jar.display());
}
fn newest_remapped_jar() -> PathBuf {
let libs = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../../build/libs");
let mut best: Option<(std::time::SystemTime, PathBuf)> = None;
if let Ok(entries) = fs::read_dir(&libs) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("prestige-") || !name.ends_with(".jar") || name.ends_with("-dev.jar") || name.ends_with("-sources.jar") {
continue;
}
let time = entry.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
if best.as_ref().map_or(true, |(t, _)| time > *t) {
best = Some((time, entry.path()));
}
println!("cargo:rerun-if-env-changed=PRESTIGE_BUNDLE");
let generated = if let Ok(jar) = env::var("PRESTIGE_PAYLOAD") {
// Explicit single-target developer builds retain Java's exact-target guard.
format!("static COMMON: &[u8] = &[];\nstatic PAYLOADS: &[(&str, &[u8])] = &[(\"\", {})];", include(Path::new(&jar)))
} else {
let dir = env::var_os("PRESTIGE_BUNDLE").map(PathBuf::from).unwrap_or_else(||
PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("../../../build/bundle"));
let manifest = dir.join("versions.txt");
println!("cargo:rerun-if-changed={}", manifest.display());
let versions = fs::read_to_string(&manifest)
.expect("run gradlew bundlePayloads before building the native bundle");
let expected: Vec<_> = (1..=11).map(|n| format!("1.21.{n}")).collect();
assert_eq!(versions.lines().collect::<Vec<_>>(), expected, "incomplete payload matrix");
let mut code = format!("static COMMON: &[u8] = {};\nstatic PAYLOADS: &[(&str, &[u8])] = &[\n", include(&dir.join("common.jar")));
for version in versions.lines() {
code.push_str(&format!("({version:?}, {}),\n", include(&dir.join(format!("{version}.jar")))));
}
}
best.map(|(_, p)| p).unwrap_or_else(|| libs.join("prestige-0.1.0.jar"))
code.push_str("];\n");
code
};
fs::write(PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("payloads.rs"), generated).unwrap();
}
-3
View File
@@ -56,9 +56,6 @@ impl Jni {
pub unsafe fn exception_clear(&self) {
f!(self, 17, unsafe extern "system" fn(EnvPtr))(self.env)
}
pub unsafe fn new_global_ref(&self, o: JObject) -> JObject {
f!(self, 21, unsafe extern "system" fn(EnvPtr, JObject) -> JObject)(self.env, o)
}
pub unsafe fn is_same_object(&self, a: JObject, b: JObject) -> bool {
f!(self, 24, unsafe extern "system" fn(EnvPtr, JObject, JObject) -> JBool)(self.env, a, b) != 0
}
+3 -1
View File
@@ -1,4 +1,4 @@
//! prestige_native.dll: loaded into a running Minecraft 1.21.11 (Fabric) JVM by PrestigeInjector.exe.
//! prestige_native.dll: loads the exact Minecraft 1.21.1–1.21.11 Fabric payload for the running JVM.
//!
//! The DLL worker waits for the JVM, appends the embedded Prestige payload jar to Fabric's Knot class loader, registers the
//! JVMTI-backed natives of `dev.zprestige.prestige.inject.NativeBridge` and starts `Bootstrap`, which transforms the already
@@ -6,6 +6,8 @@
mod bridge;
mod jni;
mod log;
#[path = "../../paths.rs"]
mod paths;
mod worker;
use std::ffi::c_void;
+4 -46
View File
@@ -1,61 +1,19 @@
use std::ffi::c_void;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(windows)]
extern "system" {
fn GetModuleFileNameW(module: *mut c_void, buf: *mut u16, size: u32) -> u32;
}
#[cfg(unix)]
#[repr(C)]
struct DlInfo {
dli_fname: *const std::ffi::c_char,
dli_fbase: *mut c_void,
dli_sname: *const std::ffi::c_char,
dli_saddr: *mut c_void,
}
#[cfg(unix)]
extern "C" {
fn dladdr(addr: *const c_void, info: *mut DlInfo) -> i32;
}
#[cfg(unix)]
fn module_path() -> PathBuf {
fn anchor() {}
let mut info = DlInfo { dli_fname: std::ptr::null(), dli_fbase: std::ptr::null_mut(), dli_sname: std::ptr::null(), dli_saddr: std::ptr::null_mut() };
let ok = unsafe { dladdr(anchor as fn() as usize as *const c_void, &mut info) };
if ok != 0 && !info.dli_fname.is_null() {
let name = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) };
PathBuf::from(std::ffi::OsStr::from_bytes(name.to_bytes()))
} else {
std::env::temp_dir().join("libprestige_native")
}
}
#[cfg(windows)]
fn module_path() -> PathBuf {
let mut buf = [0u16; 1024];
let len = unsafe { GetModuleFileNameW(crate::MODULE, buf.as_mut_ptr(), buf.len() as u32) } as usize;
PathBuf::from(String::from_utf16_lossy(&buf[..len]))
}
fn log_path() -> &'static PathBuf {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(|| {
module_path().with_file_name("prestige-native.log")
})
PATH.get_or_init(|| crate::paths::native_log(std::process::id()))
}
/// Appends a line to prestige-native.log beside the DLL.
pub fn log(message: &str) {
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
if let Some(parent) = log_path().parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path()) {
let _ = writeln!(file, "[{secs}] {message}");
}
+104 -17
View File
@@ -15,7 +15,7 @@ extern "system" {
fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *mut c_void;
}
static PAYLOAD: &[u8] = include_bytes!(env!("PRESTIGE_PAYLOAD_JAR"));
include!(concat!(env!("OUT_DIR"), "/payloads.rs"));
const NATIVE_BRIDGE: &str = "dev.zprestige.prestige.inject.NativeBridge";
const BOOTSTRAP: &str = "dev.zprestige.prestige.inject.Bootstrap";
@@ -29,6 +29,7 @@ pub fn run() {
}
unsafe fn install() -> Result<(), String> {
crate::paths::initialize().map_err(|error| format!("create OpenPrestige data directory: {error}"))?;
let vm = find_vm()?;
let env = attach_current_thread(vm)?;
struct Detach(VmPtr);
@@ -44,11 +45,21 @@ unsafe fn install() -> Result<(), String> {
init_jvmti(vm)?;
log!("JVMTI ready");
let jar = write_payload()?;
log!("payload written to {}", jar.display());
let (_, fabric_loader) = locate_fabric(&jni)?;
let version = minecraft_version(&jni, fabric_loader)?;
let payload = select_payload(&version, PAYLOADS)
.ok_or_else(|| format!("unsupported Minecraft {version}; bundled targets: {}",
PAYLOADS.iter().map(|(target, _)| *target).collect::<Vec<_>>().join(", ")))?;
log!("selected Minecraft {version} payload");
if !COMMON.is_empty() {
let common = write_payload("common", COMMON)?;
add_to_knot(&jni, &common)?;
}
let jar = write_payload(&version, payload.1)?;
log!("using payload at {}", jar.display());
let loader = add_to_knot(&jni, &jar)?;
log!("payload appended to the Fabric Knot class loader");
log!("payload appended to the game class loader: {}", describe(&jni, loader));
register_natives(&jni, loader)?;
log!("natives registered");
@@ -102,16 +113,55 @@ unsafe fn find_vm() -> Result<VmPtr, String> {
Err("no JavaVM was created".into())
}
fn write_payload() -> Result<PathBuf, String> {
let dir = std::env::temp_dir().join("PrestigeLoader");
fn write_payload(target: &str, bytes: &[u8]) -> Result<PathBuf, String> {
let dir = crate::paths::initialize().map_err(|e| format!("create OpenPrestige data directory: {e}"))?
.join("runtime").join("payloads");
std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
let path = dir.join(format!("prestige-payload-{}.jar", std::process::id()));
std::fs::write(&path, PAYLOAD).map_err(|e| format!("write {}: {e}", path.display()))?;
if !target.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-') {
return Err(format!("invalid Minecraft target: {target}"));
}
let path = dir.join(format!("prestige-{target}-{}.jar", std::process::id()));
std::fs::write(&path, bytes).map_err(|e| format!("write {}: {e}", path.display()))?;
Ok(path)
}
/// Read stable Fabric metadata before adding a payload to the game loader.
unsafe fn minecraft_version(jni: &Jni, loader: JObject) -> Result<String, String> {
let api = load_fabric_class(jni, "net.fabricmc.loader.api.FabricLoader", loader)?;
let instance = jni.get_static_method_id(api, "getInstance", "()Lnet/fabricmc/loader/api/FabricLoader;");
jni.check("FabricLoader.getInstance lookup")?;
let fabric = jni.call_static_object(api, instance, &[]);
jni.check("FabricLoader.getInstance")?;
let get_mod = jni.get_method_id(api, "getModContainer", "(Ljava/lang/String;)Ljava/util/Optional;");
jni.check("FabricLoader.getModContainer lookup")?;
let minecraft = jni.new_string("minecraft");
let optional = jni.call_object(jni_non_null(fabric)?, get_mod, &[obj(minecraft)]);
jni.check("Minecraft mod container")?;
let optional_class = jni.find_class("java/util/Optional");
let get = jni.get_method_id(optional_class, "get", "()Ljava/lang/Object;");
jni.check("Optional.get lookup")?;
let container = jni.call_object(jni_non_null(optional)?, get, &[]);
jni.check("Minecraft mod present")?;
let container_class = load_fabric_class(jni, "net.fabricmc.loader.api.ModContainer", loader)?;
let metadata = jni.get_method_id(container_class, "getMetadata", "()Lnet/fabricmc/loader/api/metadata/ModMetadata;");
jni.check("ModContainer.getMetadata lookup")?;
let metadata = jni.call_object(jni_non_null(container)?, metadata, &[]);
jni.check("Minecraft metadata")?;
let metadata_class = load_fabric_class(jni, "net.fabricmc.loader.api.metadata.ModMetadata", loader)?;
let version = jni.get_method_id(metadata_class, "getVersion", "()Lnet/fabricmc/loader/api/Version;");
jni.check("ModMetadata.getVersion lookup")?;
let version = jni.call_object(jni_non_null(metadata)?, version, &[]);
jni.check("Minecraft version")?;
let version_class = load_fabric_class(jni, "net.fabricmc.loader.api.Version", loader)?;
let friendly = jni.get_method_id(version_class, "getFriendlyString", "()Ljava/lang/String;");
jni.check("Version.getFriendlyString lookup")?;
let friendly = jni.call_object(jni_non_null(version)?, friendly, &[]);
jni.check("Minecraft version string")?;
Ok(jni.get_string_utf(jni_non_null(friendly)?))
}
/// FabricLauncherBase.getLauncher().addToClassPath(path) so the payload and the game classes share the Knot class loader.
/// Returns a global reference to the Knot target class loader.
/// Returns a local reference to the Fabric launcher's target class loader.
unsafe fn add_to_knot(jni: &Jni, jar: &std::path::Path) -> Result<JObject, String> {
jni.ensure_local_capacity(4096);
let (base, fabric_loader) = locate_fabric(jni)?;
@@ -149,23 +199,52 @@ unsafe fn add_to_knot(jni: &Jni, jar: &std::path::Path) -> Result<JObject, Strin
if loader.is_null() {
return Err("Knot target class loader is null".into());
}
Ok(jni.new_global_ref(loader))
Ok(loader)
}
const FABRIC_BASE: &str = "net.fabricmc.loader.impl.launch.FabricLauncherBase";
/// Finds the class loader that can see fabric-loader. The system class loader is tried first (official launcher, most
/// others); launchers that run the game from their own URLClassLoader (Prism/MultiMC, many modpack launchers) keep
/// fabric-loader out of it, so every thread's context class loader is probed too. Returns the FabricLauncherBase class
/// and the loader it was found through (null = FindClass / system loader).
fn select_payload<'a>(version: &str, payloads: &'a [(&str, &[u8])]) -> Option<&'a (&'a str, &'a [u8])> {
payloads.iter().find(|(target, _)| target.is_empty() || *target == version)
}
#[cfg(test)]
mod payload_tests {
use super::select_payload;
#[test]
fn only_selects_exact_target() {
let versions: Vec<_> = (1..=11).map(|n| format!("1.21.{n}")).collect();
let payloads: Vec<_> = versions.iter().enumerate()
.map(|(i, version)| (version.as_str(), &b"123456789ab"[i..i+1])).collect();
for (index, version) in versions.iter().enumerate() {
assert_eq!(select_payload(version, &payloads).unwrap().1, &b"123456789ab"[index..index+1]);
}
for unsupported in ["1.21", "1.21.0", "1.21.12", "1.21.1-pre1", ""] {
assert!(select_payload(unsupported, &payloads).is_none());
}
}
}
/// Prefer the render thread's context loader when a launcher supplies its own loader hierarchy.
/// Fall back to the system loader and then the other thread context loaders.
unsafe fn locate_fabric(jni: &Jni) -> Result<(JClass, JObject), String> {
let (render, loaders) = thread_loaders(jni)?;
if let Some(loader) = render {
if let Ok(class) = class_for_name(jni, FABRIC_BASE, loader, false) {
log!("fabric-loader found through the render thread: {}", describe(jni, loader));
return Ok((class, loader));
}
}
let base = jni.find_class(&FABRIC_BASE.replace('.', "/"));
if jni.take_exception().is_none() && !base.is_null() {
return Ok((base, std::ptr::null_mut()));
}
log!("FabricLauncherBase is not visible to the system class loader, probing thread context class loaders");
let loaders = thread_loaders(jni)?;
for &loader in &loaders {
if render.is_some_and(|r| jni.is_same_object(r, loader)) {
continue;
}
if let Ok(class) = class_for_name(jni, FABRIC_BASE, loader, false) {
log!("fabric-loader found through {}", describe(jni, loader));
return Ok((class, loader));
@@ -180,10 +259,11 @@ unsafe fn locate_fabric(jni: &Jni) -> Result<(JClass, JObject), String> {
}
/// Distinct context class loaders of all live threads (the game threads inherit the launcher's loader).
unsafe fn thread_loaders(jni: &Jni) -> Result<Vec<JObject>, String> {
unsafe fn thread_loaders(jni: &Jni) -> Result<(Option<JObject>, Vec<JObject>), String> {
let thread_class = jni.find_class("java/lang/Thread");
let get_all = jni.get_static_method_id(thread_class, "getAllStackTraces", "()Ljava/util/Map;");
let get_context = jni.get_method_id(thread_class, "getContextClassLoader", "()Ljava/lang/ClassLoader;");
let get_name = jni.get_method_id(thread_class, "getName", "()Ljava/lang/String;");
let map_class = jni.find_class("java/util/Map");
let key_set = jni.get_method_id(map_class, "keySet", "()Ljava/util/Set;");
let set_class = jni.find_class("java/util/Set");
@@ -195,6 +275,7 @@ unsafe fn thread_loaders(jni: &Jni) -> Result<Vec<JObject>, String> {
let threads = jni.call_object(jni_non_null(set)?, to_array, &[]);
jni.check("thread list")?;
let mut loaders: Vec<JObject> = Vec::new();
let mut render = None;
for i in 0..jni.get_array_length(jni_non_null(threads)?) {
let thread = jni.get_object_array_element(threads, i);
if thread.is_null() {
@@ -204,11 +285,17 @@ unsafe fn thread_loaders(jni: &Jni) -> Result<Vec<JObject>, String> {
if jni.take_exception().is_some() || loader.is_null() {
continue;
}
let name = jni.call_object(thread, get_name, &[]);
if jni.take_exception().is_none() && !name.is_null() {
if matches!(jni.get_string_utf(name).as_str(), "Render thread" | "Client thread") {
render = Some(loader);
}
}
if !loaders.iter().any(|&known| jni.is_same_object(known, loader)) {
loaders.push(loader);
}
}
Ok(loaders)
Ok((render, loaders))
}
unsafe fn jni_non_null(o: JObject) -> Result<JObject, String> {
+36
View File
@@ -0,0 +1,36 @@
use std::io;
use std::path::PathBuf;
fn env_path(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.filter(|path| !path.is_empty())
.map(PathBuf::from)
}
pub fn root() -> PathBuf {
#[cfg(windows)]
let base = env_path("APPDATA")
.or_else(|| env_path("USERPROFILE").map(|home| home.join("AppData/Roaming")));
#[cfg(target_os = "macos")]
let base = env_path("HOME").map(|home| home.join("Library/Application Support"));
#[cfg(all(unix, not(target_os = "macos")))]
let base = env_path("XDG_DATA_HOME")
.filter(|path| path.is_absolute())
.or_else(|| env_path("HOME").map(|home| home.join(".local/share")));
base.unwrap_or_else(std::env::temp_dir)
.join(".openprestige")
}
pub fn initialize() -> io::Result<PathBuf> {
let root = root();
for name in ["configs", "logs", "runtime"] {
std::fs::create_dir_all(root.join(name))?;
}
Ok(root)
}
pub fn native_log(pid: u32) -> PathBuf {
root()
.join("logs")
.join(format!("prestige-native-{pid}.log"))
}
+1 -1
View File
@@ -13,7 +13,7 @@ echo Logging to %LOG%
rem Everything gradle/game prints goes to the console AND logs\run_<time>.log
rem extra args are passed through, e.g. run.bat -PuiCmd=run\cmd\c.txt
set "ARGS=%*"
powershell -NoProfile -Command "& { & '.\gradlew.bat' runClient --console=plain $env:ARGS 2>&1 | ForEach-Object { $_; Add-Content -LiteralPath '%LOG%' -Value $_ -Encoding UTF8 }; exit $LASTEXITCODE }"
powershell -NoProfile -Command "& { & '.\gradlew.bat' :1.21.11:runClient --console=plain $env:ARGS 2>&1 | ForEach-Object { $_; Add-Content -LiteralPath '%LOG%' -Value $_ -Encoding UTF8 }; exit $LASTEXITCODE }"
set "RC=%ERRORLEVEL%"
rem keep a copy of the game's own latest.log and any crash report written during this run
+182
View File
@@ -0,0 +1,182 @@
"""Build the core-only JNI library matching imgui-java 1.92.7.1.
Requires Python 3, a JDK, CMake, and a C++17 compiler. Select a cross compiler
with --toolchain or a Visual Studio target with --architecture ARM64.
"""
import argparse
import os
import re
from pathlib import Path
import shutil
import subprocess
import tempfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
BINDING_COMMIT = "b164a88602af3e28483efbb4d85aea372010c7c5"
IMGUI_COMMIT = "b1bcb12a624af7509894c8e77dd47416997777fa"
NATIVE_FILES = (
"_common.h", "_internal.h", "imconfig.h",
"jni_jvm", "jni_common", "jni_binding_struct", "jni_callbacks", "jni_assertion", "jni_internal",
)
def write_if_changed(path, data):
if not path.is_file() or path.read_bytes() != data:
path.write_bytes(data)
def download(url, destination):
if not destination.is_file():
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=destination.parent, suffix=".download", delete=False) as output:
temporary = Path(output.name)
try:
with urllib.request.urlopen(url, timeout=60) as response:
shutil.copyfileobj(response, output)
except BaseException:
output.close()
temporary.unlink(missing_ok=True)
raise
try:
if not destination.is_file():
try:
temporary.replace(destination)
except PermissionError:
if not destination.is_file():
raise
finally:
temporary.unlink(missing_ok=True)
return destination
def archive(repository, commit, cache):
path = download(f"https://codeload.github.com/{repository}/zip/{commit}",
cache / "downloads" / f"{repository.split('/')[-1]}-{commit}.zip")
return zipfile.ZipFile(path)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--build-dir", type=Path, default=ROOT / "build/imgui-core")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--toolchain", type=Path)
parser.add_argument("--architecture", choices=("x64", "ARM64"))
parser.add_argument("--cache-dir", type=Path)
parser.add_argument("--zig-target", choices=(
"x86_64-windows-gnu", "aarch64-windows-gnu",
"x86_64-linux-gnu.2.17", "aarch64-linux-gnu.2.17",
"x86_64-macos.11.0", "aarch64-macos.11.0",
))
args = parser.parse_args()
# cmd.exe cannot use extended-length (\\?\) working directory paths.
build = Path(os.path.abspath(args.build_dir))
cache = Path(os.path.abspath(args.cache_dir)) if args.cache_dir else build
output = Path(os.path.abspath(args.output))
generated = build / "jni"
sources = build / "sources"
for directory in (build, output, generated, sources):
directory.mkdir(parents=True, exist_ok=True)
dependencies = []
for group, artifact, version in (
("com.badlogicgames.gdx", "gdx-jnigen", "2.5.2"),
("com.badlogicgames.gdx", "gdx-jnigen-loader", "2.5.2"),
("com.github.javaparser", "javaparser-core", "3.14.14"),
("io.github.spair", "imgui-java-binding", "1.92.7.1"),
):
name = f"{artifact}-{version}.jar"
dependencies.append(download(
f"https://repo.maven.apache.org/maven2/{group.replace('.', '/')}/{artifact}/{version}/{name}",
cache / "deps" / name,
))
binding = dependencies[-1]
with zipfile.ZipFile(dependencies[0]) as generator:
header_prefix = "com/badlogic/gdx/jnigen/resources/headers/"
for entry in generator.infolist():
if entry.filename.startswith(header_prefix) and not entry.is_dir():
destination = generated / "jni-headers" / entry.filename[len(header_prefix):]
destination.parent.mkdir(parents=True, exist_ok=True)
write_if_changed(destination, generator.read(entry))
with archive("SpaiR/imgui-java", BINDING_COMMIT, cache) as upstream:
prefix = upstream.namelist()[0]
java_prefix = prefix + "imgui-binding/src/generated/java/"
native_prefix = prefix + "imgui-binding/src/main/native/"
for entry in upstream.infolist():
if entry.filename.startswith(java_prefix) and entry.filename.endswith(".java"):
relative = entry.filename[len(java_prefix):]
if relative.startswith(("imgui/extension/", "imgui/lwjgl3/")):
continue
target = sources / relative
target.parent.mkdir(parents=True, exist_ok=True)
write_if_changed(target, upstream.read(entry))
if entry.filename.startswith(native_prefix):
name = entry.filename[len(native_prefix):]
if name in NATIVE_FILES or name.rsplit(".", 1)[0] in NATIVE_FILES:
write_if_changed(generated / name, upstream.read(entry))
write_if_changed(output / "LICENSE-imgui-java.txt", upstream.read(prefix + "LICENSE"))
with archive("ocornut/imgui", IMGUI_COMMIT, cache) as upstream:
prefix = upstream.namelist()[0]
for entry in upstream.infolist():
name = entry.filename[len(prefix):]
if "/" not in name and name.endswith((".h", ".cpp")) and name != "imconfig.h":
write_if_changed(generated / name, upstream.read(entry))
write_if_changed(output / "LICENSE-imgui.txt", upstream.read(prefix + "LICENSE.txt"))
java_home = os.environ.get("JAVA_HOME")
java = str(Path(java_home) / "bin/java") if java_home else shutil.which("java")
if not java:
raise RuntimeError("Set JAVA_HOME to a JDK.")
env = os.environ.copy()
if java_home:
env["PATH"] = str(Path(java_home) / "bin") + os.pathsep + env["PATH"]
# jnigen constructs its javac command as a string. Relative paths avoid its
# whitespace bug without depending on Windows short filename support.
write_if_changed(build / "binding.jar", binding.read_bytes())
subprocess.run([
java, "-cp", os.pathsep.join(map(str, dependencies)),
str(ROOT / "scripts/imgui-core/GenerateCore.java"),
"sources", "binding.jar", "jni",
], check=True, env=env, cwd=build)
# Upstream's GNU builds accept variable-length arrays. Use standard C++
# storage in generated JNI code so the identical methods also build in MSVC.
declaration = re.compile(r"\b(ImVec2|const char\*|jlong)\s+(\w+)\[(\w+)\];")
for source in generated.glob("imgui_*.cpp"):
text = source.read_text(encoding="utf-8")
text, count = declaration.subn(
lambda match: f"std::vector<{match[1]}> {match[2]}Storage({match[3]});\n"
f" auto* {match[2]} = {match[2]}Storage.data();",
text,
)
if count:
source.write_text("#include <vector>\n" + text, encoding="utf-8")
configuration = [
"cmake", "-S", str(ROOT / "scripts/imgui-core"), "-B", str(build / "cmake"),
f"-DCORE_JNI_DIR={generated.as_posix()}", f"-DCORE_OUTPUT_DIR={output.as_posix()}", "-DCMAKE_BUILD_TYPE=Release",
]
if args.zig_target:
if args.toolchain or args.architecture:
parser.error("--zig-target cannot be combined with --toolchain or --architecture")
import ziglang
executable = Path(ziglang.__file__).parent / ("zig.exe" if os.name == "nt" else "zig")
family = "Windows" if "windows" in args.zig_target else "Darwin" if "macos" in args.zig_target else "Linux"
toolchain = build / "zig-toolchain.cmake"
toolchain.write_text(
f'set(CMAKE_SYSTEM_NAME {family})\n'
f'set(CMAKE_SYSTEM_PROCESSOR {args.zig_target.split("-")[0]})\n'
f'set(CMAKE_CXX_COMPILER "{executable.as_posix()}")\n'
f'set(CMAKE_CXX_COMPILER_ARG1 "c++ -target {args.zig_target} -Wno-nullability-completeness")\n',
encoding="utf-8",
)
configuration.extend(("-G", "Ninja", f"-DCMAKE_TOOLCHAIN_FILE={toolchain.as_posix()}"))
if args.toolchain:
configuration.append(f"-DCMAKE_TOOLCHAIN_FILE={args.toolchain.resolve().as_posix()}")
if args.architecture:
configuration.extend(("-A", args.architecture))
subprocess.run(configuration, check=True, env=env)
subprocess.run(["cmake", "--build", str(build / "cmake"), "--config", "Release", "--parallel", "4"],
check=True, env=env)
if __name__ == "__main__":
main()
+127
View File
@@ -0,0 +1,127 @@
"""Fetch and build every core ImGui native required by build-release.bat."""
import argparse
import importlib.util
import importlib.metadata
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import sysconfig
ROOT = Path(__file__).resolve().parents[1]
TARGETS = (
("windows-x86_64", "x86_64-windows-gnu", "imgui-java64.dll"),
("windows-aarch64", "aarch64-windows-gnu", "imgui-java64.dll"),
("linux-x86_64", "x86_64-linux-gnu.2.17", "libimgui-java64.so"),
("linux-aarch64", "aarch64-linux-gnu.2.17", "libimgui-java64.so"),
("macos-x86_64", "x86_64-macos.11.0", "libimgui-java64.dylib"),
("macos-aarch64", "aarch64-macos.11.0", "libimgui-java64.dylib"),
)
def ensure_tools():
scripts = Path(sys.executable).parent / "Scripts"
user_scheme = "nt_user" if os.name == "nt" else "posix_user"
user_scripts = Path(sysconfig.get_path("scripts", scheme=user_scheme))
os.environ["PATH"] = os.pathsep.join((str(scripts), str(user_scripts), os.environ["PATH"]))
missing = [tool for tool in ("cmake", "ninja") if not shutil.which(tool)]
if importlib.util.find_spec("ziglang") is None or importlib.metadata.version("ziglang") != "0.16.0":
missing.append("ziglang==0.16.0")
if missing:
subprocess.run([sys.executable, "-m", "pip", "install", "--user", *missing], check=True)
for tool in ("cmake", "ninja"):
if not shutil.which(tool):
raise RuntimeError(f"{tool} is unavailable after installation. Add the Python Scripts directory to PATH.")
def universal(slices, destination):
images = [path.read_bytes() for path in slices]
records = []
offset = 16384
for image in images:
magic, cpu, subtype = struct.unpack_from("<III", image)
if magic != 0xFEEDFACF or cpu not in (0x01000007, 0x0100000C):
raise ValueError("The macOS build produced an unexpected Mach-O architecture.")
records.append((cpu, subtype, offset, len(image), 14))
offset = (offset + len(image) + 16383) & ~16383
if len({record[0] for record in records}) != 2:
raise ValueError("The universal library needs one Intel slice and one ARM64 slice.")
temporary = destination.with_suffix(".dylib.tmp")
with temporary.open("wb") as output:
output.write(struct.pack(">II", 0xCAFEBABE, len(images)))
for record in records:
output.write(struct.pack(">IIIII", *record))
for record, image in zip(records, images):
output.seek(record[2])
output.write(image)
temporary.replace(destination)
def validate_native(path, platform):
with path.open("rb") as library:
header = library.read(64)
if platform.startswith("windows-") and header[:2] == b"MZ":
library.seek(struct.unpack_from("<I", header, 60)[0])
signature, machine = struct.unpack("<4sH", library.read(6))
expected = 0xAA64 if platform.endswith("aarch64") else 0x8664
if signature == b"PE\0\0" and machine == expected:
return
elif platform.startswith("linux-") and header[:6] == b"\x7fELF\x02\x01":
expected = 183 if platform.endswith("aarch64") else 62
if struct.unpack_from("<H", header, 18)[0] == expected:
return
elif platform.startswith("macos-") and header[:4] == b"\xcf\xfa\xed\xfe":
expected = 0x0100000C if platform.endswith("aarch64") else 0x01000007
if struct.unpack_from("<I", header, 4)[0] == expected:
return
raise ValueError(f"The {platform} build produced a library with an unexpected architecture.")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--platform", choices=[item[0] for item in TARGETS],
help="Build one slice for troubleshooting. Default builds the full release set.")
args = parser.parse_args()
ensure_tools()
cache = ROOT / "build/imgui-core-cache"
for platform, target, filename in TARGETS:
if args.platform and args.platform != platform:
continue
print(f"Building small ImGui JNI for {platform}", flush=True)
output = ROOT / "build/core-natives" / platform
if platform.startswith("macos-"):
output = ROOT / "build/imgui-core-slices" / platform
work = ROOT / "build/imgui-core-release" / platform
work.mkdir(parents=True, exist_ok=True)
log_path = work / "build.log"
command = [
sys.executable, str(ROOT / "scripts/build_imgui_core.py"),
"--build-dir", str(work),
"--cache-dir", str(cache), "--output", str(output), "--zig-target", target,
]
with log_path.open("w", encoding="utf-8") as log:
result = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print("\n".join(log_path.read_text(encoding="utf-8", errors="replace").splitlines()[-40:]), flush=True)
raise RuntimeError(f"The {platform} build failed. Full log: {log_path}")
if not (output / filename).is_file():
raise RuntimeError(f"The {platform} build did not produce {filename}.")
validate_native(output / filename, platform)
print(f"Built {output / filename} ({(output / filename).stat().st_size:,} bytes)", flush=True)
if not args.platform:
destination = ROOT / "build/core-natives/macos-universal"
destination.mkdir(parents=True, exist_ok=True)
slices = ROOT / "build/imgui-core-slices"
universal([
slices / "macos-x86_64/libimgui-java64.dylib",
slices / "macos-aarch64/libimgui-java64.dylib",
], destination / "libimgui-java64.dylib")
for license_file in (slices / "macos-x86_64").glob("LICENSE-*.txt"):
shutil.copyfile(license_file, destination / license_file.name)
print("All five release ImGui native libraries are ready.", flush=True)
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""Split all remapped variants into version payloads and one shared library JAR."""
import contextlib
import shutil
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
VERSIONS = tuple(f"1.21.{patch}" for patch in range(1, 12))
def pack(inputs, destination):
"""Keep game classes version-local; share only byte-identical libraries/assets."""
with contextlib.ExitStack() as stack:
jars = {version: stack.enter_context(zipfile.ZipFile(path))
for version, path in inputs.items()}
for version, jar in jars.items():
actual = jar.read("prestige-engine/minecraft-version.txt").decode().strip()
if actual != version:
raise ValueError(f"{version}: payload targets {actual}")
first = next(iter(jars.values()))
candidates = {name for name in first.namelist()
if not name.endswith('/') and not name.startswith((
'dev/zprestige/', 'prestige-engine/', 'META-INF/'))
and name != 'fabric.mod.json' and not name.endswith((
'.mixins.json', '.accesswidener'))}
shared = {name: first.read(name) for name in sorted(candidates)
if all(name in jar.namelist() and jar.read(name) == first.read(name)
for jar in jars.values())}
destination.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(destination / 'common.jar', 'w', zipfile.ZIP_DEFLATED) as common:
for name, data in shared.items():
common.writestr(name, data)
for version, jar in jars.items():
with zipfile.ZipFile(destination / f'{version}.jar', 'w', zipfile.ZIP_DEFLATED) as payload:
for name in sorted(jar.namelist()):
if name not in shared and not name.endswith('/'):
payload.writestr(name, jar.read(name))
(destination / 'versions.txt').write_text('\n'.join(inputs) + '\n', encoding='utf-8')
def main():
inputs = {}
for version in VERSIONS:
candidates = [p for p in (ROOT / 'versions' / version / 'build/libs').glob('prestige-*.jar')
if not p.name.endswith(('-sources.jar', '-dev.jar'))]
if len(candidates) != 1:
raise ValueError(f'{version}: expected one remapped JAR, found {len(candidates)}; build all variants first')
inputs[version] = candidates[0]
# Stage only after every input is present. Never publish an incomplete version matrix.
(ROOT / 'build').mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=ROOT / 'build') as staging:
pack(inputs, Path(staging))
output = ROOT / 'build/bundle'
output.mkdir(parents=True, exist_ok=True)
for path in Path(staging).iterdir():
shutil.copy2(path, output / path.name)
print(f'Packed {len(inputs)} versions with common.jar in {output}')
if __name__ == '__main__':
main()
+58
View File
@@ -0,0 +1,58 @@
cmake_minimum_required(VERSION 3.20)
project(openprestige_imgui LANGUAGES CXX)
file(GLOB GENERATED CONFIGURE_DEPENDS "${CORE_JNI_DIR}/imgui_*.cpp")
add_library(imgui-java64 SHARED
${GENERATED}
"${CORE_JNI_DIR}/imgui.cpp"
"${CORE_JNI_DIR}/imgui_draw.cpp"
"${CORE_JNI_DIR}/imgui_tables.cpp"
"${CORE_JNI_DIR}/imgui_widgets.cpp"
"${CORE_JNI_DIR}/imgui_demo.cpp"
"${CORE_JNI_DIR}/jni_jvm.cpp"
"${CORE_JNI_DIR}/jni_common.cpp"
"${CORE_JNI_DIR}/jni_binding_struct.cpp"
"${CORE_JNI_DIR}/jni_callbacks.cpp"
"${CORE_JNI_DIR}/jni_assertion.cpp"
"${CORE_JNI_DIR}/jni_internal.cpp"
)
target_compile_features(imgui-java64 PRIVATE cxx_std_17)
if(WIN32)
set(JNI_OS win32)
elseif(APPLE)
set(JNI_OS mac)
else()
set(JNI_OS linux)
endif()
target_include_directories(imgui-java64 PRIVATE
"${CORE_JNI_DIR}"
"${CORE_JNI_DIR}/jni-headers"
"${CORE_JNI_DIR}/jni-headers/${JNI_OS}"
)
target_compile_definitions(imgui-java64 PRIVATE IMGUI_DISABLE_DEMO_WINDOWS)
set_target_properties(imgui-java64 PROPERTIES
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN YES
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
LIBRARY_OUTPUT_DIRECTORY "${CORE_OUTPUT_DIR}"
RUNTIME_OUTPUT_DIRECTORY "${CORE_OUTPUT_DIR}"
RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CORE_OUTPUT_DIR}"
)
if(MSVC)
target_compile_options(imgui-java64 PRIVATE /O1 /Gy /GL /utf-8)
target_link_options(imgui-java64 PRIVATE /LTCG /OPT:REF /OPT:ICF)
else()
target_compile_options(imgui-java64 PRIVATE -Os -ffunction-sections -fdata-sections)
if(APPLE)
target_link_options(imgui-java64 PRIVATE -Wl,-dead_strip)
else()
target_link_options(imgui-java64 PRIVATE -Wl,--gc-sections -s)
endif()
if(MINGW)
target_link_options(imgui-java64 PRIVATE -static-libgcc -static-libstdc++)
endif()
endif()
if(WIN32)
set_target_properties(imgui-java64 PROPERTIES PREFIX "")
target_link_libraries(imgui-java64 PRIVATE imm32 user32)
endif()
+8
View File
@@ -0,0 +1,8 @@
import com.badlogic.gdx.jnigen.NativeCodeGenerator;
public final class GenerateCore {
public static void main(String[] args) throws Exception {
new NativeCodeGenerator().generate(args[0], args[1], args[2], null,
new String[] {"**/extension/**", "**/lwjgl3/**"});
}
}
+49
View File
@@ -0,0 +1,49 @@
# Core ImGui JNI build
OpenPrestige uses core ImGui with its Java OpenGL backend. This build keeps all core and internal
JNI methods from imgui-java 1.92.7.1, and removes the native extension implementations for ImPlot,
ImNodes, ImGuizmo, imgui-node-editor, text editor, file dialog, knobs, and memory editor. Demo
windows are disabled. Core callbacks, font rendering, tables, docking, and draw lists remain available.
The source revisions and generator dependencies are pinned in `../build_imgui_core.py`.
The build consumes upstream generated Java without modifying it. A portability step replaces
GNU variable-length arrays in the generated C++ with standard C++ vectors for MSVC.
## Windows x64
Set `JAVA_HOME` to JDK 21 and install Visual Studio C++ tools and CMake. From the repository root run
```powershell
python scripts/build_imgui_core.py --output build/core-natives/windows-x86_64 --architecture x64
```
The output contains `imgui-java64.dll` and the upstream licenses. Gradle picks up
`build/core-natives`, embeds it under `prestige-natives`, and omits the corresponding upstream
native. The Java extension wrappers are omitted from the shaded payload.
Use a distinct `--build-dir` for each target. ARM64 cross builds use the toolchain files in
`toolchains`, which require LLVM-MinGW on Windows targets and an aarch64 Linux cross compiler on
Linux targets. The macOS toolchain produces a universal library. CI builds all five variants.
## Full release build on Windows
`build-release.bat` calls `python scripts/build_release_imgui.py` before Gradle builds the JAR.
The helper fetches the pinned sources and generator dependencies, installs CMake, Ninja and Zig
when needed, and builds Windows and Linux x64/ARM64 plus both macOS slices. It combines the macOS
slices into a universal library. Downloads are cached in `build/imgui-core-cache`, and compilation
is incremental under `build/imgui-core-release`.
The complete release still requires JDK 21, Rust, and the MSVC x64/ARM64 build tools used by the
Rust Windows targets. Python's package installer needs network access on the first run.
To diagnose one cross build, use `python scripts/build_release_imgui.py --platform windows-aarch64`.
Running the helper without arguments builds the entire ImGui release set.
## JNI verification
```powershell
java -Dimgui.library.path=build/core-natives/windows-x86_64 -cp build/imgui-core/deps/imgui-java-binding-1.92.7.1.jar scripts/imgui-core/SmokeTest.java src/main/resources/prestige_ui/fonts/DMSans-Regular.ttf
```
This initializes JNI, builds the real UI font atlas, and generates geometry from widgets and draw
lists. A Minecraft smoke test should additionally exercise the ClickGUI and OpenGL backend.
+59
View File
@@ -0,0 +1,59 @@
import imgui.ImDrawList;
import imgui.ImFontConfig;
import imgui.ImGui;
import imgui.ImGuiIO;
import imgui.type.ImInt;
import imgui.type.ImString;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
/** Exercises core JNI entry points, real UI fonts, input widgets and draw data without a game. */
public final class SmokeTest {
public static void main(String[] args) throws Exception {
ImGui.createContext();
try {
ImGuiIO io = ImGui.getIO();
io.setIniFilename(null);
io.setDisplaySize(1000, 600);
io.setDeltaTime(1.0f / 60);
ImFontConfig config = new ImFontConfig();
try {
config.setPixelSnapH(true);
io.getFonts().addFontFromMemoryTTF(Files.readAllBytes(Path.of(args[0])), 18, config);
} finally {
config.destroy();
}
if (!io.getFonts().build()) throw new AssertionError("Font atlas did not build");
ImInt width = new ImInt();
ImInt height = new ImInt();
ByteBuffer pixels = io.getFonts().getTexDataAsRGBA32(width, height);
if (pixels == null || width.get() <= 0 || height.get() <= 0) {
throw new AssertionError("Font atlas is empty");
}
ImString input = new ImString("OpenPrestige", 64);
float[] value = {0.5f};
int vertices = 0;
for (int frame = 0; frame < 3; frame++) {
ImGui.newFrame();
ImGui.setNextWindowSize(500, 350);
ImGui.begin("Core JNI smoke test");
ImGui.text("OpenPrestige core-only ImGui");
ImGui.button("Inject");
ImGui.sliderFloat("Scale", value, 0, 1);
ImGui.inputText("Config name", input);
ImDrawList draw = ImGui.getWindowDrawList();
draw.addCircleFilled(100, 100, 20, 0xff80a0ff);
draw.addText(120, 100, 0xffffffff, "Draw list");
ImGui.end();
ImGui.render();
vertices = ImGui.getDrawData().getTotalVtxCount();
}
if (vertices <= 0) throw new AssertionError("No UI geometry was generated");
System.out.println("Core JNI passed. Font atlas " + width.get() + "x" + height.get()
+ ", vertices " + vertices);
} finally {
ImGui.destroyContext();
}
}
}
@@ -0,0 +1,3 @@
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
@@ -0,0 +1,2 @@
set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64" CACHE STRING "" FORCE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "11.0" CACHE STRING "" FORCE)
@@ -0,0 +1,4 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_CXX_COMPILER aarch64-w64-mingw32-clang++)
set(CMAKE_RC_COMPILER aarch64-w64-mingw32-windres)
@@ -0,0 +1,4 @@
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-clang++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
+30 -80
View File
@@ -1,9 +1,7 @@
"""Packs one platform's release zip, or writes SHA256SUMS.txt for dist/release. Called by release.bat.
"""Package openprestige releases.
package_release.py zip <out_dir> <version> <platform> <injector> <native_lib> <payload_jar>
package_release.py offline <out_dir> <version> <platform> <injector> <native_lib> <payload_jar>
package_release.py checksums <out_dir>
Zips are written with unix permissions so PrestigeInjector stays executable after unzip on Linux/macOS.
"""
import hashlib
import os
@@ -11,69 +9,7 @@ import sys
import time
import zipfile
README = {
"windows": """Prestige {version} - Windows (x86_64)
Contents
PrestigeInjector.exe injector
prestige_native.dll loader library (keep it next to the injector)
{jar} the same client as a Fabric mod (optional, see below)
Inject
1. Start Minecraft 1.21.11 with Fabric Loader 0.19+ and Fabric API.
2. Run PrestigeInjector.exe and pick the game from the list.
If SmartScreen blocks the exe: More info -> Run anyway.
""",
"linux": """Prestige {version} - Linux (x86_64)
Works on any glibc distro from 2012 on (glibc 2.17+): Ubuntu, Debian, Fedora, Arch, Mint, openSUSE, ...
Not for musl distros (Alpine) or ARM machines.
Contents
PrestigeInjector injector
libprestige_native.so loader library (keep it next to the injector)
{jar} the same client as a Fabric mod (optional, see below)
Inject
1. Start Minecraft 1.21.11 with Fabric Loader 0.19+ and Fabric API.
2. In a terminal in this folder: ./PrestigeInjector
Run it as the same user as the game. The game must not use -XX:+DisableAttachMechanism.
""",
"macos": """Prestige {version} - macOS (universal: Intel + Apple Silicon)
Contents
PrestigeInjector injector
libprestige_native.dylib loader library (keep it next to the injector)
{jar} the same client as a Fabric mod (optional, see below)
Inject
1. Start Minecraft 1.21.11 with Fabric Loader 0.19+ and Fabric API.
2. In Terminal, in this folder, clear the download quarantine once:
xattr -dr com.apple.quarantine .
3. Run: ./PrestigeInjector
Run it as the same user as the game. The game must not use -XX:+DisableAttachMechanism.
""",
}
MOD_NOTE = """
Install as a mod instead
Put {jar} into the mods/ folder of a Fabric 1.21.11 instance; no injector needed.
Do not use both at once.
"""
TESTED = "Tested on Prism Launcher with Minecraft 1.21.11 + Fabric.\n"
FOOTER = """
Credits
Cracked by Skid Solutions
technix sourcing / Frida scripts
stutheguyy fixing
bynbang / nitrogenoliquido ZKM transformers
dario AI models
Discord: https://discord.gg/x2FJyGrDNg
"""
FOOTER = '\nCredits\n Cracked by Skid Solutions\n technix sourcing / Frida scripts\n stutheguyy fixing\n bynbang / nitrogenoliquido ZKM transformers\n dario AI models\n\nDiscord: https://discord.gg/x2FJyGrDNg\n'
def add(zf, arcname, data, mode):
@@ -85,19 +21,33 @@ def add(zf, arcname, data, mode):
def make_zip(out_dir, version, platform, injector, lib, jar):
family = platform.split("-")[0]
name = f"prestige-{version}-{platform}"
jar_name = os.path.basename(jar)
title, body = README[family].format(version=version, jar=jar_name).split("\n", 1)
readme = title + "\n" + TESTED + body + MOD_NOTE.format(jar=jar_name) + FOOTER
if family == "windows":
readme = readme.replace("\n", "\r\n")
if platform in ("windows-aarch64", "linux-aarch64"):
native = "imgui-java64.dll" if platform.startswith("windows") else "libimgui-java64.so"
with zipfile.ZipFile(jar) as payload:
entry = f"prestige-natives/{platform}/{native}"
if entry not in payload.namelist():
raise ValueError(f"ARM64 payload is missing {entry}. Build the core ImGui natives first.")
name = f"openprestige-{version}-{platform}"
out = os.path.join(out_dir, name + ".zip")
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
for path, mode in ((injector, 0o755), (lib, 0o644), (jar, 0o644)):
with open(path, "rb") as f:
add(zf, f"{name}/{os.path.basename(path)}", f.read(), mode)
add(zf, f"{name}/README.txt", readme.encode(), 0o644)
os.makedirs(out_dir, exist_ok=True)
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
executable = "OpenPrestigeInjector" + (".exe" if platform.startswith("windows-") else "")
for path, filename, permissions in ((injector, executable, 0o755), (lib, os.path.basename(lib), 0o644)):
with open(path, "rb") as file:
add(bundle, f"{name}/{filename}", file.read(), permissions)
readme = (f"OpenPrestige {version} - {platform}\n\n"
f"Extract this complete folder and run {executable}.\n"
"Original CLI: Up/Down selects a Minecraft JVM, Enter injects, Esc quits.\n"
f"Keep {os.path.basename(lib)} beside the executable.\n"
"The native library embeds its payload. No external JAR or runtime download is required.\n"
"It selects the exact game version and stores common libraries once.\n"
"The launcher has no downloader or update checks.\n\n"
"Requires a 64-bit Minecraft 1.21.1 through 1.21.11 Fabric JVM.\n"
"Linux/macOS: run from a terminal as the same user as the game; attach must be enabled.\n"
"The Fabric mod JAR is available separately. Use either injection or the mod.\n"
"All versions have build and startup checks; Dawn gameplay still needs per-version verification.\n"
+ FOOTER)
add(bundle, f"{name}/README.txt", readme.encode(), 0o644)
print(f" wrote {out} ({os.path.getsize(out) // 1024} KiB)")
@@ -114,7 +64,7 @@ def checksums(out_dir):
if __name__ == "__main__":
if len(sys.argv) == 8 and sys.argv[1] == "zip":
if len(sys.argv) == 8 and sys.argv[1] == "offline":
make_zip(*sys.argv[2:])
elif len(sys.argv) == 3 and sys.argv[1] == "checksums":
checksums(sys.argv[2])
+48
View File
@@ -0,0 +1,48 @@
"""Check this repository's release contents and architecture requirements."""
import contextlib
import hashlib
import io
from pathlib import Path
import tempfile
import unittest
import zipfile
import package_release
class ReleasePackaging(unittest.TestCase):
def test_contents_and_checksums(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
injector = root / "injector.exe"
library = root / "prestige_native.dll"
jar = root / "prestige-1.2.3.jar"
injector.write_bytes(b"launcher")
library.write_bytes(b"library")
with zipfile.ZipFile(jar, "w") as payload:
payload.writestr("example.class", b"payload")
out = root / "release"
with contextlib.redirect_stdout(io.StringIO()):
package_release.make_zip(str(out), "1.2.3", "windows-x86_64", str(injector), str(library), str(jar))
archive = next(out.glob("*.zip"))
with zipfile.ZipFile(archive) as bundle:
names = {Path(name).name for name in bundle.namelist()}
self.assertEqual(names, {"OpenPrestigeInjector.exe", library.name, "README.txt"})
readme = bundle.read("openprestige-1.2.3-windows-x86_64/README.txt").decode()
self.assertIn("embeds its payload", readme)
self.assertNotIn("Keep the payload JAR beside", readme)
package_release.checksums(str(out))
expected = f"{hashlib.sha256(archive.read_bytes()).hexdigest()} {archive.name}\n"
self.assertEqual((out / "SHA256SUMS.txt").read_text(), expected)
def test_arm_native_required(self):
with tempfile.TemporaryDirectory() as directory:
jar = Path(directory) / "prestige-1.2.3.jar"
with zipfile.ZipFile(jar, "w"):
pass
with self.assertRaisesRegex(ValueError, "ARM64 payload is missing"):
package_release.make_zip(directory, "1.2.3", "windows-aarch64", "unused.exe", "unused.dll", str(jar))
if __name__ == "__main__":
unittest.main()
+13
View File
@@ -9,4 +9,17 @@ pluginManagement {
}
}
plugins {
id 'dev.kikugie.stonecutter' version '0.9.8'
}
rootProject.name = 'prestige'
stonecutter {
kotlinController = false
centralScript = 'build.gradle'
create(rootProject) {
versions '1.21.1', '1.21.2', '1.21.3', '1.21.4', '1.21.5', '1.21.6',
'1.21.7', '1.21.8', '1.21.9', '1.21.10', '1.21.11'
}
}
@@ -69,7 +69,7 @@ public class Module extends SettingHolder implements MinecraftAccess {
this.setLastEnabled(this.isEnabled());
if (this.isEnabled()) {
Prestige.eventBus.register(this);
if (mc.world != null && mc.player != null) {
if (!requiresWorldOnEnable() || (mc.world != null && mc.player != null)) {
this.onEnable();
} else {
Prestige.moduleManager.queueEnable(this);
@@ -89,7 +89,7 @@ public class Module extends SettingHolder implements MinecraftAccess {
public void applyState() {
if (this.isEnabled()) {
Prestige.eventBus.register(this);
if (mc.world != null && mc.player != null) {
if (!requiresWorldOnEnable() || (mc.world != null && mc.player != null)) {
this.onEnable();
} else {
Prestige.moduleManager.queueEnable(this);
@@ -123,6 +123,10 @@ public class Module extends SettingHolder implements MinecraftAccess {
public void onEnable() {
}
protected boolean requiresWorldOnEnable() {
return true;
}
public void onDisable() {
}
@@ -0,0 +1,42 @@
package dev.zprestige.prestige.client;
import java.nio.file.Path;
public final class AppPaths {
private static final Path ROOT = root();
private AppPaths() {}
public static Path configs() {
return ROOT.resolve("configs");
}
public static Path runtime() {
return ROOT.resolve("runtime");
}
private static Path root() {
String os = System.getProperty("os.name", "");
Path base;
if (os.startsWith("Windows")) {
base = env("APPDATA");
Path home = env("USERPROFILE");
if (base == null && home != null) base = home.resolve("AppData").resolve("Roaming");
} else {
Path home = env("HOME");
if (os.startsWith("Mac")) {
base = home == null ? null : home.resolve("Library").resolve("Application Support");
} else {
base = env("XDG_DATA_HOME");
if (base == null || !base.isAbsolute()) base = home == null ? null : home.resolve(".local").resolve("share");
}
}
if (base == null) base = Path.of(System.getProperty("java.io.tmpdir"));
return base.resolve(".openprestige");
}
private static Path env(String name) {
String value = System.getenv(name);
return value == null || value.isEmpty() ? null : Path.of(value);
}
}
@@ -34,11 +34,10 @@ import dev.zprestige.prestige.util.SimulatedClickManager;
import dev.zprestige.prestige.util.FrameDeltaTimer;
import dev.zprestige.prestige.util.NotificationManager;
import java.util.concurrent.atomic.AtomicBoolean;
import net.fabricmc.api.ModInitializer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ChatScreen;
public class Prestige implements ModInitializer {
public class Prestige {
private static final AtomicBoolean initialized = new AtomicBoolean(false);
private static final java.util.concurrent.atomic.AtomicInteger renderErrorCount = new java.util.concurrent.atomic.AtomicInteger();
public static EventBus eventBus;
@@ -160,8 +159,4 @@ public class Prestige implements ModInitializer {
}
}
@Override
public void onInitialize() {
this.init();
}
}
@@ -119,7 +119,11 @@ public class ExplosionDamageCalculator implements MinecraftAccess {
(float)damage,
mc.world.getDamageSources().explosion(null),
target.getArmor(),
//? if >=1.21.2 {
(float)target.getAttributeInstance(EntityAttributes.ARMOR_TOUGHNESS).getValue()
//? } else {
/* (float)target.getAttributeInstance(EntityAttributes.GENERIC_ARMOR_TOUGHNESS).getValue()
*///? }
);
damage = this.applyResistance(target, damage);
damage = applyProtectionEnchantments(target, damage, mc.world.getDamageSources().explosion(null));
@@ -148,7 +152,11 @@ public class ExplosionDamageCalculator implements MinecraftAccess {
(float)damage,
mc.world.getDamageSources().explosion(null),
target.getArmor(),
//? if >=1.21.2 {
(float)target.getAttributeInstance(EntityAttributes.ARMOR_TOUGHNESS).getValue()
//? } else {
/* (float)target.getAttributeInstance(EntityAttributes.GENERIC_ARMOR_TOUGHNESS).getValue()
*///? }
);
damage = this.applyResistance(target, damage);
damage = applyProtectionEnchantments(target, damage, mc.world.getDamageSources().explosion(null));
@@ -175,7 +183,11 @@ public class ExplosionDamageCalculator implements MinecraftAccess {
(float)damage,
mc.world.getDamageSources().explosion(null),
target.getArmor(),
//? if >=1.21.2 {
(float)target.getAttributeInstance(EntityAttributes.ARMOR_TOUGHNESS).getValue()
//? } else {
/* (float)target.getAttributeInstance(EntityAttributes.GENERIC_ARMOR_TOUGHNESS).getValue()
*///? }
);
damage = applyProtectionEnchantments(target, damage, mc.world.getDamageSources().explosion(null));
return damage < 0.0 ? 0.0 : damage;
@@ -210,7 +222,11 @@ public class ExplosionDamageCalculator implements MinecraftAccess {
(float)damage,
mc.world.getDamageSources().explosion(null),
target.getArmor(),
//? if >=1.21.2 {
(float)target.getAttributeInstance(EntityAttributes.ARMOR_TOUGHNESS).getValue()
//? } else {
/* (float)target.getAttributeInstance(EntityAttributes.GENERIC_ARMOR_TOUGHNESS).getValue()
*///? }
);
damage = applyProtectionEnchantments(target, damage, mc.world.getDamageSources().explosion(null));
return damage < 0.0 ? 0.0 : damage;
@@ -225,7 +241,7 @@ public class ExplosionDamageCalculator implements MinecraftAccess {
int protectionFactor = 0;
Object2IntMap enchantments = (Object2IntMap)ENCHANTMENT_BUFFER.get();
for (EquipmentSlot slot : AttributeModifierSlot.ARMOR) {
for (EquipmentSlot slot : new EquipmentSlot[]{EquipmentSlot.HEAD, EquipmentSlot.CHEST, EquipmentSlot.LEGS, EquipmentSlot.FEET}) {
collectEnchantments(target.getEquippedStack(slot), enchantments);
int protection = getEnchantmentLevel(enchantments, Enchantments.PROTECTION);
if (protection > 0) {
@@ -26,6 +26,7 @@ public final class PearlFollowSimulatedPearl extends PersistentProjectileEntity
if (hitResult.getType() != Type.MISS) {
this.onCollision(hitResult);
} else {
//? if >=1.21.2
this.tickBlockCollision();
if (!this.landed) {
Vec3d motion = this.getVelocity();
@@ -72,7 +73,15 @@ public final class PearlFollowSimulatedPearl extends PersistentProjectileEntity
this.setVelocity(scaledMotion);
this.setYaw((float)(MathHelper.atan2(scaledMotion.x, scaledMotion.z) * 180.0F / (float)Math.PI));
this.setPitch((float)(MathHelper.atan2(scaledMotion.y, scaledMotion.horizontalLength()) * 180.0F / (float)Math.PI));
//? if >=1.21.5 {
this.lastYaw = this.getYaw();
//? } else {
/* this.prevYaw = this.getYaw();
*///? }
//? if >=1.21.5 {
this.lastPitch = this.getPitch();
//? } else {
/* this.prevPitch = this.getPitch();
*///? }
}
}
@@ -27,6 +27,7 @@ public final class PearlTrajectorySimulatedPearl extends PersistentProjectileEnt
this.onCollision(hitResult);
}
//? if >=1.21.2
this.tickBlockCollision();
Vec3d motion = this.getVelocity();
double nextX = this.getX() + motion.x;
@@ -68,7 +69,15 @@ public final class PearlTrajectorySimulatedPearl extends PersistentProjectileEnt
this.setVelocity(scaledMotion);
this.setYaw((float)(MathHelper.atan2(scaledMotion.x, scaledMotion.z) * 180.0F / (float)Math.PI));
this.setPitch((float)(MathHelper.atan2(scaledMotion.y, scaledMotion.horizontalLength()) * 180.0F / (float)Math.PI));
//? if >=1.21.5 {
this.lastYaw = this.getYaw();
//? } else {
/* this.prevYaw = this.getYaw();
*///? }
//? if >=1.21.5 {
this.lastPitch = this.getPitch();
//? } else {
/* this.prevPitch = this.getPitch();
*///? }
}
}
@@ -27,6 +27,7 @@ public final class TrajectoriesSimulatedPearl extends PersistentProjectileEntity
this.onCollision(hitResult);
}
//? if >=1.21.2
this.tickBlockCollision();
Vec3d motion = this.getVelocity();
double nextX = this.getX() + motion.x;
@@ -68,7 +69,15 @@ public final class TrajectoriesSimulatedPearl extends PersistentProjectileEntity
this.setVelocity(scaledMotion);
this.setYaw((float)(MathHelper.atan2(scaledMotion.x, scaledMotion.z) * 180.0F / (float)Math.PI));
this.setPitch((float)(MathHelper.atan2(scaledMotion.y, scaledMotion.horizontalLength()) * 180.0F / (float)Math.PI));
//? if >=1.21.5 {
this.lastYaw = this.getYaw();
//? } else {
/* this.prevYaw = this.getYaw();
*///? }
//? if >=1.21.5 {
this.lastPitch = this.getPitch();
//? } else {
/* this.prevPitch = this.getPitch();
*///? }
}
}
@@ -82,28 +82,76 @@ public class VisualRotationManager implements MinecraftAccess {
this.savedPitch = mc.player.getPitch();
this.savedBodyYaw = mc.player.bodyYaw;
this.savedHeadYaw = mc.player.headYaw;
//? if >=1.21.5 {
this.savedLastYaw = mc.player.lastYaw;
//? } else {
/* this.savedLastYaw = mc.player.prevYaw;
*///? }
//? if >=1.21.5 {
this.savedLastPitch = mc.player.lastPitch;
//? } else {
/* this.savedLastPitch = mc.player.prevPitch;
*///? }
//? if >=1.21.5 {
this.savedLastBodyYaw = mc.player.lastBodyYaw;
//? } else {
/* this.savedLastBodyYaw = mc.player.prevBodyYaw;
*///? }
//? if >=1.21.5 {
this.savedLastHeadYaw = mc.player.lastHeadYaw;
//? } else {
/* this.savedLastHeadYaw = mc.player.prevHeadYaw;
*///? }
mc.player.setYaw(this.renderYaw);
mc.player.setPitch(this.renderPitch);
mc.player.bodyYaw = this.renderYaw;
mc.player.headYaw = this.renderYaw;
//? if >=1.21.5 {
mc.player.lastYaw = this.prevRenderYaw;
//? } else {
/* mc.player.prevYaw = this.prevRenderYaw;
*///? }
//? if >=1.21.5 {
mc.player.lastPitch = this.prevRenderPitch;
//? } else {
/* mc.player.prevPitch = this.prevRenderPitch;
*///? }
//? if >=1.21.5 {
mc.player.lastBodyYaw = this.prevRenderYaw;
//? } else {
/* mc.player.prevBodyYaw = this.prevRenderYaw;
*///? }
//? if >=1.21.5 {
mc.player.lastHeadYaw = this.prevRenderYaw;
//? } else {
/* mc.player.prevHeadYaw = this.prevRenderYaw;
*///? }
this.applied = true;
} else if (event.getPhase() == EventPhase.POST && this.applied) {
mc.player.setYaw(this.savedYaw);
mc.player.setPitch(this.savedPitch);
mc.player.bodyYaw = this.savedBodyYaw;
mc.player.headYaw = this.savedHeadYaw;
//? if >=1.21.5 {
mc.player.lastYaw = this.savedLastYaw;
//? } else {
/* mc.player.prevYaw = this.savedLastYaw;
*///? }
//? if >=1.21.5 {
mc.player.lastPitch = this.savedLastPitch;
//? } else {
/* mc.player.prevPitch = this.savedLastPitch;
*///? }
//? if >=1.21.5 {
mc.player.lastBodyYaw = this.savedLastBodyYaw;
//? } else {
/* mc.player.prevBodyYaw = this.savedLastBodyYaw;
*///? }
//? if >=1.21.5 {
mc.player.lastHeadYaw = this.savedLastHeadYaw;
//? } else {
/* mc.player.prevHeadYaw = this.savedLastHeadYaw;
*///? }
this.applied = false;
}
}
@@ -12,7 +12,11 @@ import net.minecraft.resource.ResourcePack;
import net.minecraft.resource.ResourcePackInfo;
import net.minecraft.resource.ResourceType;
import net.minecraft.resource.ResourcePack.ResultConsumer;
//? if >=1.21.4 {
import net.minecraft.resource.metadata.ResourceMetadataSerializer;
//? } else {
/*import net.minecraft.resource.metadata.ResourceMetadataReader;
*///? }
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
@@ -40,7 +44,11 @@ public class ClasspathResourcePack implements ResourcePack {
@Nullable
@Override
//? if >=1.21.4 {
public Object parseMetadata(ResourceMetadataSerializer metadataSerializer) throws IOException {
//? } else {
/* public Object parseMetadata(ResourceMetadataReader metadataSerializer) throws IOException {
*///? }
return null;
}
@@ -22,11 +22,13 @@ public record OutlineCaptureConsumer(MeshBuilder writer) implements VertexConsum
return this;
}
//? if >=1.21.11 {
@Override
public VertexConsumer lineWidth(float width) {
return this;
}
//? }
@Override
public VertexConsumer texture(float u, float v) {
this.writer.putFloats(new float[]{u, v});
@@ -65,6 +65,7 @@ public final class EngineDev implements ClientModInitializer {
switch (cmd) {
case "wait" -> waitTicks = Integer.parseInt(arg);
case "report" -> log(EngineState.details());
case "loadnative" -> System.load(Path.of(arg).toAbsolutePath().toString());
case "injectselftest" -> log(dev.zprestige.prestige.inject.SelfTest.run());
case "listeners" -> {
String text = DevCmd.listeners();
@@ -131,7 +132,11 @@ public final class EngineDev implements ClientModInitializer {
case "server" -> {
var server = mc.getServer();
if (server == null) { log("no integrated server"); return; }
//? if >=1.21.10 {
server.execute(() -> server.getCommandManager().parseAndExecute(server.getCommandSource(), arg));
//? } else {
/* server.execute(() -> server.getCommandManager().executeWithPrefix(server.getCommandSource(), arg));
*///? }
log("server command: " + arg);
}
case "newworld" -> { newWorldName = arg.isEmpty() ? "engine-test" : arg; newWorldStage = 1; }
@@ -144,27 +149,45 @@ public final class EngineDev implements ClientModInitializer {
case "shot" -> {
Path out = Path.of(arg).toAbsolutePath();
Files.createDirectories(out.getParent());
//? if >=1.21.5 {
ScreenshotRecorder.takeScreenshot(mc.getFramebuffer(), img -> {
try { img.writeTo(out); log("shot written " + out); } catch (Exception e) { log("shot failed " + e); } finally { img.close(); }
});
//? } else {
/* try (var img = ScreenshotRecorder.takeScreenshot(mc.getFramebuffer())) { img.writeTo(out); log("shot written " + out); }
*///? }
}
case "exit" -> { log("final: " + EngineState.details()); mc.scheduleStop(); }
default -> log("unknown command: " + line);
}
}
private static void openCreateWorld(MinecraftClient mc) {
//? if >=1.21.9 {
CreateWorldScreen.show(mc, () -> {});
//? } elif >=1.21.2 {
/*CreateWorldScreen.show(mc, mc.currentScreen);
*///? } else {
/*CreateWorldScreen.create(mc, mc.currentScreen);
*///? }
}
/** Creates a world through the vanilla Create World screen (default settings) and waits until the player exists. */
private static void newWorld(MinecraftClient mc) {
Screen s = mc.currentScreen;
switch (newWorldStage) {
case 1 -> { CreateWorldScreen.show(mc, () -> {}); newWorldStage = 2; waitTicks = 0; newWorldDelay = 40; }
case 1 -> { openCreateWorld(mc); newWorldStage = 2; waitTicks = 0; newWorldDelay = 40; }
case 2 -> {
if (newWorldDelay-- > 0) return;
if (s instanceof CreateWorldScreen) {
for (var c : s.children()) {
if (c instanceof ButtonWidget b && b.getMessage().getString().toLowerCase().contains("create new world")) {
try { ((net.minecraft.client.gui.widget.TextFieldWidget) findName(s)).setText(newWorldName); } catch (Throwable t) { log("name field: " + t); }
//? if >=1.21.9 {
b.onPress(null);
//? } else {
/* b.onPress();
*///? }
log("create world pressed: " + newWorldName);
newWorldStage = 3;
newWorldDelay = 20 * 120;
@@ -10,6 +10,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import net.fabricmc.loader.api.FabricLoader;
import net.lenni0451.classtransform.TransformerManager;
@@ -85,9 +86,15 @@ public final class EnginePlugin implements IMixinConfigPlugin {
/** Builds the ClassTransform manager for the given runtime namespace ("named" or "intermediary") and transformer class names. */
public static TransformerManager createManager(String namespace, List<String> transformers) throws IOException {
return createManager(namespace, transformers, null);
}
/** Injection can also supply bytes for generated classes that have no class-path resource. */
public static TransformerManager createManager(String namespace, List<String> transformers,
Function<Class<?>, byte[]> liveBytes) throws IOException {
ClassLoader loader = EnginePlugin.class.getClassLoader();
byte[] tiny = namespace.equals("named") ? null : resource("prestige-engine/mappings.tiny");
TransformerManager manager = new TransformerManager(new ResourceClassProvider(loader, new HashSet<>(transformers), tiny), tiny == null ? null : new ByteArrayInputStream(tiny));
TransformerManager manager = new TransformerManager(new ResourceClassProvider(loader, new HashSet<>(transformers), tiny, liveBytes), tiny == null ? null : new ByteArrayInputStream(tiny));
// A transformer whose target method does not exist in this runtime (Lunar's Genesis loader names some methods differently
// from the bundled mappings) is skipped on its own. CANCEL would drop every hook of the whole class and abort the injection.
manager.setFailStrategy(FailStrategy.CONTINUE);
@@ -99,12 +106,14 @@ public final class EnginePlugin implements IMixinConfigPlugin {
private static final class ResourceClassProvider implements IClassProvider {
private final ClassLoader loader;
private final Set<String> transformers;
private final Function<Class<?>, byte[]> liveBytes;
/** Named (Yarn) class name -> intermediary name, from the bundled mapping. Lunar's jar only has the intermediary files. */
private final Map<String, String> namedToIntermediary;
ResourceClassProvider(ClassLoader loader, Set<String> transformers, byte[] tiny) {
ResourceClassProvider(ClassLoader loader, Set<String> transformers, byte[] tiny, Function<Class<?>, byte[]> liveBytes) {
this.loader = loader;
this.transformers = transformers;
this.namedToIntermediary = classNames(tiny);
this.liveBytes = liveBytes;
}
private static Map<String, String> classNames(byte[] tiny) {
@@ -129,6 +138,18 @@ public final class EnginePlugin implements IMixinConfigPlugin {
in = loader.getResourceAsStream(slashed + ".class");
}
}
if (in == null && liveBytes != null) {
// MixinExtras defines LocalRefImpl at runtime without publishing a .class resource.
// Resolve without initialization, then ask the injection byte source for its actual definition.
try {
byte[] bytes = liveBytes.apply(Class.forName(slashed.replace('/', '.'), false, loader));
if (bytes != null && bytes.length != 0) {
return transformers.contains(slashed.replace('/', '.')) ? gate(bytes) : bytes;
}
} catch (ClassNotFoundException | LinkageError | RuntimeException e) {
throw new ClassNotFoundException(name + " (could not read generated class " + slashed + ")", e);
}
}
if (in == null) throw new ClassNotFoundException(name + " (missing resource " + slashed + ".class)");
try (InputStream stream = in) {
byte[] bytes = stream.readAllBytes();
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_4970$class_4971: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_4970$class_4971", remap = false, priority = 2000)
public abstract class I00 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_2248: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_2248", remap = false, priority = 2000)
public abstract class I01 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_309: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_309", remap = false, priority = 2000)
public abstract class I02 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_310: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_310", remap = false, priority = 2000)
public abstract class I03 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_312: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_312", remap = false, priority = 2000)
public abstract class I04 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_279: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_279", remap = false, priority = 2000)
public abstract class I05 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_329: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_329", remap = false, priority = 2000)
public abstract class I06 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_4603: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_4603", remap = false, priority = 2000)
public abstract class I07 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_437: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_437", remap = false, priority = 2000)
public abstract class I08 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_743: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_743", remap = false, priority = 2000)
public abstract class I09 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_742: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_742", remap = false, priority = 2000)
public abstract class I10 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_634: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_634", remap = false, priority = 2000)
public abstract class I11 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_746: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_746", remap = false, priority = 2000)
public abstract class I12 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_636: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_636", remap = false, priority = 2000)
public abstract class I13 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_640: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_640", remap = false, priority = 2000)
public abstract class I14 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_9919: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_9919", remap = false, priority = 2000)
public abstract class I15 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_702: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_702", remap = false, priority = 2000)
public abstract class I16 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_4184: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_4184", remap = false, priority = 2000)
public abstract class I17 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_757: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_757", remap = false, priority = 2000)
public abstract class I18 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_765: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_765", remap = false, priority = 2000)
public abstract class I19 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_9975: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_9975", remap = false, priority = 2000)
public abstract class I20 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_761: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_761", remap = false, priority = 2000)
public abstract class I21 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_852: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_852", remap = false, priority = 2000)
public abstract class I22 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_11683: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_11683", remap = false, priority = 2000)
public abstract class I23 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_8138$class_8141: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_8138$class_8141", remap = false, priority = 2000)
public abstract class I24 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_897: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_897", remap = false, priority = 2000)
public abstract class I25 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_922: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_922", remap = false, priority = 2000)
public abstract class I26 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_758: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_758", remap = false, priority = 2000)
public abstract class I27 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_759: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_759", remap = false, priority = 2000)
public abstract class I28 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_638: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_638", remap = false, priority = 2000)
public abstract class I29 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_1297: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_1297", remap = false, priority = 2000)
public abstract class I30 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_1309: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_1309", remap = false, priority = 2000)
public abstract class I31 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_1657: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_1657", remap = false, priority = 2000)
public abstract class I32 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_1799: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_1799", remap = false, priority = 2000)
public abstract class I33 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_2535: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_2535", remap = false, priority = 2000)
public abstract class I34 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_3294: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_3294", remap = false, priority = 2000)
public abstract class I35 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_3304: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_3304", remap = false, priority = 2000)
public abstract class I36 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_3218: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_3218", remap = false, priority = 2000)
public abstract class I37 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_5223: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_5223", remap = false, priority = 2000)
public abstract class I38 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_1937: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_1937", remap = false, priority = 2000)
public abstract class I39 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_2818: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_2818", remap = false, priority = 2000)
public abstract class I40 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.class_5868: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.class_5868", remap = false, priority = 2000)
public abstract class I41 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.block.AbstractBlock$AbstractBlockState: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.block.AbstractBlock$AbstractBlockState", remap = false, priority = 2000)
public abstract class N00 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.block.Block: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.block.Block", remap = false, priority = 2000)
public abstract class N01 {}
@@ -1,7 +0,0 @@
package dev.zprestige.prestige.engine.mixin;
import org.spongepowered.asm.mixin.Mixin;
/** Engine anchor for net.minecraft.client.Keyboard: gives Mixin a target so EnginePlugin.preApply runs the ClassTransform hooks on it. */
@Mixin(targets = "net.minecraft.client.Keyboard", remap = false, priority = 2000)
public abstract class N02 {}
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff. Show more