From 2140d6dfcb28fc32bae46596236df1b1ba74a762 Mon Sep 17 00:00:00 2001 From: MonsterMilo <108966405+MonsterMilo@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:46:56 +0000 Subject: [PATCH 1/2] Base: injector, Java core with hot-reload plugins, desktop app - native/agent: DLL that attaches to the game's JVM, finds Minecraft's class loader (mcp/srg/notch names) and starts the Java core on top of it - native/inject: finds Java game windows, loads the agent via LoadLibraryW - native/app: Prism.exe with Inject/Unload, auto-inject for Lunar 1.8.9, plugin list and log; agent + core embedded - java/api + java/core: plugin API, event bus, scheduler on the client thread, plugin manager with hot reload - tests/run.sh: end-to-end test against a stand-in game Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N1jsNaA8oesLoCYL6zeeF7 --- .cargo/config.toml | 3 + .github/workflows/build.yml | 43 + Cargo.lock | 2738 +++++++++++++++++ Cargo.toml | 14 + README.md | 58 + build.sh | 19 + docs/ARCHITECTURE.md | 57 + java/api/build.gradle | 3 + .../api/src/main/java/prism/api/EventBus.java | 14 + java/api/src/main/java/prism/api/Game.java | 19 + java/api/src/main/java/prism/api/Logger.java | 12 + java/api/src/main/java/prism/api/Plugin.java | 13 + .../main/java/prism/api/PluginContext.java | 22 + .../src/main/java/prism/api/PluginInfo.java | 21 + .../src/main/java/prism/api/Scheduler.java | 17 + .../src/main/java/prism/api/Subscription.java | 5 + .../prism/api/event/PluginDisableEvent.java | 12 + .../prism/api/event/PluginEnableEvent.java | 12 + .../java/prism/api/event/ShutdownEvent.java | 5 + java/build.gradle | 12 + java/core/build.gradle | 7 + java/core/src/main/java/prism/core/Bus.java | 67 + .../main/java/prism/core/ClientThread.java | 63 + .../src/main/java/prism/core/CoreLog.java | 70 + .../src/main/java/prism/core/GameImpl.java | 97 + .../core/src/main/java/prism/core/Native.java | 44 + .../main/java/prism/core/PluginManager.java | 289 ++ java/core/src/main/java/prism/core/Prism.java | 83 + java/core/src/main/java/prism/core/Tasks.java | 79 + java/example-plugin/build.gradle | 3 + .../src/main/java/example/ExamplePlugin.java | 15 + .../src/main/resources/plugin.properties | 4 + java/settings.gradle | 2 + native/agent/Cargo.toml | 23 + native/agent/src/boot.rs | 318 ++ native/agent/src/jvm.rs | 421 +++ native/agent/src/lib.rs | 178 ++ native/agent/src/log.rs | 40 + native/app/Cargo.toml | 15 + native/app/build.rs | 22 + native/app/src/files.rs | 182 ++ native/app/src/main.rs | 341 ++ native/inject/Cargo.toml | 18 + native/inject/src/lib.rs | 43 + native/inject/src/win.rs | 174 ++ tests/fake-game/src/launcher/Launcher.java | 22 + .../src/net/minecraft/client/Minecraft.java | 33 + .../net/minecraft/client/gui/GuiIngame.java | 5 + .../net/minecraft/client/gui/GuiNewChat.java | 7 + .../net/minecraft/util/ChatComponentText.java | 6 + .../net/minecraft/util/IChatComponent.java | 2 + tests/run.sh | 62 + 52 files changed, 5834 insertions(+) create mode 100644 .cargo/config.toml create mode 100644 .github/workflows/build.yml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100755 build.sh create mode 100644 docs/ARCHITECTURE.md create mode 100644 java/api/build.gradle create mode 100644 java/api/src/main/java/prism/api/EventBus.java create mode 100644 java/api/src/main/java/prism/api/Game.java create mode 100644 java/api/src/main/java/prism/api/Logger.java create mode 100644 java/api/src/main/java/prism/api/Plugin.java create mode 100644 java/api/src/main/java/prism/api/PluginContext.java create mode 100644 java/api/src/main/java/prism/api/PluginInfo.java create mode 100644 java/api/src/main/java/prism/api/Scheduler.java create mode 100644 java/api/src/main/java/prism/api/Subscription.java create mode 100644 java/api/src/main/java/prism/api/event/PluginDisableEvent.java create mode 100644 java/api/src/main/java/prism/api/event/PluginEnableEvent.java create mode 100644 java/api/src/main/java/prism/api/event/ShutdownEvent.java create mode 100644 java/build.gradle create mode 100644 java/core/build.gradle create mode 100644 java/core/src/main/java/prism/core/Bus.java create mode 100644 java/core/src/main/java/prism/core/ClientThread.java create mode 100644 java/core/src/main/java/prism/core/CoreLog.java create mode 100644 java/core/src/main/java/prism/core/GameImpl.java create mode 100644 java/core/src/main/java/prism/core/Native.java create mode 100644 java/core/src/main/java/prism/core/PluginManager.java create mode 100644 java/core/src/main/java/prism/core/Prism.java create mode 100644 java/core/src/main/java/prism/core/Tasks.java create mode 100644 java/example-plugin/build.gradle create mode 100644 java/example-plugin/src/main/java/example/ExamplePlugin.java create mode 100644 java/example-plugin/src/main/resources/plugin.properties create mode 100644 java/settings.gradle create mode 100644 native/agent/Cargo.toml create mode 100644 native/agent/src/boot.rs create mode 100644 native/agent/src/jvm.rs create mode 100644 native/agent/src/lib.rs create mode 100644 native/agent/src/log.rs create mode 100644 native/app/Cargo.toml create mode 100644 native/app/build.rs create mode 100644 native/app/src/files.rs create mode 100644 native/app/src/main.rs create mode 100644 native/inject/Cargo.toml create mode 100644 native/inject/src/lib.rs create mode 100644 native/inject/src/win.rs create mode 100644 tests/fake-game/src/launcher/Launcher.java create mode 100644 tests/fake-game/src/net/minecraft/client/Minecraft.java create mode 100644 tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java create mode 100644 tests/fake-game/src/net/minecraft/client/gui/GuiNewChat.java create mode 100644 tests/fake-game/src/net/minecraft/util/ChatComponentText.java create mode 100644 tests/fake-game/src/net/minecraft/util/IChatComponent.java create mode 100755 tests/run.sh diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..a42900a --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,3 @@ +# Cross-building the Windows binaries from Linux needs mingw-w64 (apt install mingw-w64). +[target.x86_64-pc-windows-gnu] +linker = "x86_64-w64-mingw32-gcc" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..accacad --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,43 @@ +name: build +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: { distribution: temurin, java-version: '21' } + - uses: gradle/actions/setup-gradle@v4 + with: { gradle-version: '8.14.3' } + - uses: dtolnay/rust-toolchain@stable + - run: tests/run.sh + + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: { distribution: temurin, java-version: '21' } + - uses: gradle/actions/setup-gradle@v4 + with: { gradle-version: '8.14.3' } + - uses: dtolnay/rust-toolchain@stable + - name: Build + shell: pwsh + run: | + cd java; gradle -q build; cd .. + cargo build --release -p prism-agent + $env:PRISM_AGENT_DLL = "$PWD\target\release\prism_agent.dll" + $env:PRISM_CORE_JAR = "$PWD\java\core\build\libs\prism-core-0.1.0.jar" + cargo build --release -p prism-app + New-Item -ItemType Directory -Force dist | Out-Null + Copy-Item target\release\Prism.exe dist\ + Copy-Item java\api\build\libs\prism-api-0.1.0.jar dist\prism-api.jar + Copy-Item java\example-plugin\build\libs\example-plugin-0.1.0.jar dist\example-plugin.jar + - uses: actions/upload-artifact@v4 + with: + name: prism-windows + path: dist/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1c7ff76 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2738 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.59.0", + "x11rb", +] + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.6", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775cfde491852059e386c4e1deb4aef381c617dc364184c6f6afee99b87c402b" +dependencies = [ + "bytemuck", + "emath", +] + +[[package]] +name = "eframe" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac2645a9bf4826eb4e91488b1f17b8eaddeef09396706b2f14066461338e24f" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-winit", + "egui_glow", + "glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "winapi", + "windows-sys 0.52.0", + "winit", +] + +[[package]] +name = "egui" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53eafabcce0cb2325a59a98736efe0bf060585b437763f8c476957fb274bb974" +dependencies = [ + "ahash", + "emath", + "epaint", + "log", + "nohash-hasher", +] + +[[package]] +name = "egui-winit" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a9c430f4f816340e8e8c1b20eec274186b1be6bc4c7dfc467ed50d57abc36c6" +dependencies = [ + "ahash", + "arboard", + "egui", + "log", + "raw-window-handle", + "smithay-clipboard", + "web-time", + "webbrowser", + "winit", +] + +[[package]] +name = "egui_glow" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e39bccc683cd43adab530d8f21a13eb91e80de10bcc38c3f1c16601b6f62b26" +dependencies = [ + "ahash", + "bytemuck", + "egui", + "glow", + "log", + "memoffset", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "emath" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1fe0049ce51d0fb414d029e668dd72eb30bc2b739bf34296ed97bd33df544f3" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "epaint" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a32af8da821bd4f43f2c137e295459ee2e1661d87ca8779dfa0eaf45d870e20f" +dependencies = [ + "ab_glyph", + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "log", + "nohash-hasher", + "parking_lot", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "483440db0b7993cf77a20314f08311dbe95675092405518c0677aa08c151a3ea" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glow" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d51fa363f025f5c111e03f13eda21162faeacb6911fe8caa0c0349f9cf0c4483" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prism-agent" +version = "0.1.0" +dependencies = [ + "jni-sys 0.3.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "prism-app" +version = "0.1.0" +dependencies = [ + "eframe", + "prism-inject", + "zip", +] + +[[package]] +name = "prism-inject" +version = "0.1.0" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.6", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5e94349 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] +resolver = "2" +members = ["native/agent", "native/inject", "native/app"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT" + +[profile.release] +opt-level = 3 +lto = true +strip = true +panic = "abort" diff --git a/README.md b/README.md new file mode 100644 index 0000000..31b1117 --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# Prism + +An open-source plugin platform for Minecraft 1.8.9. Prism loads into a running game +(Lunar Client first; Forge and vanilla next) and runs Java plugins inside it. + +> Status: **base only**. Injection, the Java core, plugin loading with hot reload and the +> desktop app work. Features come next, one at a time. + +## Using it + +1. Download `Prism.exe` from the latest build. +2. Start Lunar Client 1.8.9 and run `Prism.exe`. +3. Prism injects on its own (or press **Inject**). You'll see `[Prism] Loaded` in chat. +4. Drop plugin `.jar` files into the plugins folder (**Open folder** in the app). + Plugins reload by themselves when a jar changes. + +Everything lives in `%APPDATA%\Prism`: `plugins\`, `data\`, `logs\prism.log`. + +## Writing a plugin + +Compile against `prism-api.jar` (Java 8). Add a `plugin.properties` to the jar: + +```properties +id=example +name=Example +version=1.0.0 +main=example.ExamplePlugin +``` + +```java +public class ExamplePlugin implements Plugin { + @Override + public void onEnable(PluginContext ctx) { + ctx.game().chat("§dHello!"); + ctx.scheduler().every(1000, () -> { /* runs on the game thread */ }); + } +} +``` + +See [`java/example-plugin`](java/example-plugin) and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). + +## Building + +Needs Rust, a JDK 17+ and Gradle. On Linux, also `mingw-w64` and +`rustup target add x86_64-pc-windows-gnu` (it cross-compiles for Windows). + +```sh +./build.sh # dist/Prism.exe, dist/prism-api.jar, dist/example-plugin.jar +tests/run.sh # end-to-end test against a stand-in game (Linux) +``` + +## Good to know + +- Prism only runs inside your own game. It does not touch Lunar's files. +- Injecting into a client may be against that client's terms. Use it at your own risk. +- Some antivirus tools flag injectors. The full source is here so you can build it yourself. + +MIT licensed. diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..13e4c97 --- /dev/null +++ b/build.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Builds everything into dist/: Prism.exe (agent + core embedded), prism-api.jar, example-plugin.jar. +# On Linux this cross-compiles for Windows (needs mingw-w64 and `rustup target add x86_64-pc-windows-gnu`). +set -euo pipefail +cd "$(dirname "$0")" +TARGET_ARGS=() +OUT=target/release +if [[ "$(uname -s)" != MINGW* && "$(uname -s)" != MSYS* ]]; then + TARGET_ARGS=(--target x86_64-pc-windows-gnu); OUT=target/x86_64-pc-windows-gnu/release +fi +(cd java && gradle -q build) +cargo build --release "${TARGET_ARGS[@]}" -p prism-agent +PRISM_AGENT_DLL="$PWD/$OUT/prism_agent.dll" PRISM_CORE_JAR="$PWD/java/core/build/libs/prism-core-0.1.0.jar" \ + cargo build --release "${TARGET_ARGS[@]}" -p prism-app +mkdir -p dist +cp "$OUT/Prism.exe" dist/ +cp java/api/build/libs/prism-api-0.1.0.jar dist/prism-api.jar +cp java/example-plugin/build/libs/example-plugin-0.1.0.jar dist/example-plugin.jar +ls -la dist diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..da88b49 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,57 @@ +# How Prism works + +``` +Prism.exe (Rust) the game (javaw.exe) + ├─ finds games (window + jvm.dll) ┌───────────────────────────────────────┐ + ├─ writes bin\prism_agent-.dll ──▶│ prism_agent.dll (Rust) │ + │ and bin\prism-core-.jar │ ├─ JNI_GetCreatedJavaVMs → attach │ + └─ LoadLibraryW via remote thread │ ├─ finds Minecraft's class loader │ + │ ├─ URLClassLoader(core jar, game CL) │ + │ └─ prism.core.Prism.start(...) │ + │ prism-core.jar (Java 8 bytecode) │ + │ ├─ plugin manager (hot reload) │ + │ ├─ event bus, scheduler, logging │ + │ └─ plugins (each its own class loader)│ + └───────────────────────────────────────┘ +``` + +## Native side (`native/`) + +- **inject**: lists visible windows whose process has `jvm.dll` loaded, and loads the agent with + `VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread(LoadLibraryW)`. +- **agent**: `DllMain` starts a thread that attaches to the JVM as a daemon thread, gets JVMTI + (with `can_redefine_classes` for the hook system later) and waits until Minecraft is loaded. + It finds the game's class loader from the threads' context class loaders, falling back to + JVMTI `GetLoadedClasses`, and detects the names the client uses: + + | names | detected by | clients | + |---|---|---| + | `mcp` | `Minecraft.getMinecraft()` | Lunar | + | `srg` | `Minecraft.func_71410_x()` | Forge | + | `notch` | `ave.A()` | vanilla, OptiFine, Badlion | + + The core jar is loaded by a `URLClassLoader` whose parent is the game's loader, so core and + plugins can use Minecraft classes. The agent registers the natives of `prism.core.Native` + (log, unload, redefine class). +- **Unload**: the app creates `bin\unload-`. The agent calls `Prism.stop()`, unregisters its + natives, closes the core's class loader, detaches and frees the DLL. The game keeps running. +- Files are named per build (`-`), so a new version never needs to overwrite a DLL or jar + a running game still holds. + +## Java side (`java/`) + +- **api**: what plugins compile against (`Plugin`, `PluginContext`, `EventBus`, `Scheduler`, + `Game`, `Logger`). +- **core**: `Prism` (start/stop), `PluginManager`, `Bus`, `Tasks`, `ClientThread`. + - Plugins are copied to `cache\plugins\` before loading, so the original jar is never locked. + The folder is scanned every second; a changed jar is reloaded once it stops changing. + - Each plugin gets its own class loader and context. Its event handlers and tasks are removed + when it is disabled, and one failing plugin never affects another. + - Game state is only touched on the client thread. `Scheduler` runs work there through + `Minecraft#addScheduledTask`, found by its shape, so it works with every naming scheme. + +## Next steps (not built yet) + +- Hooks: patch game methods (JVMTI redefine + ASM) for ticks, rendering and input events. +- Packets: a Netty handler in the game's pipeline for packet events. +- In-game UI, updates, Forge and vanilla testing. diff --git a/java/api/build.gradle b/java/api/build.gradle new file mode 100644 index 0000000..98f78c7 --- /dev/null +++ b/java/api/build.gradle @@ -0,0 +1,3 @@ +// prism-api.jar: what plugins compile against. +base { archivesName = 'prism-api' } +java { withSourcesJar() } diff --git a/java/api/src/main/java/prism/api/EventBus.java b/java/api/src/main/java/prism/api/EventBus.java new file mode 100644 index 0000000..4b7c5bb --- /dev/null +++ b/java/api/src/main/java/prism/api/EventBus.java @@ -0,0 +1,14 @@ +package prism.api; + +import java.util.function.Consumer; + +/** + * Typed events. A handler for a class also receives its subclasses. + * Handlers run on the thread that posted the event; one failing handler never stops the others. + */ +public interface EventBus { + Subscription on(Class type, Consumer handler); + + /** Posts an event to every plugin. Returns the event so callers can read results back. */ + E post(E event); +} diff --git a/java/api/src/main/java/prism/api/Game.java b/java/api/src/main/java/prism/api/Game.java new file mode 100644 index 0000000..6fd0096 --- /dev/null +++ b/java/api/src/main/java/prism/api/Game.java @@ -0,0 +1,19 @@ +package prism.api; + +/** The running Minecraft client. */ +public interface Game { + /** + * Which class names this client uses: {@code "mcp"} (Lunar), {@code "srg"} (Forge) + * or {@code "notch"} (vanilla and vanilla-based clients). + */ + String mappings(); + + /** The game's class loader, for plugins that work with Minecraft classes directly. */ + ClassLoader classLoader(); + + /** + * Shows a message in the player's own chat (only they see it, nothing is sent to the server). + * Supports {@code §} colour codes. Safe to call from any thread. + */ + void chat(String message); +} diff --git a/java/api/src/main/java/prism/api/Logger.java b/java/api/src/main/java/prism/api/Logger.java new file mode 100644 index 0000000..2b6ff74 --- /dev/null +++ b/java/api/src/main/java/prism/api/Logger.java @@ -0,0 +1,12 @@ +package prism.api; + +/** Writes to Prism's log file (logs/prism.log). */ +public interface Logger { + void info(String msg); + + void warn(String msg); + + void error(String msg, Throwable t); + + default void error(String msg) { error(msg, null); } +} diff --git a/java/api/src/main/java/prism/api/Plugin.java b/java/api/src/main/java/prism/api/Plugin.java new file mode 100644 index 0000000..f9832fb --- /dev/null +++ b/java/api/src/main/java/prism/api/Plugin.java @@ -0,0 +1,13 @@ +package prism.api; + +/** + * Entry point of a Prism plugin. The class named by {@code main} in the plugin's + * {@code plugin.properties} must implement this and have a public no-argument constructor. + */ +public interface Plugin { + /** Called once when the plugin is loaded (also after every hot reload). */ + void onEnable(PluginContext ctx) throws Exception; + + /** Called before the plugin is unloaded. Subscriptions and tasks are cleaned up automatically. */ + default void onDisable() throws Exception {} +} diff --git a/java/api/src/main/java/prism/api/PluginContext.java b/java/api/src/main/java/prism/api/PluginContext.java new file mode 100644 index 0000000..e1f2bd3 --- /dev/null +++ b/java/api/src/main/java/prism/api/PluginContext.java @@ -0,0 +1,22 @@ +package prism.api; + +import java.nio.file.Path; + +/** Everything a plugin gets from Prism. One context per plugin, valid until it is disabled. */ +public interface PluginContext { + PluginInfo info(); + + Logger log(); + + /** Subscriptions made here are removed when the plugin is disabled. */ + EventBus events(); + + /** Tasks scheduled here are cancelled when the plugin is disabled. */ + Scheduler scheduler(); + + /** The game Prism is injected into. */ + Game game(); + + /** A folder for this plugin's own files (created on first call). */ + Path dataFolder(); +} diff --git a/java/api/src/main/java/prism/api/PluginInfo.java b/java/api/src/main/java/prism/api/PluginInfo.java new file mode 100644 index 0000000..3a17c17 --- /dev/null +++ b/java/api/src/main/java/prism/api/PluginInfo.java @@ -0,0 +1,21 @@ +package prism.api; + +/** Read from {@code plugin.properties} inside the plugin jar. */ +public final class PluginInfo { + private final String id, name, version, main; + + public PluginInfo(String id, String name, String version, String main) { + this.id = id; + this.name = name; + this.version = version; + this.main = main; + } + + public String id() { return id; } + public String name() { return name; } + public String version() { return version; } + public String main() { return main; } + + @Override + public String toString() { return name + " " + version; } +} diff --git a/java/api/src/main/java/prism/api/Scheduler.java b/java/api/src/main/java/prism/api/Scheduler.java new file mode 100644 index 0000000..fa94cdb --- /dev/null +++ b/java/api/src/main/java/prism/api/Scheduler.java @@ -0,0 +1,17 @@ +package prism.api; + +/** Runs code later or on the game's main (client) thread. Game state must only be touched there. */ +public interface Scheduler { + /** Runs on the client thread, as soon as the game gets to it. */ + void runOnClientThread(Runnable task); + + /** Runs once on the client thread after {@code delayMs}. */ + Task later(long delayMs, Runnable task); + + /** Runs on the client thread every {@code periodMs}, starting after one period. */ + Task every(long periodMs, Runnable task); + + interface Task { + void cancel(); + } +} diff --git a/java/api/src/main/java/prism/api/Subscription.java b/java/api/src/main/java/prism/api/Subscription.java new file mode 100644 index 0000000..8b12a83 --- /dev/null +++ b/java/api/src/main/java/prism/api/Subscription.java @@ -0,0 +1,5 @@ +package prism.api; + +public interface Subscription { + void cancel(); +} diff --git a/java/api/src/main/java/prism/api/event/PluginDisableEvent.java b/java/api/src/main/java/prism/api/event/PluginDisableEvent.java new file mode 100644 index 0000000..42d921e --- /dev/null +++ b/java/api/src/main/java/prism/api/event/PluginDisableEvent.java @@ -0,0 +1,12 @@ +package prism.api.event; + +import prism.api.PluginInfo; + +/** Posted before a plugin is disabled. */ +public final class PluginDisableEvent { + private final PluginInfo plugin; + + public PluginDisableEvent(PluginInfo plugin) { this.plugin = plugin; } + + public PluginInfo plugin() { return plugin; } +} diff --git a/java/api/src/main/java/prism/api/event/PluginEnableEvent.java b/java/api/src/main/java/prism/api/event/PluginEnableEvent.java new file mode 100644 index 0000000..93fd616 --- /dev/null +++ b/java/api/src/main/java/prism/api/event/PluginEnableEvent.java @@ -0,0 +1,12 @@ +package prism.api.event; + +import prism.api.PluginInfo; + +/** Posted after a plugin was enabled. */ +public final class PluginEnableEvent { + private final PluginInfo plugin; + + public PluginEnableEvent(PluginInfo plugin) { this.plugin = plugin; } + + public PluginInfo plugin() { return plugin; } +} diff --git a/java/api/src/main/java/prism/api/event/ShutdownEvent.java b/java/api/src/main/java/prism/api/event/ShutdownEvent.java new file mode 100644 index 0000000..c57a7ed --- /dev/null +++ b/java/api/src/main/java/prism/api/event/ShutdownEvent.java @@ -0,0 +1,5 @@ +package prism.api.event; + +/** Posted once when Prism is unloaded from the game (or the game closes). */ +public final class ShutdownEvent { +} diff --git a/java/build.gradle b/java/build.gradle new file mode 100644 index 0000000..b0a7179 --- /dev/null +++ b/java/build.gradle @@ -0,0 +1,12 @@ +// Java 8 bytecode: runs on Lunar (Java 17) and on Forge 1.8.9 (Java 8). +subprojects { + apply plugin: 'java' + group = 'prism' + version = '0.1.0' + repositories { mavenCentral() } + tasks.withType(JavaCompile).configureEach { + options.release = 8 + options.encoding = 'UTF-8' + options.compilerArgs += ['-Xlint:-options'] + } +} diff --git a/java/core/build.gradle b/java/core/build.gradle new file mode 100644 index 0000000..b72e83f --- /dev/null +++ b/java/core/build.gradle @@ -0,0 +1,7 @@ +// prism-core.jar: loaded into the game by the agent. Contains the API classes too. +base { archivesName = 'prism-core' } +dependencies { implementation project(':api') } +jar { + dependsOn ':api:jar' + from { project(':api').sourceSets.main.output } +} diff --git a/java/core/src/main/java/prism/core/Bus.java b/java/core/src/main/java/prism/core/Bus.java new file mode 100644 index 0000000..7155a51 --- /dev/null +++ b/java/core/src/main/java/prism/core/Bus.java @@ -0,0 +1,67 @@ +package prism.core; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +import prism.api.EventBus; +import prism.api.Logger; +import prism.api.Subscription; + +/** The one event bus. Plugins get an {@link Owned} view so their handlers can be removed together. */ +final class Bus { + private static final class Handler { + final Class type; + final Consumer fn; + final Owned owner; + + @SuppressWarnings("unchecked") + Handler(Class type, Consumer fn, Owned owner) { + this.type = type; + this.fn = (Consumer) fn; + this.owner = owner; + } + } + + private final List handlers = new CopyOnWriteArrayList<>(); + private final Logger log = CoreLog.forSource("events"); + + E post(E event) { + for (Handler h : handlers) { + if (!h.type.isInstance(event)) continue; + try { + h.fn.accept(event); + } catch (Throwable t) { + log.error((h.owner == null ? "core" : h.owner.name) + " failed handling " + + event.getClass().getSimpleName(), t); + } + } + return event; + } + + Owned owned(String name) { return new Owned(name); } + + /** One plugin's view of the bus. */ + final class Owned implements EventBus { + final String name; + private volatile boolean closed; + + Owned(String name) { this.name = name; } + + @Override + public Subscription on(Class type, Consumer handler) { + if (closed) throw new IllegalStateException("plugin is disabled"); + Handler h = new Handler(type, handler, this); + handlers.add(h); + return () -> handlers.remove(h); + } + + @Override + public E post(E event) { return Bus.this.post(event); } + + void close() { + closed = true; + handlers.removeIf(h -> h.owner == this); + } + } +} diff --git a/java/core/src/main/java/prism/core/ClientThread.java b/java/core/src/main/java/prism/core/ClientThread.java new file mode 100644 index 0000000..9edd1fb --- /dev/null +++ b/java/core/src/main/java/prism/core/ClientThread.java @@ -0,0 +1,63 @@ +package prism.core; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import prism.api.Logger; + +/** + * Runs code on Minecraft's client thread through Minecraft#addScheduledTask, found by its + * shape (instance method taking one Runnable) so it works with every naming scheme. + */ +final class ClientThread { + private static final Logger log = CoreLog.forSource("core"); + private static Class mcClass; + private static Method getInstance, addTask; + private static boolean warned; + + static void init(Class minecraft) { + mcClass = minecraft; + for (Method m : minecraft.getDeclaredMethods()) { + if (Modifier.isStatic(m.getModifiers()) && m.getParameterCount() == 0 + && m.getReturnType() == minecraft) { + getInstance = m; + } + if (!Modifier.isStatic(m.getModifiers()) && m.getParameterCount() == 1 + && m.getParameterTypes()[0] == Runnable.class) { + // addScheduledTask returns a ListenableFuture; prefer that one if there are several + if (addTask == null || m.getReturnType().getName().endsWith("ListenableFuture")) addTask = m; + } + } + if (getInstance != null) getInstance.setAccessible(true); + if (addTask != null) addTask.setAccessible(true); + log.info("client thread: " + (getInstance != null && addTask != null ? "ready" : "not found")); + } + + static Object minecraft() { + if (getInstance == null) return null; + try { + return getInstance.invoke(null); + } catch (Exception e) { + return null; + } + } + + static Class minecraftClass() { return mcClass; } + + static void run(Runnable task) { + Object mc = minecraft(); + if (mc != null && addTask != null) { + try { + addTask.invoke(mc, task); + return; + } catch (Exception e) { + log.error("addScheduledTask failed", e); + } + } + if (!warned) { + warned = true; + log.warn("client thread not available, running tasks directly"); + } + task.run(); + } +} diff --git a/java/core/src/main/java/prism/core/CoreLog.java b/java/core/src/main/java/prism/core/CoreLog.java new file mode 100644 index 0000000..c61d512 --- /dev/null +++ b/java/core/src/main/java/prism/core/CoreLog.java @@ -0,0 +1,70 @@ +package prism.core; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.text.SimpleDateFormat; +import java.util.Date; + +import prism.api.Logger; + +/** Log file at logs/prism.log (previous run kept as prism.old.log). */ +final class CoreLog { + private static Writer out; + private static final SimpleDateFormat TIME = new SimpleDateFormat("HH:mm:ss"); + + static synchronized void open(Path logsDir) { + try { + Files.createDirectories(logsDir); + Path file = logsDir.resolve("prism.log"); + if (Files.exists(file)) Files.move(file, logsDir.resolve("prism.old.log"), + java.nio.file.StandardCopyOption.REPLACE_EXISTING); + out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + } catch (IOException e) { + out = null; + } + } + + static synchronized void close() { + if (out == null) return; + try { + out.close(); + } catch (IOException ignored) { + } + out = null; + } + + static synchronized void write(String level, String source, String msg, Throwable t) { + StringBuilder line = new StringBuilder() + .append(TIME.format(new Date())).append(' ').append(level) + .append(" [").append(source).append("] ").append(msg); + if (t != null) { + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + line.append('\n').append(sw.toString().trim()); + } + String s = line.toString(); + if (out != null) { + try { + out.write(s); + out.write('\n'); + out.flush(); + } catch (IOException ignored) { + } + } + } + + static Logger forSource(String source) { + return new Logger() { + public void info(String msg) { write("INFO", source, msg, null); } + public void warn(String msg) { write("WARN", source, msg, null); } + public void error(String msg, Throwable t) { write("ERROR", source, msg, t); } + }; + } +} diff --git a/java/core/src/main/java/prism/core/GameImpl.java b/java/core/src/main/java/prism/core/GameImpl.java new file mode 100644 index 0000000..1715acc --- /dev/null +++ b/java/core/src/main/java/prism/core/GameImpl.java @@ -0,0 +1,97 @@ +package prism.core; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import prism.api.Game; +import prism.api.Logger; + +final class GameImpl implements Game { + private final String mappings; + private final ClassLoader loader; + private final Logger log = CoreLog.forSource("game"); + + // resolved on first chat() + private Field ingameGui; + private Method getChat, printChat; + private Constructor textComponent; + private boolean resolved, broken; + + GameImpl(String mappings, ClassLoader loader) { + this.mappings = mappings; + this.loader = loader; + } + + @Override public String mappings() { return mappings; } + + @Override public ClassLoader classLoader() { return loader; } + + @Override + public void chat(String message) { + ClientThread.run(() -> printNow(message)); + } + + private void printNow(String message) { + if (!resolve()) { + log.info("(chat) " + message); + return; + } + try { + Object mc = ClientThread.minecraft(); + Object gui = mc == null ? null : ingameGui.get(mc); + if (gui == null) { // still loading: no HUD yet + log.info("(chat, no HUD yet) " + message); + return; + } + printChat.invoke(getChat.invoke(gui), textComponent.newInstance(message)); + } catch (Exception e) { + log.error("chat failed", e); + } + } + + /** Minecraft.ingameGUI -> GuiIngame.getChatGUI() -> GuiNewChat.printChatMessage(new ChatComponentText(s)) */ + private synchronized boolean resolve() { + if (resolved || broken) return resolved; + try { + Class mc = ClientThread.minecraftClass(); + String[] n = names(); + Class chatText = Class.forName(n[3], false, loader); + Class component = Class.forName(n[4], false, loader); + ingameGui = field(mc, n[0]); + getChat = method(ingameGui.getType(), n[1]); + printChat = getChat.getReturnType().getMethod(n[2], component); + textComponent = chatText.getConstructor(String.class); + resolved = true; + } catch (Throwable t) { + broken = true; + log.error("chat not available for " + mappings + " names", t); + } + return resolved; + } + + private String[] names() { + switch (mappings) { + case "srg": + return new String[] {"field_71456_v", "func_146158_b", "func_146227_a", + "net.minecraft.util.ChatComponentText", "net.minecraft.util.IChatComponent"}; + case "notch": // vanilla 1.8.9 + return new String[] {"q", "d", "a", "fa", "eu"}; + default: // mcp (Lunar) + return new String[] {"ingameGUI", "getChatGUI", "printChatMessage", + "net.minecraft.util.ChatComponentText", "net.minecraft.util.IChatComponent"}; + } + } + + private static Field field(Class c, String name) throws NoSuchFieldException { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + private static Method method(Class c, String name) throws NoSuchMethodException { + Method m = c.getDeclaredMethod(name); + m.setAccessible(true); + return m; + } +} diff --git a/java/core/src/main/java/prism/core/Native.java b/java/core/src/main/java/prism/core/Native.java new file mode 100644 index 0000000..44736f7 --- /dev/null +++ b/java/core/src/main/java/prism/core/Native.java @@ -0,0 +1,44 @@ +package prism.core; + +/** + * Calls into the native agent (prism_agent.dll). The agent registers these methods + * before {@link Prism#start} runs. Without the agent (tests), they are no-ops. + */ +public final class Native { + private Native() {} + + static native void log0(String line); + + static native void unload0(); + + static native boolean redefineClass0(Class target, byte[] classFile); + + private static volatile boolean linked = true; + + static void log(String line) { + if (!linked) return; + try { + log0(line); + } catch (UnsatisfiedLinkError e) { + linked = false; + } + } + + /** Asks the agent to unload Prism from the game. Prism.stop() is called by the agent. */ + public static void requestUnload() { + try { + unload0(); + } catch (UnsatisfiedLinkError e) { + Prism.stop(); + } + } + + /** Replaces a loaded class's bytecode (JVMTI RedefineClasses). For the hook system. */ + public static boolean redefineClass(Class target, byte[] classFile) { + try { + return redefineClass0(target, classFile); + } catch (UnsatisfiedLinkError e) { + return false; + } + } +} diff --git a/java/core/src/main/java/prism/core/PluginManager.java b/java/core/src/main/java/prism/core/PluginManager.java new file mode 100644 index 0000000..bf9f28b --- /dev/null +++ b/java/core/src/main/java/prism/core/PluginManager.java @@ -0,0 +1,289 @@ +package prism.core; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import prism.api.EventBus; +import prism.api.Game; +import prism.api.Logger; +import prism.api.Plugin; +import prism.api.PluginContext; +import prism.api.PluginInfo; +import prism.api.Scheduler; +import prism.api.event.PluginDisableEvent; +import prism.api.event.PluginEnableEvent; + +/** + * Loads every jar in the plugins folder and hot-reloads it when the file changes. + * Each jar is copied to a cache file first, so the original stays unlocked and can be replaced + * while the game runs. A changed file is reloaded once it has stopped changing for one scan. + */ +final class PluginManager { + private static final long SCAN_MS = 1000; + + private final Path pluginsDir, cacheDir, dataDir; + private final ClassLoader parent; + private final Bus bus; + private final Game game; + private final Logger log = CoreLog.forSource("plugins"); + + /** file name -> loaded plugin */ + private final Map loaded = new LinkedHashMap<>(); + /** file name -> signature seen on the previous scan (to wait until a copy has finished) */ + private final Map lastSeen = new HashMap<>(); + private Thread thread; + private volatile boolean running; + private int cacheCounter; + private boolean firstScan = true; + + PluginManager(Path home, ClassLoader parent, Bus bus, Game game) { + this.pluginsDir = home.resolve("plugins"); + this.cacheDir = home.resolve("cache").resolve("plugins"); + this.dataDir = home.resolve("data"); + this.parent = parent; + this.bus = bus; + this.game = game; + } + + void start() { + try { + Files.createDirectories(pluginsDir); + Files.createDirectories(cacheDir); + clearCache(); + } catch (IOException e) { + log.error("can't create plugin folders", e); + } + running = true; + List first = scan(); + if (!first.isEmpty()) game.chat("§d[Prism] §fLoaded " + String.join(", ", first)); + else game.chat("§d[Prism] §fLoaded"); + thread = new Thread(this::loop, "Prism Plugins"); + thread.setDaemon(true); + thread.start(); + } + + void stop() { + running = false; + if (thread != null) { + thread.interrupt(); + try { + thread.join(3000); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + } + synchronized (this) { + List names = new ArrayList<>(loaded.keySet()); + for (int i = names.size() - 1; i >= 0; i--) unload(names.get(i)); + } + clearCache(); + } + + synchronized List plugins() { + List out = new ArrayList<>(); + for (Loaded l : loaded.values()) out.add(l.info); + return out; + } + + private void loop() { + while (running) { + try { + Thread.sleep(SCAN_MS); + } catch (InterruptedException e) { + return; + } + List changed = scan(); + if (!changed.isEmpty()) game.chat("§d[Prism] §fReloaded " + String.join(", ", changed)); + } + } + + /** One pass over the folder. Returns the names of plugins that were (re)loaded. */ + private synchronized List scan() { + List done = new ArrayList<>(); + Map now = new HashMap<>(); + try (DirectoryStream ds = Files.newDirectoryStream(pluginsDir, "*.jar")) { + for (Path p : ds) { + try { + now.put(p.getFileName().toString(), Files.size(p) + ":" + Files.getLastModifiedTime(p).toMillis()); + } catch (IOException ignored) { + } + } + } catch (IOException e) { + log.error("can't read plugins folder", e); + return done; + } + for (String name : new ArrayList<>(loaded.keySet())) { + if (!now.containsKey(name)) { + unload(name); + log.info(name + " removed"); + } + } + for (Map.Entry e : now.entrySet()) { + String name = e.getKey(), sig = e.getValue(); + Loaded cur = loaded.get(name); + if (cur != null && cur.signature.equals(sig)) continue; + boolean stable = firstScan || sig.equals(lastSeen.get(name)); + if (!stable) continue; // still being written; look again next scan + if (cur != null) unload(name); + Loaded l = load(pluginsDir.resolve(name), sig); + if (l != null) { + loaded.put(name, l); + done.add(l.info.name()); + } + } + lastSeen.clear(); + lastSeen.putAll(now); + firstScan = false; + return done; + } + + private Loaded load(Path jar, String signature) { + String file = jar.getFileName().toString(); + Path copy = cacheDir.resolve((cacheCounter++) + "-" + file); + URLClassLoader cl = null; + try { + Files.copy(jar, copy, StandardCopyOption.REPLACE_EXISTING); + PluginInfo info = readInfo(copy, file); + for (Loaded other : loaded.values()) { + if (other.info.id().equals(info.id())) { + throw new IllegalStateException("id '" + info.id() + "' already used by " + other.file); + } + } + cl = new URLClassLoader(new URL[] {copy.toUri().toURL()}, parent); + Plugin plugin = (Plugin) Class.forName(info.main(), true, cl).getDeclaredConstructor().newInstance(); + Loaded l = new Loaded(file, signature, info, plugin, cl, copy); + plugin.onEnable(l.ctx); + log.info("enabled " + info); + bus.post(new PluginEnableEvent(info)); + return l; + } catch (Throwable t) { + log.error("failed to load " + file, t); + game.chat("§d[Prism] §c" + file + " failed to load (see log)"); + closeQuietly(cl); + deleteQuietly(copy); + return null; + } + } + + private void unload(String file) { + Loaded l = loaded.remove(file); + if (l == null) return; + bus.post(new PluginDisableEvent(l.info)); + try { + l.plugin.onDisable(); + } catch (Throwable t) { + log.error(l.info.name() + " failed to disable", t); + } + l.ctx.close(); + closeQuietly(l.loader); + deleteQuietly(l.copy); + log.info("disabled " + l.info); + } + + private static PluginInfo readInfo(Path jar, String file) throws IOException { + try (ZipFile zip = new ZipFile(jar.toFile())) { + ZipEntry entry = zip.getEntry("plugin.properties"); + if (entry == null) throw new IOException(file + " has no plugin.properties"); + Properties p = new Properties(); + try (InputStream in = zip.getInputStream(entry)) { + p.load(in); + } + String id = p.getProperty("id"), main = p.getProperty("main"); + if (id == null || main == null) throw new IOException(file + ": plugin.properties needs id and main"); + if (!id.matches("[a-z0-9][a-z0-9_-]*")) throw new IOException(file + ": id must be lowercase letters, digits, - or _"); + return new PluginInfo(id, p.getProperty("name", id), p.getProperty("version", "0"), main); + } + } + + private void clearCache() { + try (DirectoryStream ds = Files.newDirectoryStream(cacheDir)) { + for (Path p : ds) deleteQuietly(p); + } catch (IOException ignored) { + } + } + + private static void closeQuietly(URLClassLoader cl) { + if (cl == null) return; + try { + cl.close(); + } catch (IOException ignored) { + } + } + + private static void deleteQuietly(Path p) { + try { + Files.deleteIfExists(p); + } catch (IOException ignored) { + // still locked on Windows; removed by clearCache() on the next start + } + } + + private final class Loaded { + final String file, signature; + final PluginInfo info; + final Plugin plugin; + final URLClassLoader loader; + final Path copy; + final Context ctx; + + Loaded(String file, String signature, PluginInfo info, Plugin plugin, URLClassLoader loader, Path copy) { + this.file = file; + this.signature = signature; + this.info = info; + this.plugin = plugin; + this.loader = loader; + this.copy = copy; + this.ctx = new Context(info); + } + } + + private final class Context implements PluginContext { + private final PluginInfo info; + private final Logger log; + private final Bus.Owned events; + private final Tasks.Owned tasks; + + Context(PluginInfo info) { + this.info = info; + this.log = CoreLog.forSource(info.id()); + this.events = bus.owned(info.id()); + this.tasks = new Tasks.Owned(log); + } + + @Override public PluginInfo info() { return info; } + @Override public Logger log() { return log; } + @Override public EventBus events() { return events; } + @Override public Scheduler scheduler() { return tasks; } + @Override public Game game() { return game; } + + @Override + public Path dataFolder() { + Path p = dataDir.resolve(info.id()); + try { + Files.createDirectories(p); + } catch (IOException e) { + log.error("can't create " + p, e); + } + return p; + } + + void close() { + events.close(); + tasks.close(); + } + } +} diff --git a/java/core/src/main/java/prism/core/Prism.java b/java/core/src/main/java/prism/core/Prism.java new file mode 100644 index 0000000..2da081d --- /dev/null +++ b/java/core/src/main/java/prism/core/Prism.java @@ -0,0 +1,83 @@ +package prism.core; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicBoolean; + +import prism.api.Logger; +import prism.api.event.ShutdownEvent; + +/** + * Started by the native agent once the game's classes are loaded. + * Layout of the Prism folder (home): bin/ (agent + core), plugins/, data/, logs/, cache/. + */ +public final class Prism { + public static final String VERSION = "0.1.0"; + + private static final AtomicBoolean running = new AtomicBoolean(); + private static Bus bus; + private static PluginManager plugins; + private static Thread shutdownHook; + + private Prism() {} + + /** + * @param home the Prism folder + * @param mappings "mcp", "srg" or "notch" + * @param minecraft the game's Minecraft class + * @return null when started, else why it failed + */ + public static String start(String home, String mappings, Class minecraft) { + if (!running.compareAndSet(false, true)) return "already running"; + try { + Path dir = Paths.get(home); + CoreLog.open(dir.resolve("logs")); + Logger log = CoreLog.forSource("core"); + log.info("Prism " + VERSION + " starting (" + mappings + " names, Java " + + System.getProperty("java.version") + ")"); + ClientThread.init(minecraft); + // injected at the launcher/loading screen: wait for the game object to exist + for (int i = 0; i < 600 && ClientThread.minecraft() == null; i++) Thread.sleep(100); + if (ClientThread.minecraft() == null) log.warn("Minecraft instance not found yet; continuing"); + Tasks.start(); + bus = new Bus(); + GameImpl game = new GameImpl(mappings, minecraft.getClassLoader()); + plugins = new PluginManager(dir, Prism.class.getClassLoader(), bus, game); + plugins.start(); + shutdownHook = new Thread(Prism::stop, "Prism Shutdown"); + Runtime.getRuntime().addShutdownHook(shutdownHook); + log.info("started with " + plugins.plugins().size() + " plugin(s)"); + return null; + } catch (Throwable t) { + CoreLog.write("ERROR", "core", "start failed", t); + running.set(false); + return t.toString(); + } + } + + /** Disables every plugin and stops Prism's threads. Called by the agent on unload and at game exit. */ + public static void stop() { + if (!running.compareAndSet(true, false)) return; + Logger log = CoreLog.forSource("core"); + log.info("stopping"); + try { + if (bus != null) bus.post(new ShutdownEvent()); + if (plugins != null) plugins.stop(); + } catch (Throwable t) { + log.error("stop failed", t); + } + Tasks.stop(); + if (shutdownHook != null && Thread.currentThread() != shutdownHook) { + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException ignored) { // JVM already shutting down + } + } + log.info("stopped"); + CoreLog.close(); + bus = null; + plugins = null; + } + + public static boolean isRunning() { return running.get(); } +} diff --git a/java/core/src/main/java/prism/core/Tasks.java b/java/core/src/main/java/prism/core/Tasks.java new file mode 100644 index 0000000..4c44ce1 --- /dev/null +++ b/java/core/src/main/java/prism/core/Tasks.java @@ -0,0 +1,79 @@ +package prism.core; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import prism.api.Logger; +import prism.api.Scheduler; + +/** One timer thread for everyone; the work itself always runs on the client thread. */ +final class Tasks { + private static ScheduledExecutorService timer; + + static synchronized void start() { + timer = Executors.newSingleThreadScheduledExecutor(r -> { + Thread t = new Thread(r, "Prism Timer"); + t.setDaemon(true); + return t; + }); + } + + static synchronized void stop() { + if (timer != null) timer.shutdownNow(); + timer = null; + } + + /** A plugin's scheduler: everything it scheduled is cancelled by {@link #close()}. */ + static final class Owned implements Scheduler { + private final Logger log; + private final Set> futures = ConcurrentHashMap.newKeySet(); + private volatile boolean closed; + + Owned(Logger log) { this.log = log; } + + private Runnable guarded(Runnable task) { + return () -> { + if (closed) return; + try { + task.run(); + } catch (Throwable t) { + log.error("task failed", t); + } + }; + } + + @Override + public void runOnClientThread(Runnable task) { + if (!closed) ClientThread.run(guarded(task)); + } + + @Override + public Task later(long delayMs, Runnable task) { + return track(timer.schedule(() -> runOnClientThread(task), delayMs, TimeUnit.MILLISECONDS)); + } + + @Override + public Task every(long periodMs, Runnable task) { + return track(timer.scheduleAtFixedRate(() -> runOnClientThread(task), periodMs, periodMs, + TimeUnit.MILLISECONDS)); + } + + private Task track(ScheduledFuture f) { + futures.add(f); + return () -> { + f.cancel(false); + futures.remove(f); + }; + } + + void close() { + closed = true; + for (ScheduledFuture f : futures) f.cancel(false); + futures.clear(); + } + } +} diff --git a/java/example-plugin/build.gradle b/java/example-plugin/build.gradle new file mode 100644 index 0000000..82ecee8 --- /dev/null +++ b/java/example-plugin/build.gradle @@ -0,0 +1,3 @@ +// A minimal plugin. Drop the built jar into the Prism plugins folder. +base { archivesName = 'example-plugin' } +dependencies { compileOnly project(':api') } diff --git a/java/example-plugin/src/main/java/example/ExamplePlugin.java b/java/example-plugin/src/main/java/example/ExamplePlugin.java new file mode 100644 index 0000000..ff71e3a --- /dev/null +++ b/java/example-plugin/src/main/java/example/ExamplePlugin.java @@ -0,0 +1,15 @@ +package example; + +import prism.api.Plugin; +import prism.api.PluginContext; +import prism.api.event.PluginEnableEvent; + +/** Says hello in chat and logs when other plugins load. */ +public class ExamplePlugin implements Plugin { + @Override + public void onEnable(PluginContext ctx) { + ctx.log().info("hello from " + ctx.info()); + ctx.game().chat("§d[Example] §fHello!"); + ctx.events().on(PluginEnableEvent.class, e -> ctx.log().info("saw " + e.plugin() + " load")); + } +} diff --git a/java/example-plugin/src/main/resources/plugin.properties b/java/example-plugin/src/main/resources/plugin.properties new file mode 100644 index 0000000..f4004ce --- /dev/null +++ b/java/example-plugin/src/main/resources/plugin.properties @@ -0,0 +1,4 @@ +id=example +name=Example +version=1.0.0 +main=example.ExamplePlugin diff --git a/java/settings.gradle b/java/settings.gradle new file mode 100644 index 0000000..cfaf91a --- /dev/null +++ b/java/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'prism' +include 'api', 'core', 'example-plugin' diff --git a/native/agent/Cargo.toml b/native/agent/Cargo.toml new file mode 100644 index 0000000..92bb228 --- /dev/null +++ b/native/agent/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "prism-agent" +description = "Loaded into the game process: finds the JVM and starts the Java core." +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +name = "prism_agent" +crate-type = ["cdylib"] + +[dependencies] +jni-sys = "0.3" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_LibraryLoader", + "Win32_System_SystemServices", + "Win32_System_Threading", + "Win32_System_Diagnostics_Debug", +] } diff --git a/native/agent/src/boot.rs b/native/agent/src/boot.rs new file mode 100644 index 0000000..a087cca --- /dev/null +++ b/native/agent/src/boot.rs @@ -0,0 +1,318 @@ +//! Finds the game's class loader, loads prism-core.jar on top of it and starts the core. +//! Runs on the agent's own thread (attached to the JVM as a daemon thread). + +use crate::jvm::{self, Env, Jvmti}; +use crate::log::log; +use jni_sys::*; +use std::ffi::c_void; +use std::path::Path; +use std::ptr::null_mut; +use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; +use std::time::{Duration, Instant}; + +/// Set by Native.unload0() (or the unload file); the agent thread then shuts down. +pub static UNLOAD: AtomicBool = AtomicBool::new(false); +static JVMTI: AtomicPtr = AtomicPtr::new(null_mut()); + +/// Which class names the client uses. +fn mode_of(env: Env, loader: jobject) -> Option<(&'static str, jclass)> { + if let Some(mc) = env.load_class(loader, "net.minecraft.client.Minecraft") { + if env + .static_method(mc, "getMinecraft", "()Lnet/minecraft/client/Minecraft;") + .is_some() + { + return Some(("mcp", mc)); // Lunar + } + if env + .static_method(mc, "func_71410_x", "()Lnet/minecraft/client/Minecraft;") + .is_some() + { + return Some(("srg", mc)); // Forge + } + env.delete_local(mc); + } + if let Some(mc) = env.load_class(loader, "ave") { + if env.static_method(mc, "A", "()Lave;").is_some() { + return Some(("notch", mc)); // vanilla 1.8.9 + } + env.delete_local(mc); + } + None +} + +pub struct Game { + pub loader: jobject, // global refs + pub minecraft: jclass, + pub mode: &'static str, +} + +/// 1) context class loaders of all threads (Lunar's and Forge's loaders show up here), +/// 2) JVMTI: the loader of the loaded Minecraft class. +fn find_game(env: Env, ti: Option) -> Option { + let found = |loader: jobject| -> Option { + let (mode, mc) = mode_of(env, loader)?; + Some(Game { + loader: env.global(loader), + minecraft: env.global(mc), + mode, + }) + }; + // 1) threads + if let Some(g) = (|| -> Option { + let thread = env.find_class("java/lang/Thread").ok()?; + let all = env.static_method(thread, "getAllStackTraces", "()Ljava/util/Map;")?; + let map = env.call_static_object(thread, all, &[]).ok()?; + let map_cls = env.find_class("java/util/Map").ok()?; + let key_set = env.method(map_cls, "keySet", "()Ljava/util/Set;").ok()?; + let set = env.call_object(map, key_set, &[]).ok()?; + let coll = env.find_class("java/util/Collection").ok()?; + let to_array = env.method(coll, "toArray", "()[Ljava/lang/Object;").ok()?; + let arr = env.call_object(set, to_array, &[]).ok()?; + let ctx = env + .method(thread, "getContextClassLoader", "()Ljava/lang/ClassLoader;") + .ok()?; + for i in 0..env.array_len(arr) { + let t = env.array_get(arr, i); + if let Ok(loader) = env.call_object(t, ctx, &[]) { + if !loader.is_null() { + if let Some(g) = found(loader) { + return Some(g); + } + } + } + } + None + })() { + return Some(g); + } + // 2) JVMTI + let mut game = None; + if let Some(ti) = ti { + ti.for_class_loaders( + env, + &["Lnet/minecraft/client/Minecraft;", "Lave;"], + |_, loader| { + game = found(loader); + game.is_some() + }, + ); + } + game +} + +/// A URLClassLoader for the core jar with the game's loader as parent, so the core sees game classes. +fn core_loader(env: Env, jar: &Path, parent: jobject) -> Result { + let file_cls = env.find_class("java/io/File")?; + let path = env.string(&jar.to_string_lossy()); + let file = env.new_object(file_cls, "(Ljava/lang/String;)V", &[jvalue { l: path }])?; + let to_uri = env.method(file_cls, "toURI", "()Ljava/net/URI;")?; + let uri = env.call_object(file, to_uri, &[])?; + let uri_cls = env.find_class("java/net/URI")?; + let to_url = env.method(uri_cls, "toURL", "()Ljava/net/URL;")?; + let url = env.call_object(uri, to_url, &[])?; + let url_cls = env.find_class("java/net/URL")?; + let urls = env.new_object_array(url_cls, 1, url); + let ucl = env.find_class("java/net/URLClassLoader")?; + env.new_object( + ucl, + "([Ljava/net/URL;Ljava/lang/ClassLoader;)V", + &[jvalue { l: urls }, jvalue { l: parent }], + ) +} + +// ------------------------------------------------------------------ natives of prism.core.Native + +extern "system" fn n_log(env: *mut JNIEnv, _: jclass, line: jstring) { + log(&Env(env).rust_string(line)); +} + +extern "system" fn n_unload(_: *mut JNIEnv, _: jclass) { + UNLOAD.store(true, Ordering::SeqCst); +} + +extern "system" fn n_redefine( + env: *mut JNIEnv, + _: jclass, + target: jclass, + bytes: jbyteArray, +) -> jboolean { + let p = JVMTI.load(Ordering::SeqCst); + if p.is_null() || target.is_null() || bytes.is_null() { + return JNI_FALSE; + } + let ti: Jvmti = unsafe { std::mem::transmute(p) }; + let data = Env(env).byte_array(bytes); + let r = ti.redefine(target, &data); + if r != 0 { + log(&format!("RedefineClasses failed: JVMTI error {r}")); + } + (r == 0) as jboolean +} + +// ------------------------------------------------------------------ the agent thread + +pub struct Paths { + pub home: std::path::PathBuf, + pub core_jar: std::path::PathBuf, +} + +/// Everything the agent does, start to unload. `extra_unload` is polled for an outside unload request. +pub fn run(vm: *mut JavaVM, paths: Paths, extra_unload: impl Fn() -> bool) { + UNLOAD.store(false, Ordering::SeqCst); + let Some(env) = jvm::attach(vm, "Prism Agent") else { + log("can't attach to the JVM"); + return; + }; + let ti = Jvmti::get(vm); + if let Some(t) = ti { + let redefine = t.enable_redefine(); + log(&format!("JVMTI ready (redefine classes: {redefine})")); + JVMTI.store( + unsafe { std::mem::transmute::(t) }, + Ordering::SeqCst, + ); + } else { + log("JVMTI not available"); + } + + // wait for Minecraft to be loaded (injecting at the launcher screen is fine) + let started = Instant::now(); + let game = loop { + if UNLOAD.load(Ordering::SeqCst) || extra_unload() { + return finish(vm, ti, None, None); + } + env.push_frame(256); + let g = find_game(env, ti); + env.pop_frame(); + if let Some(g) = g { + break g; + } + if started.elapsed() > Duration::from_secs(300) { + log("gave up: no Minecraft 1.8.9 classes found in 5 minutes"); + return finish(vm, ti, None, None); + } + std::thread::sleep(Duration::from_millis(500)); + }; + log(&format!( + "game found: {} names ({})", + game.mode, + match game.mode { + "mcp" => "Lunar", + "srg" => "Forge", + _ => "vanilla based", + } + )); + + let core = match start_core(env, &paths, &game) { + Ok(c) => Some(c), + Err(e) => { + log(&format!("core failed to start: {e}")); + None + } + }; + + if core.is_some() { + while !UNLOAD.load(Ordering::SeqCst) && !extra_unload() { + std::thread::sleep(Duration::from_millis(100)); + } + log("unload requested"); + } + finish(vm, ti, Some(game), core) +} + +pub struct Core { + loader: jobject, // global + native: jclass, // global + prism: jclass, // global +} + +fn start_core(env: Env, paths: &Paths, game: &Game) -> Result { + if !paths.core_jar.exists() { + return Err(format!("{} is missing", paths.core_jar.display())); + } + env.push_frame(64); + let r = (|| { + let loader = core_loader(env, &paths.core_jar, game.loader)?; + let native = env + .load_class(loader, "prism.core.Native") + .ok_or("prism.core.Native not in core jar")?; + env.register_natives( + native, + &[ + ("log0", "(Ljava/lang/String;)V", n_log as *mut c_void), + ("unload0", "()V", n_unload as *mut c_void), + ( + "redefineClass0", + "(Ljava/lang/Class;[B)Z", + n_redefine as *mut c_void, + ), + ], + )?; + let prism = env + .load_class(loader, "prism.core.Prism") + .ok_or("prism.core.Prism not in core jar")?; + let start = env + .static_method( + prism, + "start", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/String;", + ) + .ok_or("Prism.start missing")?; + let home = env.string(&paths.home.to_string_lossy()); + let mode = env.string(game.mode); + let err = env.call_static_object( + prism, + start, + &[ + jvalue { l: home }, + jvalue { l: mode }, + jvalue { l: game.minecraft }, + ], + )?; + if !err.is_null() { + env.unregister_natives(native); + return Err(env.rust_string(err)); + } + log("core started"); + Ok(Core { + loader: env.global(loader), + native: env.global(native), + prism: env.global(prism), + }) + })(); + env.pop_frame(); + r +} + +/// Stops the core, removes our natives and lets go of every Java reference, then detaches. +fn finish(vm: *mut JavaVM, ti: Option, game: Option, core: Option) { + if let Some(env) = jvm::env_of(vm) { + if let Some(core) = core { + if let Some(stop) = env.static_method(core.prism, "stop", "()V") { + if let Err(e) = env.call_static_void(core.prism, stop, &[]) { + log(&format!("Prism.stop failed: {e}")); + } + } + // after this, Native methods throw UnsatisfiedLinkError instead of calling into a freed DLL + env.unregister_natives(core.native); + if let Ok(ucl) = env.find_class("java/net/URLClassLoader") { + if let Ok(close) = env.method(ucl, "close", "()V") { + let _ = env.call_void(core.loader, close, &[]); + } + } + env.delete_global(core.native); + env.delete_global(core.prism); + env.delete_global(core.loader); + } + if let Some(g) = game { + env.delete_global(g.minecraft); + env.delete_global(g.loader); + } + } + JVMTI.store(null_mut(), Ordering::SeqCst); + if let Some(t) = ti { + t.dispose(); + } + jvm::detach(vm); + log("unloaded"); +} diff --git a/native/agent/src/jvm.rs b/native/agent/src/jvm.rs new file mode 100644 index 0000000..0c721e8 --- /dev/null +++ b/native/agent/src/jvm.rs @@ -0,0 +1,421 @@ +//! Thin helpers over raw JNI and the few JVMTI functions Prism needs. + +use jni_sys::*; +use std::ffi::{c_char, c_void, CStr, CString}; +use std::ptr::null_mut; + +/// A JNIEnv for the current thread. +#[derive(Clone, Copy)] +pub struct Env(pub *mut JNIEnv); + +macro_rules! jni { + ($env:expr, $f:ident $(, $a:expr)*) => { + unsafe { ((**$env.0).$f.expect(stringify!($f)))($env.0 $(, $a)*) } + }; +} + +fn c(s: &str) -> CString { + CString::new(s).expect("nul in string") +} + +impl Env { + /// Clears a pending Java exception. Returns its toString() if there was one. + pub fn take_exception(&self) -> Option { + if jni!(self, ExceptionCheck) == JNI_FALSE { + return None; + } + let t = jni!(self, ExceptionOccurred); + jni!(self, ExceptionClear); + if t.is_null() { + return Some("unknown exception".into()); + } + let text = self.call_to_string(t); + self.delete_local(t); + Some(text.unwrap_or_else(|| "exception".into())) + } + + fn ok(&self) -> Result<(), String> { + match self.take_exception() { + Some(e) => Err(e), + None => Ok(()), + } + } + + pub fn delete_local(&self, o: jobject) { + if !o.is_null() { + jni!(self, DeleteLocalRef, o); + } + } + + pub fn global(&self, o: jobject) -> jobject { + jni!(self, NewGlobalRef, o) + } + + pub fn delete_global(&self, o: jobject) { + if !o.is_null() { + jni!(self, DeleteGlobalRef, o); + } + } + + pub fn find_class(&self, name: &str) -> Result { + let n = c(name); + let cls = jni!(self, FindClass, n.as_ptr()); + self.ok()?; + if cls.is_null() { + return Err(format!("class {name} not found")); + } + Ok(cls) + } + + pub fn method(&self, cls: jclass, name: &str, sig: &str) -> Result { + let (n, s) = (c(name), c(sig)); + let m = jni!(self, GetMethodID, cls, n.as_ptr(), s.as_ptr()); + self.ok()?; + if m.is_null() { + return Err(format!("method {name}{sig} not found")); + } + Ok(m) + } + + /// A static method, or None if the class doesn't have it (no exception left behind). + pub fn static_method(&self, cls: jclass, name: &str, sig: &str) -> Option { + let (n, s) = (c(name), c(sig)); + let m = jni!(self, GetStaticMethodID, cls, n.as_ptr(), s.as_ptr()); + if self.take_exception().is_some() || m.is_null() { + None + } else { + Some(m) + } + } + + pub fn call_object( + &self, + obj: jobject, + m: jmethodID, + args: &[jvalue], + ) -> Result { + let r = jni!(self, CallObjectMethodA, obj, m, args.as_ptr()); + self.ok()?; + Ok(r) + } + + pub fn call_void(&self, obj: jobject, m: jmethodID, args: &[jvalue]) -> Result<(), String> { + jni!(self, CallVoidMethodA, obj, m, args.as_ptr()); + self.ok() + } + + pub fn call_static_object( + &self, + cls: jclass, + m: jmethodID, + args: &[jvalue], + ) -> Result { + let r = jni!(self, CallStaticObjectMethodA, cls, m, args.as_ptr()); + self.ok()?; + Ok(r) + } + + pub fn call_static_void( + &self, + cls: jclass, + m: jmethodID, + args: &[jvalue], + ) -> Result<(), String> { + jni!(self, CallStaticVoidMethodA, cls, m, args.as_ptr()); + self.ok() + } + + pub fn new_object( + &self, + cls: jclass, + ctor_sig: &str, + args: &[jvalue], + ) -> Result { + let m = self.method(cls, "", ctor_sig)?; + let o = jni!(self, NewObjectA, cls, m, args.as_ptr()); + self.ok()?; + Ok(o) + } + + /// A Java string from Rust text (via UTF-16, so any path survives). + pub fn string(&self, s: &str) -> jstring { + let w: Vec = s.encode_utf16().collect(); + jni!(self, NewString, w.as_ptr(), w.len() as jsize) + } + + pub fn rust_string(&self, s: jstring) -> String { + if s.is_null() { + return String::new(); + } + let len = jni!(self, GetStringLength, s); + let chars = jni!(self, GetStringChars, s, null_mut()); + if chars.is_null() { + return String::new(); + } + let out = + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(chars, len as usize) }); + jni!(self, ReleaseStringChars, s, chars); + out + } + + pub fn call_to_string(&self, o: jobject) -> Option { + let obj = jni!(self, FindClass, c("java/lang/Object").as_ptr()); + let m = jni!( + self, + GetMethodID, + obj, + c("toString").as_ptr(), + c("()Ljava/lang/String;").as_ptr() + ); + let s = jni!(self, CallObjectMethod, o, m); + if jni!(self, ExceptionCheck) != JNI_FALSE { + jni!(self, ExceptionClear); + return None; + } + let r = self.rust_string(s); + self.delete_local(s); + self.delete_local(obj); + Some(r) + } + + /// Class.forName(name, false, loader), or None. + pub fn load_class(&self, loader: jobject, dotted: &str) -> Option { + let class = self.find_class("java/lang/Class").ok()?; + let for_name = self.static_method( + class, + "forName", + "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;", + )?; + let name = self.string(dotted); + let r = self.call_static_object( + class, + for_name, + &[ + jvalue { l: name }, + jvalue { z: JNI_FALSE }, + jvalue { l: loader }, + ], + ); + self.delete_local(name); + self.delete_local(class); + match r { + Ok(c) if !c.is_null() => Some(c), + _ => None, + } + } + + pub fn array_len(&self, a: jarray) -> jsize { + jni!(self, GetArrayLength, a) + } + + pub fn array_get(&self, a: jobjectArray, i: jsize) -> jobject { + jni!(self, GetObjectArrayElement, a, i) + } + + pub fn new_object_array(&self, cls: jclass, len: jsize, first: jobject) -> jobjectArray { + jni!(self, NewObjectArray, len, cls, first) + } + + pub fn byte_array(&self, a: jbyteArray) -> Vec { + let len = self.array_len(a) as usize; + let mut out = vec![0u8; len]; + jni!( + self, + GetByteArrayRegion, + a, + 0, + len as jsize, + out.as_mut_ptr() as *mut jbyte + ); + out + } + + pub fn register_natives( + &self, + cls: jclass, + methods: &[(&str, &str, *mut c_void)], + ) -> Result<(), String> { + let names: Vec<(CString, CString)> = methods.iter().map(|(n, s, _)| (c(n), c(s))).collect(); + let table: Vec = methods + .iter() + .zip(names.iter()) + .map(|((_, _, f), (n, s))| JNINativeMethod { + name: n.as_ptr() as *mut c_char, + signature: s.as_ptr() as *mut c_char, + fnPtr: *f, + }) + .collect(); + let r = jni!( + self, + RegisterNatives, + cls, + table.as_ptr(), + table.len() as jint + ); + self.ok()?; + if r != 0 { + return Err(format!("RegisterNatives returned {r}")); + } + Ok(()) + } + + pub fn unregister_natives(&self, cls: jclass) { + jni!(self, UnregisterNatives, cls); + let _ = self.take_exception(); + } + + pub fn push_frame(&self, n: jint) -> bool { + jni!(self, PushLocalFrame, n) == 0 + } + + pub fn pop_frame(&self) { + jni!(self, PopLocalFrame, null_mut()); + } +} + +// ---------------------------------------------------------------------------------- JavaVM + +pub fn attach(vm: *mut JavaVM, name: &str) -> Option { + let n = c(name); + let mut args = JavaVMAttachArgs { + version: JNI_VERSION_1_6, + name: n.as_ptr() as *mut c_char, + group: null_mut(), + }; + let mut env: *mut c_void = null_mut(); + let r = unsafe { + ((**vm).AttachCurrentThreadAsDaemon.unwrap())( + vm, + &mut env, + &mut args as *mut _ as *mut c_void, + ) + }; + if r == JNI_OK && !env.is_null() { + Some(Env(env as *mut JNIEnv)) + } else { + None + } +} + +pub fn detach(vm: *mut JavaVM) { + unsafe { + ((**vm).DetachCurrentThread.unwrap())(vm); + } +} + +/// The JNIEnv of the calling thread if it is attached. +pub fn env_of(vm: *mut JavaVM) -> Option { + let mut env: *mut c_void = null_mut(); + let r = unsafe { ((**vm).GetEnv.unwrap())(vm, &mut env, JNI_VERSION_1_6) }; + (r == JNI_OK && !env.is_null()).then(|| Env(env as *mut JNIEnv)) +} + +// ---------------------------------------------------------------------------------- JVMTI + +const JVMTI_VERSION_1_2: jint = 0x3001_0200; + +/// jvmtiEnv: a pointer to the JVMTI function table. Slots are the function numbers in +/// the JVMTI spec minus one (see jvmti.h, "/* 47 : Deallocate */" and so on). +#[derive(Clone, Copy)] +pub struct Jvmti(*mut *const *const c_void); + +#[repr(C)] +struct ClassDefinition { + klass: jclass, + class_byte_count: jint, + class_bytes: *const u8, +} + +impl Jvmti { + pub fn get(vm: *mut JavaVM) -> Option { + let mut env: *mut c_void = null_mut(); + let r = unsafe { ((**vm).GetEnv.unwrap())(vm, &mut env, JVMTI_VERSION_1_2) }; + (r == JNI_OK && !env.is_null()).then(|| Jvmti(env as *mut *const *const c_void)) + } + + fn slot(&self, number: usize) -> *const c_void { + unsafe { *(*self.0).add(number - 1) } + } + + fn dealloc(&self, p: *mut u8) { + let f: extern "system" fn(Jvmti, *mut u8) -> jint = + unsafe { std::mem::transmute(self.slot(47)) }; + f(*self, p); + } + + /// Asks for can_redefine_classes (bit 9 of the capabilities). Returns whether it was granted. + pub fn enable_redefine(&self) -> bool { + let mut caps = [0u32; 4]; + let potential: extern "system" fn(Jvmti, *mut u32) -> jint = + unsafe { std::mem::transmute(self.slot(140)) }; + if potential(*self, caps.as_mut_ptr()) != 0 || caps[0] & (1 << 9) == 0 { + return false; + } + let want = [1u32 << 9, 0, 0, 0]; + let add: extern "system" fn(Jvmti, *const u32) -> jint = + unsafe { std::mem::transmute(self.slot(142)) }; + add(*self, want.as_ptr()) == 0 + } + + pub fn redefine(&self, cls: jclass, bytes: &[u8]) -> jint { + let def = ClassDefinition { + klass: cls, + class_byte_count: bytes.len() as jint, + class_bytes: bytes.as_ptr(), + }; + let f: extern "system" fn(Jvmti, jint, *const ClassDefinition) -> jint = + unsafe { std::mem::transmute(self.slot(87)) }; + f(*self, 1, &def) + } + + /// Calls `visit` with the loader of every loaded class whose signature is in `sigs`. + /// Stops when `visit` returns true. + pub fn for_class_loaders( + &self, + env: Env, + sigs: &[&str], + mut visit: impl FnMut(jclass, jobject) -> bool, + ) { + let mut count: jint = 0; + let mut classes: *mut jclass = null_mut(); + let get_loaded: extern "system" fn(Jvmti, *mut jint, *mut *mut jclass) -> jint = + unsafe { std::mem::transmute(self.slot(78)) }; + let get_sig: extern "system" fn(Jvmti, jclass, *mut *mut c_char, *mut *mut c_char) -> jint = + unsafe { std::mem::transmute(self.slot(48)) }; + let get_loader: extern "system" fn(Jvmti, jclass, *mut jobject) -> jint = + unsafe { std::mem::transmute(self.slot(57)) }; + if get_loaded(*self, &mut count, &mut classes) != 0 || classes.is_null() { + return; + } + let list = unsafe { std::slice::from_raw_parts(classes, count as usize) }; + let mut done = false; + for &cls in list { + if !done { + let mut sig: *mut c_char = null_mut(); + if get_sig(*self, cls, &mut sig, null_mut()) == 0 && !sig.is_null() { + let s = unsafe { CStr::from_ptr(sig) } + .to_string_lossy() + .into_owned(); + self.dealloc(sig as *mut u8); + if sigs.contains(&s.as_str()) { + let mut loader: jobject = null_mut(); + if get_loader(*self, cls, &mut loader) == 0 && !loader.is_null() { + done = visit(cls, loader); + env.delete_local(loader); + } + } + } + } + env.delete_local(cls); + } + self.dealloc(classes as *mut u8); + } + + pub fn dispose(&self) { + let f: extern "system" fn(Jvmti) -> jint = unsafe { std::mem::transmute(self.slot(127)) }; + f(*self); + } +} + +unsafe impl Send for Jvmti {} +unsafe impl Sync for Jvmti {} diff --git a/native/agent/src/lib.rs b/native/agent/src/lib.rs new file mode 100644 index 0000000..38363ef --- /dev/null +++ b/native/agent/src/lib.rs @@ -0,0 +1,178 @@ +//! prism_agent: the native part of Prism. +//! +//! On Windows the Prism app loads this DLL into the game with LoadLibraryW. DllMain starts a +//! thread that finds the JVM (JNI_GetCreatedJavaVMs), waits for Minecraft's classes, loads +//! prism-core.jar on top of the game's class loader and calls prism.core.Prism.start(). +//! +//! File layout (the Prism folder, %APPDATA%\Prism): +//! bin\prism_agent-.dll this DLL (named per build so updates never hit a locked file) +//! bin\prism-core-.jar the Java core of the same build +//! bin\unload- created by the app to unload Prism from that game +//! +//! On other systems the same code can be loaded as a JVMTI agent (Agent_OnAttach), which the +//! tests use: options = "|". + +mod boot; +mod jvm; +mod log; + +use std::path::PathBuf; + +/// bin\prism_agent-abc.dll -> (Prism folder, bin\prism-core-abc.jar) +#[allow(dead_code)] +fn paths_from_dll(dll: &std::path::Path) -> boot::Paths { + let bin = dll.parent().map(PathBuf::from).unwrap_or_default(); + let home = bin + .parent() + .map(PathBuf::from) + .unwrap_or_else(|| bin.clone()); + let stem = dll + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + let jar = match stem.strip_prefix("prism_agent-") { + Some(build) => format!("prism-core-{build}.jar"), + None => "prism-core.jar".to_string(), + }; + boot::Paths { + home, + core_jar: bin.join(jar), + } +} + +#[cfg(windows)] +mod win { + use super::*; + use jni_sys::{jint, jsize, JavaVM, JNI_OK}; + use std::ffi::c_void; + use std::os::windows::ffi::OsStringExt; + use std::ptr::null_mut; + use windows_sys::Win32::Foundation::{BOOL, HMODULE, TRUE}; + use windows_sys::Win32::System::LibraryLoader::{ + DisableThreadLibraryCalls, FreeLibraryAndExitThread, GetModuleFileNameW, GetModuleHandleA, + GetProcAddress, + }; + use windows_sys::Win32::System::SystemServices::DLL_PROCESS_ATTACH; + use windows_sys::Win32::System::Threading::{CreateThread, GetCurrentProcessId}; + + static mut SELF: HMODULE = null_mut(); + + type GetCreatedJavaVMs = unsafe extern "system" fn(*mut *mut JavaVM, jsize, *mut jsize) -> jint; + + fn find_vm() -> Option<*mut JavaVM> { + unsafe { + let jvm = GetModuleHandleA(b"jvm.dll\0".as_ptr()); + if jvm.is_null() { + return None; + } + let f = GetProcAddress(jvm, b"JNI_GetCreatedJavaVMs\0".as_ptr())?; + let f: GetCreatedJavaVMs = std::mem::transmute(f); + let mut vm: *mut JavaVM = null_mut(); + let mut n: jsize = 0; + (f(&mut vm, 1, &mut n) == JNI_OK && n > 0 && !vm.is_null()).then_some(vm) + } + } + + fn own_path() -> PathBuf { + let mut buf = [0u16; 1024]; + let n = unsafe { GetModuleFileNameW(SELF, buf.as_mut_ptr(), buf.len() as u32) } as usize; + PathBuf::from(std::ffi::OsString::from_wide(&buf[..n])) + } + + unsafe extern "system" fn agent_thread(_: *mut c_void) -> u32 { + let paths = paths_from_dll(&own_path()); + log::open(&paths.home.join("logs")); + log::log(&format!( + "Prism agent {} loaded into pid {}", + env!("CARGO_PKG_VERSION"), + GetCurrentProcessId() + )); + let unload_file = paths + .core_jar + .with_file_name(format!("unload-{}", GetCurrentProcessId())); + let _ = std::fs::remove_file(&unload_file); + let mut vm = None; + for _ in 0..60 { + vm = find_vm(); + if vm.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(500)); + } + match vm { + Some(vm) => boot::run(vm, paths, || { + let hit = unload_file.exists(); + if hit { + let _ = std::fs::remove_file(&unload_file); + } + hit + }), + None => log::log("no JVM in this process"), + } + // give any thread that was just inside our code a moment to leave, then unload the DLL + std::thread::sleep(std::time::Duration::from_millis(300)); + FreeLibraryAndExitThread(SELF, 0); + } + + #[no_mangle] + #[allow(non_snake_case)] + pub extern "system" fn DllMain(module: HMODULE, reason: u32, _: *mut c_void) -> BOOL { + if reason == DLL_PROCESS_ATTACH { + unsafe { + SELF = module; + DisableThreadLibraryCalls(module); + let h = CreateThread(null_mut(), 0, Some(agent_thread), null_mut(), 0, null_mut()); + if !h.is_null() { + windows_sys::Win32::Foundation::CloseHandle(h); + } + } + } + TRUE + } +} + +/// JVMTI entry for loading the agent with the attach API (used by the tests on Linux). +#[cfg(not(windows))] +#[no_mangle] +#[allow(non_snake_case)] +pub extern "system" fn Agent_OnAttach( + vm: *mut jni_sys::JavaVM, + options: *const std::ffi::c_char, + _reserved: *mut std::ffi::c_void, +) -> jni_sys::jint { + let opts = if options.is_null() { + String::new() + } else { + unsafe { std::ffi::CStr::from_ptr(options) } + .to_string_lossy() + .into_owned() + }; + let mut parts = opts.splitn(2, '|'); + let home = PathBuf::from(parts.next().unwrap_or(".")); + let core_jar = parts + .next() + .map(PathBuf::from) + .unwrap_or_else(|| home.join("bin").join("prism-core.jar")); + log::open(&home.join("logs")); + log::log("Prism agent loaded (attach)"); + let vm_addr = vm as usize; + let unload_file = home + .join("bin") + .join(format!("unload-{}", std::process::id())); + let _ = std::fs::remove_file(&unload_file); + std::thread::spawn(move || { + let unload = || { + let hit = unload_file.exists(); + if hit { + let _ = std::fs::remove_file(&unload_file); + } + hit + }; + boot::run( + vm_addr as *mut jni_sys::JavaVM, + boot::Paths { home, core_jar }, + unload, + ) + }); + 0 +} diff --git a/native/agent/src/log.rs b/native/agent/src/log.rs new file mode 100644 index 0000000..93adc81 --- /dev/null +++ b/native/agent/src/log.rs @@ -0,0 +1,40 @@ +//! The agent's own log: logs/agent.log in the Prism folder (the core keeps logs/prism.log). + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::Mutex; + +static FILE: Mutex> = Mutex::new(None); + +pub fn open(logs_dir: &Path) { + let _ = std::fs::create_dir_all(logs_dir); + let f = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(logs_dir.join("agent.log")) + .ok(); + *FILE.lock().unwrap() = f; +} + +pub fn log(line: &str) { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let text = format!( + "[{:02}:{:02}:{:02} UTC] {line}\n", + secs / 3600 % 24, + secs / 60 % 60, + secs % 60 + ); + if let Ok(mut g) = FILE.lock() { + if let Some(f) = g.as_mut() { + let _ = f.write_all(text.as_bytes()); + let _ = f.flush(); + } + } + #[cfg(not(windows))] + eprint!("[prism-agent] {text}"); +} diff --git a/native/app/Cargo.toml b/native/app/Cargo.toml new file mode 100644 index 0000000..1ae2c8e --- /dev/null +++ b/native/app/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "prism-app" +description = "The Prism desktop app: inject, auto-inject, plugins, log." +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "Prism" +path = "src/main.rs" + +[dependencies] +prism-inject = { path = "../inject" } +eframe = { version = "0.29", default-features = false, features = ["glow", "default_fonts"] } +zip = { version = "2", default-features = false, features = ["deflate"] } diff --git a/native/app/build.rs b/native/app/build.rs new file mode 100644 index 0000000..83b6328 --- /dev/null +++ b/native/app/build.rs @@ -0,0 +1,22 @@ +// Embeds the agent DLL and the core jar into Prism.exe so the app is a single file. +// Set PRISM_AGENT_DLL and PRISM_CORE_JAR (build.sh / build.ps1 do). Without them the app looks for +// prism_agent.dll and prism-core.jar next to the exe instead (handy while developing). +use std::{env, fs, path::Path}; + +fn main() { + let out = env::var("OUT_DIR").unwrap(); + for (var, name) in [ + ("PRISM_AGENT_DLL", "agent.bin"), + ("PRISM_CORE_JAR", "core.bin"), + ] { + println!("cargo:rerun-if-env-changed={var}"); + let dest = Path::new(&out).join(name); + match env::var(var) { + Ok(src) if !src.is_empty() => { + println!("cargo:rerun-if-changed={src}"); + fs::copy(&src, &dest).unwrap_or_else(|e| panic!("{var}={src}: {e}")); + } + _ => fs::write(&dest, b"").unwrap(), + } + } +} diff --git a/native/app/src/files.rs b/native/app/src/files.rs new file mode 100644 index 0000000..08533f6 --- /dev/null +++ b/native/app/src/files.rs @@ -0,0 +1,182 @@ +//! The Prism folder (%APPDATA%\Prism): installing the agent + core, settings, plugins, log. + +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +static AGENT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/agent.bin")); +static CORE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/core.bin")); + +pub fn home() -> PathBuf { + if let Some(appdata) = std::env::var_os("APPDATA") { + return PathBuf::from(appdata).join("Prism"); + } + let base = std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")); + base.join(".prism") +} + +/// Files of this build, ready to inject. +pub struct Install { + pub agent: PathBuf, + pub build: String, +} + +fn fnv(data: &[&[u8]]) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for d in data { + for b in d.iter() { + h ^= *b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + } + h +} + +/// Writes bin\prism_agent-.dll and bin\prism-core-.jar (once per build). +/// Files are named by build so an update never has to overwrite a file a running game holds. +pub fn install(home: &Path) -> Result { + let bin = home.join("bin"); + for d in ["bin", "plugins", "logs", "data"] { + fs::create_dir_all(home.join(d)) + .map_err(|e| format!("can't create {}: {e}", home.join(d).display()))?; + } + let (agent, core) = if AGENT.is_empty() || CORE.is_empty() { + // development build: files next to the exe + let dir = std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(PathBuf::from)) + .unwrap_or_default(); + let a = fs::read(dir.join("prism_agent.dll")) + .map_err(|_| "prism_agent.dll not found next to Prism.exe")?; + let c = fs::read(dir.join("prism-core.jar")) + .map_err(|_| "prism-core.jar not found next to Prism.exe")?; + (a, c) + } else { + (AGENT.to_vec(), CORE.to_vec()) + }; + let build = format!("{:012x}", fnv(&[&agent, &core]) & 0xffff_ffff_ffff); + let agent_path = bin.join(format!("prism_agent-{build}.dll")); + let core_path = bin.join(format!("prism-core-{build}.jar")); + if fs::read(&agent_path).map(|d| d != agent).unwrap_or(true) { + fs::write(&agent_path, &agent) + .map_err(|e| format!("can't write {}: {e}", agent_path.display()))?; + } + if fs::read(&core_path).map(|d| d != core).unwrap_or(true) { + fs::write(&core_path, &core) + .map_err(|e| format!("can't write {}: {e}", core_path.display()))?; + } + // remove older builds (files still in use by a running game just stay until next time) + if let Ok(rd) = fs::read_dir(&bin) { + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + let old = (name.starts_with("prism_agent-") || name.starts_with("prism-core-")) + && !name.contains(&build); + if old { + let _ = fs::remove_file(e.path()); + } + } + } + Ok(Install { + agent: agent_path, + build, + }) +} + +// ------------------------------------------------------------------ settings + +#[derive(Clone, PartialEq)] +pub struct Settings { + pub auto_inject: bool, +} + +pub fn load_settings(home: &Path) -> Settings { + let text = fs::read_to_string(home.join("app.properties")).unwrap_or_default(); + let get = |k: &str| { + text.lines().find_map(|l| { + l.strip_prefix(&format!("{k}=")) + .map(str::trim) + .map(String::from) + }) + }; + Settings { + auto_inject: get("auto_inject").map(|v| v == "true").unwrap_or(true), + } +} + +pub fn save_settings(home: &Path, s: &Settings) { + let _ = fs::write( + home.join("app.properties"), + format!("auto_inject={}\n", s.auto_inject), + ); +} + +// ------------------------------------------------------------------ plugins + +pub struct PluginFile { + pub file: String, + pub name: String, + pub version: String, + pub error: Option, +} + +fn read_properties(jar: &Path) -> Result, String> { + let f = fs::File::open(jar).map_err(|e| e.to_string())?; + let mut zip = zip::ZipArchive::new(f).map_err(|_| "not a valid jar".to_string())?; + let mut entry = zip + .by_name("plugin.properties") + .map_err(|_| "no plugin.properties".to_string())?; + let mut text = String::new(); + entry.read_to_string(&mut text).map_err(|e| e.to_string())?; + Ok(text + .lines() + .filter(|l| !l.trim_start().starts_with('#')) + .filter_map(|l| { + l.split_once('=') + .map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + }) + .collect()) +} + +pub fn plugins(home: &Path) -> Vec { + let mut out = Vec::new(); + let Ok(rd) = fs::read_dir(home.join("plugins")) else { + return out; + }; + for e in rd.flatten() { + let path = e.path(); + if path.extension().and_then(|x| x.to_str()) != Some("jar") { + continue; + } + let file = e.file_name().to_string_lossy().into_owned(); + match read_properties(&path) { + Ok(props) => { + let get = |k: &str| props.iter().find(|(pk, _)| pk == k).map(|(_, v)| v.clone()); + out.push(PluginFile { + name: get("name") + .or_else(|| get("id")) + .unwrap_or_else(|| file.clone()), + version: get("version").unwrap_or_default(), + file, + error: None, + }); + } + Err(err) => out.push(PluginFile { + name: file.clone(), + version: String::new(), + file, + error: Some(err), + }), + } + } + out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase())); + out +} + +/// The last `n` lines of the core's log. +pub fn log_tail(home: &Path, n: usize) -> String { + let text = fs::read_to_string(home.join("logs").join("prism.log")).unwrap_or_default(); + let lines: Vec<&str> = text.lines().collect(); + lines[lines.len().saturating_sub(n)..].join("\n") +} diff --git a/native/app/src/main.rs b/native/app/src/main.rs new file mode 100644 index 0000000..d4d2bfe --- /dev/null +++ b/native/app/src/main.rs @@ -0,0 +1,341 @@ +//! Prism desktop app: finds games, injects Prism (by hand or automatically into Lunar 1.8.9), +//! lists plugins and shows the log. +#![cfg_attr(windows, windows_subsystem = "windows")] + +mod files; + +use eframe::egui::{self, Color32, RichText}; +use prism_inject::GameProcess; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +const ACCENT: Color32 = Color32::from_rgb(0xb3, 0x7d, 0xff); +const GOOD: Color32 = Color32::from_rgb(0x6d, 0xd6, 0x8c); +const BAD: Color32 = Color32::from_rgb(0xff, 0x6b, 0x6b); +const MUTED: Color32 = Color32::from_rgb(0x9a, 0x94, 0xa8); +/// Wait after a Lunar window appears before auto-injecting (the agent also waits for the game). +const AUTO_DELAY: Duration = Duration::from_secs(3); + +fn main() -> eframe::Result<()> { + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("Prism") + .with_inner_size([520.0, 600.0]) + .with_min_inner_size([420.0, 420.0]), + ..Default::default() + }; + eframe::run_native("Prism", options, Box::new(|cc| Ok(Box::new(App::new(cc))))) +} + +enum Job { + Injected(u32, Result<(), String>), +} + +struct App { + home: PathBuf, + install: Result, + settings: files::Settings, + games: Vec, + plugins: Vec, + log: String, + status: Option<(String, bool)>, + last_refresh: Instant, + /// pid -> when its window was first seen (for the auto-inject delay) + first_seen: HashMap, + /// pids we already tried to auto-inject (never retried automatically) + auto_tried: HashSet, + busy: HashSet, + jobs_tx: mpsc::Sender, + jobs_rx: mpsc::Receiver, +} + +impl App { + fn new(cc: &eframe::CreationContext) -> Self { + style(&cc.egui_ctx); + let home = files::home(); + let install = files::install(&home); + let settings = files::load_settings(&home); + let (jobs_tx, jobs_rx) = mpsc::channel(); + let mut app = App { + home, + install, + settings, + games: Vec::new(), + plugins: Vec::new(), + log: String::new(), + status: None, + last_refresh: Instant::now() - Duration::from_secs(60), + first_seen: HashMap::new(), + auto_tried: HashSet::new(), + busy: HashSet::new(), + jobs_tx, + jobs_rx, + }; + app.refresh(); + app + } + + fn refresh(&mut self) { + self.games = prism_inject::list_games(); + let now = Instant::now(); + let live: HashSet = self.games.iter().map(|g| g.pid).collect(); + self.first_seen.retain(|pid, _| live.contains(pid)); + for g in &self.games { + self.first_seen.entry(g.pid).or_insert(now); + } + self.plugins = files::plugins(&self.home); + self.log = files::log_tail(&self.home, 200); + self.last_refresh = now; + } + + fn inject(&mut self, pid: u32) { + let Ok(install) = &self.install else { return }; + let dll = install.agent.clone(); + let tx = self.jobs_tx.clone(); + self.busy.insert(pid); + std::thread::spawn(move || { + let _ = tx.send(Job::Injected(pid, prism_inject::inject(pid, &dll))); + }); + } + + fn unload(&mut self, pid: u32) { + match prism_inject::request_unload(&self.home.join("bin"), pid) { + Ok(()) => self.status = Some(("Unloading…".into(), true)), + Err(e) => self.status = Some((format!("Unload failed: {e}"), false)), + } + } + + fn auto_inject(&mut self) { + if !self.settings.auto_inject || self.install.is_err() { + return; + } + let due: Vec = self + .games + .iter() + .filter(|g| g.is_lunar_189() && !g.injected && !self.auto_tried.contains(&g.pid)) + .filter(|g| { + self.first_seen + .get(&g.pid) + .is_some_and(|t| t.elapsed() >= AUTO_DELAY) + }) + .map(|g| g.pid) + .collect(); + for pid in due { + self.auto_tried.insert(pid); + self.inject(pid); + } + } +} + +impl eframe::App for App { + fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + while let Ok(job) = self.jobs_rx.try_recv() { + match job { + Job::Injected(pid, r) => { + self.busy.remove(&pid); + self.status = Some(match r { + Ok(()) => ("Injected".into(), true), + Err(e) => (format!("Inject failed: {e}"), false), + }); + self.refresh(); + } + } + } + if self.last_refresh.elapsed() >= Duration::from_secs(2) { + self.refresh(); + self.auto_inject(); + } + ctx.request_repaint_after(Duration::from_millis(500)); + + egui::TopBottomPanel::top("header").show(ctx, |ui| { + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(RichText::new("Prism").size(22.0).strong().color(ACCENT)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let v = match &self.install { + Ok(i) => format!("v{} · {}", env!("CARGO_PKG_VERSION"), &i.build[..6]), + Err(_) => format!("v{}", env!("CARGO_PKG_VERSION")), + }; + ui.label(RichText::new(v).color(MUTED)); + }); + }); + ui.add_space(6.0); + }); + + egui::TopBottomPanel::bottom("status").show(ctx, |ui| { + ui.add_space(4.0); + match (&self.install, &self.status) { + (Err(e), _) => { + ui.label(RichText::new(e).color(BAD)); + } + (_, Some((msg, ok))) => { + ui.label(RichText::new(msg).color(if *ok { GOOD } else { BAD })); + } + _ => { + ui.label(RichText::new(self.home.display().to_string()).color(MUTED)); + } + } + ui.add_space(4.0); + }); + + egui::CentralPanel::default().show(ctx, |ui| { + egui::ScrollArea::vertical().show(ui, |ui| { + section(ui, "Games"); + if self.games.is_empty() { + ui.label(RichText::new("No game running").color(MUTED)); + } + let mut action: Option<(u32, bool)> = None; + for g in &self.games { + card(ui, |ui| { + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.label(RichText::new(&g.title).strong()); + let (txt, col) = if g.injected { + ("Injected", GOOD) + } else { + ("Not injected", MUTED) + }; + ui.label(RichText::new(txt).color(col).small()); + }); + ui.with_layout( + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + if self.busy.contains(&g.pid) { + ui.spinner(); + } else if g.injected { + if ui.button("Unload").clicked() { + action = Some((g.pid, false)); + } + } else if ui + .add_enabled( + self.install.is_ok(), + egui::Button::new(RichText::new("Inject").strong()) + .fill(ACCENT.linear_multiply(0.35)), + ) + .clicked() + { + action = Some((g.pid, true)); + } + }, + ); + }); + }); + } + match action { + Some((pid, true)) => self.inject(pid), + Some((pid, false)) => self.unload(pid), + None => {} + } + let before = self.settings.clone(); + ui.checkbox(&mut self.settings.auto_inject, "Auto-inject Lunar 1.8.9"); + if self.settings != before { + files::save_settings(&self.home, &self.settings); + } + + ui.add_space(10.0); + ui.horizontal(|ui| { + section(ui, "Plugins"); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button("Open folder").clicked() { + open_folder(&self.home.join("plugins")); + } + }); + }); + if self.plugins.is_empty() { + ui.label( + RichText::new("No plugins. Drop .jar files in the plugins folder.") + .color(MUTED), + ); + } + for p in &self.plugins { + card(ui, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(&p.name).strong()) + .on_hover_text(&p.file); + ui.label(RichText::new(&p.version).color(MUTED)); + if let Some(e) = &p.error { + ui.with_layout( + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + ui.label(RichText::new(e).color(BAD).small()); + }, + ); + } + }); + }); + } + + ui.add_space(10.0); + egui::CollapsingHeader::new(RichText::new("Log").strong()) + .default_open(false) + .show(ui, |ui| { + ui.horizontal(|ui| { + if ui.small_button("Open logs folder").clicked() { + open_folder(&self.home.join("logs")); + } + }); + egui::ScrollArea::vertical() + .max_height(220.0) + .stick_to_bottom(true) + .show(ui, |ui| { + ui.add( + egui::Label::new( + RichText::new(if self.log.is_empty() { + "(empty)" + } else { + &self.log + }) + .monospace() + .small(), + ) + .wrap(), + ); + }); + }); + }); + }); + } +} + +fn section(ui: &mut egui::Ui, title: &str) { + ui.label(RichText::new(title).size(15.0).strong()); + ui.add_space(2.0); +} + +fn card(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { + egui::Frame::none() + .fill(Color32::from_rgb(0x1d, 0x1a, 0x26)) + .rounding(8.0) + .inner_margin(egui::Margin::symmetric(10.0, 8.0)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + add(ui) + }); + ui.add_space(4.0); +} + +fn open_folder(path: &std::path::Path) { + let _ = std::fs::create_dir_all(path); + #[cfg(windows)] + let _ = std::process::Command::new("explorer").arg(path).spawn(); + #[cfg(not(windows))] + let _ = std::process::Command::new("xdg-open").arg(path).spawn(); +} + +fn style(ctx: &egui::Context) { + let mut v = egui::Visuals::dark(); + v.panel_fill = Color32::from_rgb(0x13, 0x11, 0x1a); + v.window_fill = v.panel_fill; + v.selection.bg_fill = ACCENT.linear_multiply(0.5); + v.hyperlink_color = ACCENT; + v.widgets.inactive.rounding = 6.0.into(); + v.widgets.hovered.rounding = 6.0.into(); + v.widgets.active.rounding = 6.0.into(); + ctx.set_visuals(v); + let mut s = (*ctx.style()).clone(); + s.spacing.item_spacing = egui::vec2(8.0, 6.0); + s.spacing.button_padding = egui::vec2(12.0, 5.0); + ctx.set_style(s); +} diff --git a/native/inject/Cargo.toml b/native/inject/Cargo.toml new file mode 100644 index 0000000..744374f --- /dev/null +++ b/native/inject/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "prism-inject" +description = "Finds running Minecraft (Java) games and loads the Prism agent into them." +version.workspace = true +edition.workspace = true +license.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Diagnostics_Debug", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_ProcessStatus", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/native/inject/src/lib.rs b/native/inject/src/lib.rs new file mode 100644 index 0000000..edfa03d --- /dev/null +++ b/native/inject/src/lib.rs @@ -0,0 +1,43 @@ +//! Finding games and loading the agent DLL into them. +//! +//! Injection is the classic, documented way: allocate the DLL path in the game process, +//! then start a thread there at LoadLibraryW. The agent does the rest from DllMain. + +use std::path::Path; + +#[derive(Clone, Debug)] +pub struct GameProcess { + pub pid: u32, + /// Window title, e.g. "Lunar Client 1.8.9 (...)". + pub title: String, + /// True when a prism_agent DLL is loaded in it. + pub injected: bool, +} + +impl GameProcess { + /// Lunar 1.8.9 (what auto-inject targets). + pub fn is_lunar_189(&self) -> bool { + let t = self.title.to_lowercase(); + t.contains("lunar") && t.contains("1.8.9") + } +} + +#[cfg(windows)] +mod win; +#[cfg(windows)] +pub use win::{inject, list_games}; + +#[cfg(not(windows))] +pub fn list_games() -> Vec { + Vec::new() +} + +#[cfg(not(windows))] +pub fn inject(_pid: u32, _dll: &Path) -> Result<(), String> { + Err("injection is only supported on Windows".into()) +} + +/// Asks the agent in `pid` to unload (it polls for this file next to its core jar). +pub fn request_unload(bin_dir: &Path, pid: u32) -> std::io::Result<()> { + std::fs::write(bin_dir.join(format!("unload-{pid}")), b"") +} diff --git a/native/inject/src/win.rs b/native/inject/src/win.rs new file mode 100644 index 0000000..a36a578 --- /dev/null +++ b/native/inject/src/win.rs @@ -0,0 +1,174 @@ +use crate::GameProcess; +use std::collections::HashMap; +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::ptr::null_mut; +use windows_sys::Win32::Foundation::{ + CloseHandle, BOOL, HANDLE, HMODULE, HWND, LPARAM, TRUE, WAIT_OBJECT_0, +}; +use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; +use windows_sys::Win32::System::Memory::{ + VirtualAllocEx, VirtualFreeEx, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, +}; +use windows_sys::Win32::System::ProcessStatus::{ + EnumProcessModulesEx, GetModuleBaseNameW, LIST_MODULES_ALL, +}; +use windows_sys::Win32::System::Threading::{ + CreateRemoteThread, GetExitCodeThread, OpenProcess, WaitForSingleObject, PROCESS_CREATE_THREAD, + PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, PROCESS_VM_READ, PROCESS_VM_WRITE, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + EnumWindows, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible, +}; + +struct Handle(HANDLE); +impl Drop for Handle { + fn drop(&mut self) { + unsafe { CloseHandle(self.0) }; + } +} + +fn open(pid: u32, access: u32) -> Option { + let h = unsafe { OpenProcess(access, 0, pid) }; + (!h.is_null()).then(|| Handle(h)) +} + +/// Lower-case names of the modules loaded in a process. +fn modules(pid: u32) -> Vec { + let Some(p) = open(pid, PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) else { + return Vec::new(); + }; + let mut mods: Vec = vec![null_mut(); 1024]; + let mut needed = 0u32; + let size = (mods.len() * std::mem::size_of::()) as u32; + if unsafe { EnumProcessModulesEx(p.0, mods.as_mut_ptr(), size, &mut needed, LIST_MODULES_ALL) } + == 0 + { + return Vec::new(); + } + let n = (needed as usize / std::mem::size_of::()).min(mods.len()); + mods[..n] + .iter() + .filter_map(|&m| { + let mut buf = [0u16; 260]; + let len = + unsafe { GetModuleBaseNameW(p.0, m, buf.as_mut_ptr(), buf.len() as u32) } as usize; + (len > 0).then(|| String::from_utf16_lossy(&buf[..len]).to_lowercase()) + }) + .collect() +} + +unsafe extern "system" fn collect_window(hwnd: HWND, lparam: LPARAM) -> BOOL { + let out = &mut *(lparam as *mut HashMap); + if IsWindowVisible(hwnd) == 0 { + return TRUE; + } + let len = GetWindowTextLengthW(hwnd); + if len <= 0 { + return TRUE; + } + let mut buf = vec![0u16; len as usize + 1]; + let n = GetWindowTextW(hwnd, buf.as_mut_ptr(), buf.len() as i32) as usize; + let mut pid = 0u32; + GetWindowThreadProcessId(hwnd, &mut pid); + out.entry(pid) + .or_insert_with(|| String::from_utf16_lossy(&buf[..n])); + TRUE +} + +/// Every process with a visible window that has a JVM loaded (Minecraft Java clients). +pub fn list_games() -> Vec { + let mut windows: HashMap = HashMap::new(); + unsafe { EnumWindows(Some(collect_window), &mut windows as *mut _ as LPARAM) }; + let mut games: Vec = windows + .into_iter() + .filter_map(|(pid, title)| { + let mods = modules(pid); + if !mods.iter().any(|m| m == "jvm.dll") { + return None; + } + let injected = mods.iter().any(|m| m.starts_with("prism_agent")); + Some(GameProcess { + pid, + title, + injected, + }) + }) + .collect(); + games.sort_by_key(|g| g.pid); + games +} + +/// Loads `dll` into process `pid`. +pub fn inject(pid: u32, dll: &Path) -> Result<(), String> { + let wide: Vec = dll + .as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect(); + let bytes = wide.len() * 2; + let p = open( + pid, + PROCESS_CREATE_THREAD + | PROCESS_QUERY_INFORMATION + | PROCESS_VM_OPERATION + | PROCESS_VM_WRITE + | PROCESS_VM_READ, + ) + .ok_or_else(|| { + format!("can't open process {pid} (try running Prism as the same user as the game)") + })?; + unsafe { + let mem = VirtualAllocEx( + p.0, + null_mut(), + bytes, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ); + if mem.is_null() { + return Err("VirtualAllocEx failed".into()); + } + let result = (|| { + if WriteProcessMemory(p.0, mem, wide.as_ptr() as *const c_void, bytes, null_mut()) == 0 + { + return Err("WriteProcessMemory failed".to_string()); + } + // kernel32 is mapped at the same address in every process of a boot session + let k32 = GetModuleHandleA(b"kernel32.dll\0".as_ptr()); + let load = + GetProcAddress(k32, b"LoadLibraryW\0".as_ptr()).ok_or("LoadLibraryW not found")?; + let thread = CreateRemoteThread( + p.0, + null_mut(), + 0, + Some(std::mem::transmute::< + _, + unsafe extern "system" fn(*mut c_void) -> u32, + >(load)), + mem, + 0, + null_mut(), + ); + if thread.is_null() { + return Err("CreateRemoteThread failed".to_string()); + } + let t = Handle(thread); + if WaitForSingleObject(t.0, 15_000) != WAIT_OBJECT_0 { + return Err("the game didn't load the DLL in time".to_string()); + } + let mut code = 0u32; + GetExitCodeThread(t.0, &mut code); + if code == 0 { + return Err( + "LoadLibraryW failed in the game (antivirus or missing file?)".to_string(), + ); + } + Ok(()) + })(); + VirtualFreeEx(p.0, mem, 0, MEM_RELEASE); + result + } +} diff --git a/tests/fake-game/src/launcher/Launcher.java b/tests/fake-game/src/launcher/Launcher.java new file mode 100644 index 0000000..3b08f67 --- /dev/null +++ b/tests/fake-game/src/launcher/Launcher.java @@ -0,0 +1,22 @@ +package launcher; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; + +/** Loads the "game" through its own class loader on a "Client thread", like Lunar and Forge do. */ +public class Launcher { + public static void main(String[] args) throws Exception { + ClassLoader game = new URLClassLoader(new URL[] {new File(args[0]).toURI().toURL()}, null); + Thread t = new Thread(() -> { + try { + game.loadClass("net.minecraft.client.Minecraft").getMethod("run").invoke(null); + } catch (Exception e) { + e.printStackTrace(); + } + }, "Client thread"); + t.setContextClassLoader(game); + t.start(); + t.join(); + } +} diff --git a/tests/fake-game/src/net/minecraft/client/Minecraft.java b/tests/fake-game/src/net/minecraft/client/Minecraft.java new file mode 100644 index 0000000..1aea2f3 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/Minecraft.java @@ -0,0 +1,33 @@ +package net.minecraft.client; + +import java.util.ArrayDeque; +import java.util.Queue; +import net.minecraft.client.gui.GuiIngame; + +/** Stand-in with the same names Lunar uses (MCP), for testing the agent and core. */ +public class Minecraft { + private static Minecraft theMinecraft; + public GuiIngame ingameGUI; + private final Queue scheduledTasks = new ArrayDeque<>(); + + public static Minecraft getMinecraft() { return theMinecraft; } + + public Object addScheduledTask(Runnable r) { + synchronized (scheduledTasks) { scheduledTasks.add(r); } + return null; + } + + public static void run() throws Exception { + Thread.sleep(1500); // "loading" + theMinecraft = new Minecraft(); + theMinecraft.ingameGUI = new GuiIngame(); + System.out.println("GAME: started"); + while (true) { // game loop, 50 fps + synchronized (theMinecraft.scheduledTasks) { + Runnable r; + while ((r = theMinecraft.scheduledTasks.poll()) != null) r.run(); + } + Thread.sleep(20); + } + } +} diff --git a/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java b/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java new file mode 100644 index 0000000..e6bee9b --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java @@ -0,0 +1,5 @@ +package net.minecraft.client.gui; +public class GuiIngame { + private final GuiNewChat chat = new GuiNewChat(); + public GuiNewChat getChatGUI() { return chat; } +} diff --git a/tests/fake-game/src/net/minecraft/client/gui/GuiNewChat.java b/tests/fake-game/src/net/minecraft/client/gui/GuiNewChat.java new file mode 100644 index 0000000..782d1f6 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/gui/GuiNewChat.java @@ -0,0 +1,7 @@ +package net.minecraft.client.gui; +import net.minecraft.util.IChatComponent; +public class GuiNewChat { + public void printChatMessage(IChatComponent c) { + System.out.println("CHAT[" + Thread.currentThread().getName() + "]: " + c.getUnformattedText()); + } +} diff --git a/tests/fake-game/src/net/minecraft/util/ChatComponentText.java b/tests/fake-game/src/net/minecraft/util/ChatComponentText.java new file mode 100644 index 0000000..0a5cc82 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/util/ChatComponentText.java @@ -0,0 +1,6 @@ +package net.minecraft.util; +public class ChatComponentText implements IChatComponent { + private final String text; + public ChatComponentText(String text) { this.text = text; } + public String getUnformattedText() { return text; } +} diff --git a/tests/fake-game/src/net/minecraft/util/IChatComponent.java b/tests/fake-game/src/net/minecraft/util/IChatComponent.java new file mode 100644 index 0000000..580a8c2 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/util/IChatComponent.java @@ -0,0 +1,2 @@ +package net.minecraft.util; +public interface IChatComponent { String getUnformattedText(); } diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..f1ec0ce --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# End-to-end test on Linux: a stand-in game (MCP names, own class loader, client thread) gets the +# agent loaded with jcmd, then we check load, chat, hot reload, removal and unload. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +W="$(mktemp -d)"; trap 'kill $GAME 2>/dev/null || true; rm -rf "$W"' EXIT +fail() { echo "FAIL: $1"; echo "--- game output"; cat "$W/out.txt"; echo "--- prism.log"; cat "$W/home/logs/prism.log" 2>/dev/null; exit 1; } +wait_for() { for _ in $(seq 1 100); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 0.1; done; fail "timed out waiting for '$2' in $(basename "$1")"; } + +(cd "$ROOT/java" && gradle -q build) +(cd "$ROOT" && cargo build -q -p prism-agent) +mkdir -p "$W/classes/game" "$W/classes/launcher" "$W/home/bin" "$W/home/plugins" +SRC="$ROOT/tests/fake-game/src" +javac -q -d "$W/classes/game" $(find "$SRC/net" -name '*.java') 2>/dev/null || javac -d "$W/classes/game" $(find "$SRC/net" -name '*.java') +(cd "$W/classes/game" && jar cf "$W/game.jar" .) +javac -d "$W/classes/launcher" "$SRC/launcher/Launcher.java" +cp "$ROOT/java/core/build/libs/prism-core-0.1.0.jar" "$W/home/bin/prism-core.jar" +cp "$ROOT/java/example-plugin/build/libs/example-plugin-0.1.0.jar" "$W/home/plugins/example.jar" + +java -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 -XX:+EnableDynamicAgentLoading -cp "$W/classes/launcher" launcher.Launcher "$W/game.jar" > "$W/out.txt" 2>&1 & +GAME=$! +sleep 0.5 # inject while the game is still "loading" +jcmd $GAME JVMTI.agent_load "$ROOT/target/debug/libprism_agent.so" "$W/home|$W/home/bin/prism-core.jar" >/dev/null + +wait_for "$W/out.txt" "GAME: started" +wait_for "$W/out.txt" "CHAT\[Client thread\]: §d\[Prism\] §fLoaded Example" +wait_for "$W/out.txt" "CHAT\[Client thread\]: §d\[Example\] §fHello!" +grep -q "mcp names" "$W/home/logs/prism.log" || fail "mappings not detected as mcp" +echo "ok injected, core started on the game's class loader, plugin loaded, chat on client thread" + +# hot reload: replace the jar with a new version (different properties -> different file) +mkdir -p "$W/p2"; (cd "$W/p2" && unzip -q "$W/home/plugins/example.jar" && sed -i 's/version=1.0.0/version=1.0.1/' plugin.properties && jar cf "$W/example2.jar" .) +cp "$W/example2.jar" "$W/home/plugins/example.jar" +wait_for "$W/home/logs/prism.log" "enabled Example 1.0.1" +wait_for "$W/out.txt" "Reloaded Example" +grep -q "disabled Example 1.0.0" "$W/home/logs/prism.log" || fail "old version not disabled" +echo "ok hot reload" + +# a broken plugin must not break the others +echo "not a jar" > "$W/home/plugins/broken.jar" +wait_for "$W/out.txt" "broken.jar failed to load" +echo "ok broken plugin reported" +rm "$W/home/plugins/broken.jar" + +rm "$W/home/plugins/example.jar" +wait_for "$W/home/logs/prism.log" "disabled Example 1.0.1" +echo "ok plugin removed" + +touch "$W/home/bin/unload-$GAME" +wait_for "$W/home/logs/agent.log" "unloaded" +grep -q "stopped" "$W/home/logs/prism.log" 2>/dev/null || grep -q "stopped" "$W/home/logs/prism.old.log" || fail "core not stopped" +kill -0 $GAME || fail "game died after unload" +echo "ok unloaded, game still running" + +# inject again after unload (the app's Inject button after Unload) +cp "$ROOT/java/example-plugin/build/libs/example-plugin-0.1.0.jar" "$W/home/plugins/example.jar" +: > "$W/out.txt.mark"; LINES=$(wc -l < "$W/out.txt") +jcmd $GAME JVMTI.agent_load "$ROOT/target/debug/libprism_agent.so" "$W/home|$W/home/bin/prism-core.jar" >/dev/null +for _ in $(seq 1 100); do tail -n +$((LINES+1)) "$W/out.txt" | grep -q "Loaded Example" && break; sleep 0.1; done +tail -n +$((LINES+1)) "$W/out.txt" | grep -q "Loaded Example" || fail "re-inject didn't load" +echo "ok injected again" +echo "ALL PASSED" From 3c44be9235e440b915652c3fb7deba4992dc7dc0 Mon Sep 17 00:00:00 2001 From: MonsterMilo <108966405+MonsterMilo@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:03:51 +0000 Subject: [PATCH 2/2] Game hooks: tick, HUD/world rendering, key and mouse events - agent: JVMTI retransform with a ClassFileLoadHook that is only on for the class being patched; Native.retransform0 replaces redefineClass0 - core: hook system (ASM, relocated to prism.shadow.asm). Injected code uses only JDK classes via System properties; all patches undone on unload - events: TickEvent, RenderOverlayEvent, RenderWorldEvent, KeyEvent, MouseButtonEvent (key/mouse cancelable); Draw API for text and rects - fix: a plugin added while running now says Loaded, not Reloaded - tests: stand-in game gets the hooked methods; hook test plugin checks events, cancel, restore on unload and re-inject Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N1jsNaA8oesLoCYL6zeeF7 --- .github/workflows/build.yml | 6 +- Cargo.lock | 6 +- Cargo.toml | 2 +- README.md | 10 +- build.sh | 6 +- docs/ARCHITECTURE.md | 25 ++- java/api/build.gradle | 1 + java/api/src/main/java/prism/api/Draw.java | 15 ++ java/api/src/main/java/prism/api/Game.java | 3 + .../java/prism/api/event/Cancellable.java | 10 + .../main/java/prism/api/event/KeyEvent.java | 18 ++ .../prism/api/event/MouseButtonEvent.java | 18 ++ .../prism/api/event/RenderOverlayEvent.java | 20 ++ .../prism/api/event/RenderWorldEvent.java | 10 + .../main/java/prism/api/event/TickEvent.java | 8 + java/build.gradle | 2 +- java/core/build.gradle | 19 +- .../src/main/java/prism/core/DrawImpl.java | 106 ++++++++++ .../src/main/java/prism/core/GameImpl.java | 8 + .../core/src/main/java/prism/core/Native.java | 14 +- .../main/java/prism/core/PluginManager.java | 9 +- java/core/src/main/java/prism/core/Prism.java | 17 +- .../main/java/prism/core/hook/GameHooks.java | 51 +++++ .../src/main/java/prism/core/hook/Hook.java | 68 ++++++ .../src/main/java/prism/core/hook/Hooks.java | 103 +++++++++ .../main/java/prism/core/hook/Patcher.java | 195 ++++++++++++++++++ java/example-plugin/build.gradle | 1 + .../src/main/java/example/ExamplePlugin.java | 20 +- java/settings.gradle | 1 + native/agent/src/boot.rs | 99 +++++++-- native/agent/src/jvm.rs | 96 +++++++-- .../src/net/minecraft/client/Minecraft.java | 20 +- .../minecraft/client/gui/FontRenderer.java | 10 + .../src/net/minecraft/client/gui/Gui.java | 5 + .../net/minecraft/client/gui/GuiIngame.java | 3 + .../client/gui/ScaledResolution.java | 7 + .../client/renderer/EntityRenderer.java | 11 + .../minecraft/client/settings/KeyBinding.java | 6 + tests/hook-plugin/plugin.properties | 4 + .../src/hooktest/HookTestPlugin.java | 31 +++ tests/run.sh | 43 +++- 41 files changed, 1027 insertions(+), 80 deletions(-) create mode 100644 java/api/src/main/java/prism/api/Draw.java create mode 100644 java/api/src/main/java/prism/api/event/Cancellable.java create mode 100644 java/api/src/main/java/prism/api/event/KeyEvent.java create mode 100644 java/api/src/main/java/prism/api/event/MouseButtonEvent.java create mode 100644 java/api/src/main/java/prism/api/event/RenderOverlayEvent.java create mode 100644 java/api/src/main/java/prism/api/event/RenderWorldEvent.java create mode 100644 java/api/src/main/java/prism/api/event/TickEvent.java create mode 100644 java/core/src/main/java/prism/core/DrawImpl.java create mode 100644 java/core/src/main/java/prism/core/hook/GameHooks.java create mode 100644 java/core/src/main/java/prism/core/hook/Hook.java create mode 100644 java/core/src/main/java/prism/core/hook/Hooks.java create mode 100644 java/core/src/main/java/prism/core/hook/Patcher.java create mode 100644 tests/fake-game/src/net/minecraft/client/gui/FontRenderer.java create mode 100644 tests/fake-game/src/net/minecraft/client/gui/Gui.java create mode 100644 tests/fake-game/src/net/minecraft/client/gui/ScaledResolution.java create mode 100644 tests/fake-game/src/net/minecraft/client/renderer/EntityRenderer.java create mode 100644 tests/fake-game/src/net/minecraft/client/settings/KeyBinding.java create mode 100644 tests/hook-plugin/plugin.properties create mode 100644 tests/hook-plugin/src/hooktest/HookTestPlugin.java diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index accacad..f0cf2a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,12 +31,12 @@ jobs: cd java; gradle -q build; cd .. cargo build --release -p prism-agent $env:PRISM_AGENT_DLL = "$PWD\target\release\prism_agent.dll" - $env:PRISM_CORE_JAR = "$PWD\java\core\build\libs\prism-core-0.1.0.jar" + $env:PRISM_CORE_JAR = "$PWD\java\core\build\libs\prism-core.jar" cargo build --release -p prism-app New-Item -ItemType Directory -Force dist | Out-Null Copy-Item target\release\Prism.exe dist\ - Copy-Item java\api\build\libs\prism-api-0.1.0.jar dist\prism-api.jar - Copy-Item java\example-plugin\build\libs\example-plugin-0.1.0.jar dist\example-plugin.jar + Copy-Item java\api\build\libs\prism-api.jar dist\prism-api.jar + Copy-Item java\example-plugin\build\libs\example-plugin.jar dist\example-plugin.jar - uses: actions/upload-artifact@v4 with: name: prism-windows diff --git a/Cargo.lock b/Cargo.lock index 1c7ff76..4be85b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1570,7 +1570,7 @@ dependencies = [ [[package]] name = "prism-agent" -version = "0.1.0" +version = "0.2.0" dependencies = [ "jni-sys 0.3.1", "windows-sys 0.59.0", @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "prism-app" -version = "0.1.0" +version = "0.2.0" dependencies = [ "eframe", "prism-inject", @@ -1587,7 +1587,7 @@ dependencies = [ [[package]] name = "prism-inject" -version = "0.1.0" +version = "0.2.0" dependencies = [ "windows-sys 0.59.0", ] diff --git a/Cargo.toml b/Cargo.toml index 5e94349..cdd978d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["native/agent", "native/inject", "native/app"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT" diff --git a/README.md b/README.md index 31b1117..b67f8d6 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ An open-source plugin platform for Minecraft 1.8.9. Prism loads into a running game (Lunar Client first; Forge and vanilla next) and runs Java plugins inside it. -> Status: **base only**. Injection, the Java core, plugin loading with hot reload and the -> desktop app work. Features come next, one at a time. +> Status: early. Injection, the Java core, plugin loading with hot reload, the desktop app and +> game events (ticks, HUD/world rendering, keys and mouse) work. Features come next. ## Using it @@ -32,11 +32,15 @@ public class ExamplePlugin implements Plugin { @Override public void onEnable(PluginContext ctx) { ctx.game().chat("§dHello!"); - ctx.scheduler().every(1000, () -> { /* runs on the game thread */ }); + ctx.events().on(RenderOverlayEvent.class, e -> ctx.game().draw().text("§dHi", 4, 4, -1)); + ctx.events().on(KeyEvent.class, e -> { if (e.key() == 30) e.cancel(); }); // block A } } ``` +Events: `TickEvent`, `RenderOverlayEvent`, `RenderWorldEvent`, `KeyEvent`, `MouseButtonEvent`, +`PluginEnableEvent`, `PluginDisableEvent`, `ShutdownEvent`. + See [`java/example-plugin`](java/example-plugin) and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). ## Building diff --git a/build.sh b/build.sh index 13e4c97..9301882 100755 --- a/build.sh +++ b/build.sh @@ -10,10 +10,10 @@ if [[ "$(uname -s)" != MINGW* && "$(uname -s)" != MSYS* ]]; then fi (cd java && gradle -q build) cargo build --release "${TARGET_ARGS[@]}" -p prism-agent -PRISM_AGENT_DLL="$PWD/$OUT/prism_agent.dll" PRISM_CORE_JAR="$PWD/java/core/build/libs/prism-core-0.1.0.jar" \ +PRISM_AGENT_DLL="$PWD/$OUT/prism_agent.dll" PRISM_CORE_JAR="$PWD/java/core/build/libs/prism-core.jar" \ cargo build --release "${TARGET_ARGS[@]}" -p prism-app mkdir -p dist cp "$OUT/Prism.exe" dist/ -cp java/api/build/libs/prism-api-0.1.0.jar dist/prism-api.jar -cp java/example-plugin/build/libs/example-plugin-0.1.0.jar dist/example-plugin.jar +cp java/api/build/libs/prism-api.jar dist/prism-api.jar +cp java/example-plugin/build/libs/example-plugin.jar dist/example-plugin.jar ls -la dist diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index da88b49..41ed694 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -20,7 +20,7 @@ Prism.exe (Rust) the game (javaw.exe) - **inject**: lists visible windows whose process has `jvm.dll` loaded, and loads the agent with `VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread(LoadLibraryW)`. - **agent**: `DllMain` starts a thread that attaches to the JVM as a daemon thread, gets JVMTI - (with `can_redefine_classes` for the hook system later) and waits until Minecraft is loaded. + (with `can_retransform_classes` for the hook system) and waits until Minecraft is loaded. It finds the game's class loader from the threads' context class loaders, falling back to JVMTI `GetLoadedClasses`, and detects the names the client uses: @@ -32,7 +32,7 @@ Prism.exe (Rust) the game (javaw.exe) The core jar is loaded by a `URLClassLoader` whose parent is the game's loader, so core and plugins can use Minecraft classes. The agent registers the natives of `prism.core.Native` - (log, unload, redefine class). + (log, unload, retransform class). - **Unload**: the app creates `bin\unload-`. The agent calls `Prism.stop()`, unregisters its natives, closes the core's class loader, detaches and frees the DLL. The game keeps running. - Files are named per build (`-`), so a new version never needs to overwrite a DLL or jar @@ -50,8 +50,27 @@ Prism.exe (Rust) the game (javaw.exe) - Game state is only touched on the client thread. `Scheduler` runs work there through `Minecraft#addScheduledTask`, found by its shape, so it works with every naming scheme. +## Hooks (`prism.core.hook`) + +Prism patches a few game methods to raise its events: + +| event | method (MCP / SRG) | where | +|---|---|---| +| `TickEvent` | `Minecraft.runTick` / `func_71407_l` | start | +| `RenderOverlayEvent` | `GuiIngame.renderGameOverlay` / `func_175180_a` | every return | +| `RenderWorldEvent` | `EntityRenderer.renderWorldPass` / `func_175068_a` | before `renderHand` | +| `KeyEvent`, `MouseButtonEvent` | `KeyBinding.setKeyBindState` / `func_74510_a` | start, cancelable | + +- The agent retransforms a class (JVMTI `RetransformClasses`) with its ClassFileLoadHook switched on + only for that call. The hook passes the class's current bytes to a Java transformer, so Prism + patches what the game is really running (a client's own patches stay). +- The patch is ASM (bundled, moved to `prism.shadow.asm`). The added code only uses JDK classes: + `((Predicate) System.getProperties().get("prism.hook.")).test(args)`, so the game's class + loader never needs to see Prism. A cancelable hook returns early when the handler says so. +- On unload every patched class is retransformed without the hook, which puts back the original. + The property is set before patching and only removed once the class is restored. + ## Next steps (not built yet) -- Hooks: patch game methods (JVMTI redefine + ASM) for ticks, rendering and input events. - Packets: a Netty handler in the game's pipeline for packet events. - In-game UI, updates, Forge and vanilla testing. diff --git a/java/api/build.gradle b/java/api/build.gradle index 98f78c7..58059c2 100644 --- a/java/api/build.gradle +++ b/java/api/build.gradle @@ -1,3 +1,4 @@ // prism-api.jar: what plugins compile against. base { archivesName = 'prism-api' } java { withSourcesJar() } +tasks.withType(Jar).configureEach { archiveVersion = '' } diff --git a/java/api/src/main/java/prism/api/Draw.java b/java/api/src/main/java/prism/api/Draw.java new file mode 100644 index 0000000..12a56cb --- /dev/null +++ b/java/api/src/main/java/prism/api/Draw.java @@ -0,0 +1,15 @@ +package prism.api; + +/** Simple 2D drawing. Only call it inside a RenderOverlayEvent handler. Colors are 0xAARRGGBB. */ +public interface Draw { + /** Draws text with a shadow; supports § colour codes. Returns the text width. */ + int text(String text, float x, float y, int color); + + int textWidth(String text); + + /** Height of one line of text. */ + int fontHeight(); + + /** Filled rectangle from (x1, y1) to (x2, y2). */ + void rect(int x1, int y1, int x2, int y2, int color); +} diff --git a/java/api/src/main/java/prism/api/Game.java b/java/api/src/main/java/prism/api/Game.java index 6fd0096..b564e66 100644 --- a/java/api/src/main/java/prism/api/Game.java +++ b/java/api/src/main/java/prism/api/Game.java @@ -16,4 +16,7 @@ public interface Game { * Supports {@code §} colour codes. Safe to call from any thread. */ void chat(String message); + + /** 2D drawing for RenderOverlayEvent handlers. */ + Draw draw(); } diff --git a/java/api/src/main/java/prism/api/event/Cancellable.java b/java/api/src/main/java/prism/api/event/Cancellable.java new file mode 100644 index 0000000..f624c3b --- /dev/null +++ b/java/api/src/main/java/prism/api/event/Cancellable.java @@ -0,0 +1,10 @@ +package prism.api.event; + +/** An event a handler can cancel, stopping what the game was about to do. */ +public abstract class Cancellable { + private boolean cancelled; + + public void cancel() { cancelled = true; } + + public boolean isCancelled() { return cancelled; } +} diff --git a/java/api/src/main/java/prism/api/event/KeyEvent.java b/java/api/src/main/java/prism/api/event/KeyEvent.java new file mode 100644 index 0000000..3d3b245 --- /dev/null +++ b/java/api/src/main/java/prism/api/event/KeyEvent.java @@ -0,0 +1,18 @@ +package prism.api.event; + +/** + * A key went down or up while playing (not while a menu or chat is open). + * Key codes are LWJGL codes (e.g. 30 = A). Cancel to hide it from the game's keybinds. + */ +public final class KeyEvent extends Cancellable { + private final int key; + private final boolean pressed; + + public KeyEvent(int key, boolean pressed) { + this.key = key; + this.pressed = pressed; + } + + public int key() { return key; } + public boolean pressed() { return pressed; } +} diff --git a/java/api/src/main/java/prism/api/event/MouseButtonEvent.java b/java/api/src/main/java/prism/api/event/MouseButtonEvent.java new file mode 100644 index 0000000..83d2924 --- /dev/null +++ b/java/api/src/main/java/prism/api/event/MouseButtonEvent.java @@ -0,0 +1,18 @@ +package prism.api.event; + +/** + * A mouse button went down or up while playing (0 = left, 1 = right, 2 = middle). + * Cancel to hide it from the game's keybinds (e.g. stop an attack or use). + */ +public final class MouseButtonEvent extends Cancellable { + private final int button; + private final boolean pressed; + + public MouseButtonEvent(int button, boolean pressed) { + this.button = button; + this.pressed = pressed; + } + + public int button() { return button; } + public boolean pressed() { return pressed; } +} diff --git a/java/api/src/main/java/prism/api/event/RenderOverlayEvent.java b/java/api/src/main/java/prism/api/event/RenderOverlayEvent.java new file mode 100644 index 0000000..0bca08c --- /dev/null +++ b/java/api/src/main/java/prism/api/event/RenderOverlayEvent.java @@ -0,0 +1,20 @@ +package prism.api.event; + +/** + * After the game drew its HUD, every frame. Draw with {@code ctx.game().draw()}. + * Width and height are in GUI-scaled pixels. + */ +public final class RenderOverlayEvent { + private final float partialTicks; + private final int width, height; + + public RenderOverlayEvent(float partialTicks, int width, int height) { + this.partialTicks = partialTicks; + this.width = width; + this.height = height; + } + + public float partialTicks() { return partialTicks; } + public int width() { return width; } + public int height() { return height; } +} diff --git a/java/api/src/main/java/prism/api/event/RenderWorldEvent.java b/java/api/src/main/java/prism/api/event/RenderWorldEvent.java new file mode 100644 index 0000000..2e3d089 --- /dev/null +++ b/java/api/src/main/java/prism/api/event/RenderWorldEvent.java @@ -0,0 +1,10 @@ +package prism.api.event; + +/** After the world was drawn, before the player's hand, every frame (camera-space GL state). */ +public final class RenderWorldEvent { + private final float partialTicks; + + public RenderWorldEvent(float partialTicks) { this.partialTicks = partialTicks; } + + public float partialTicks() { return partialTicks; } +} diff --git a/java/api/src/main/java/prism/api/event/TickEvent.java b/java/api/src/main/java/prism/api/event/TickEvent.java new file mode 100644 index 0000000..45e25c4 --- /dev/null +++ b/java/api/src/main/java/prism/api/event/TickEvent.java @@ -0,0 +1,8 @@ +package prism.api.event; + +/** Start of every client tick (20 per second), on the client thread. */ +public final class TickEvent { + public static final TickEvent INSTANCE = new TickEvent(); + + private TickEvent() {} +} diff --git a/java/build.gradle b/java/build.gradle index b0a7179..35571e5 100644 --- a/java/build.gradle +++ b/java/build.gradle @@ -2,7 +2,7 @@ subprojects { apply plugin: 'java' group = 'prism' - version = '0.1.0' + version = '0.2.0' repositories { mavenCentral() } tasks.withType(JavaCompile).configureEach { options.release = 8 diff --git a/java/core/build.gradle b/java/core/build.gradle index b72e83f..35e7abf 100644 --- a/java/core/build.gradle +++ b/java/core/build.gradle @@ -1,7 +1,16 @@ -// prism-core.jar: loaded into the game by the agent. Contains the API classes too. +// prism-core.jar: loaded into the game by the agent. Contains the API classes and a private +// copy of ASM (moved to prism.shadow.asm so it never clashes with a client's own ASM). +plugins { id 'com.gradleup.shadow' version '8.3.5' } base { archivesName = 'prism-core' } -dependencies { implementation project(':api') } -jar { - dependsOn ':api:jar' - from { project(':api').sourceSets.main.output } +dependencies { + implementation project(':api') + implementation 'org.ow2.asm:asm-tree:9.7.1' } +jar { enabled = false } +shadowJar { + archiveClassifier = '' + archiveVersion = '' + relocate 'org.objectweb.asm', 'prism.shadow.asm' + exclude 'module-info.class', 'META-INF/versions/**', 'META-INF/maven/**' +} +assemble.dependsOn shadowJar diff --git a/java/core/src/main/java/prism/core/DrawImpl.java b/java/core/src/main/java/prism/core/DrawImpl.java new file mode 100644 index 0000000..6d450ac --- /dev/null +++ b/java/core/src/main/java/prism/core/DrawImpl.java @@ -0,0 +1,106 @@ +package prism.core; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import prism.api.Draw; +import prism.api.Logger; + +/** Draw through the game's FontRenderer and Gui.drawRect, found by MCP or SRG names. */ +final class DrawImpl implements Draw { + private final String mappings; + private final ClassLoader loader; + private final Logger log = CoreLog.forSource("draw"); + + private Field fontField, fontHeight; + private Method drawText, textWidth, drawRect, scaledW, scaledH; + private Constructor scaled; + private boolean resolved, broken; + + DrawImpl(String mappings, ClassLoader loader) { + this.mappings = mappings; + this.loader = loader; + } + + private boolean srg() { return "srg".equals(mappings); } + + private synchronized boolean resolve() { + if (resolved || broken) return resolved; + try { + if ("notch".equals(mappings)) throw new UnsupportedOperationException("vanilla names not supported yet"); + Class mc = ClientThread.minecraftClass(); + fontField = mc.getDeclaredField(srg() ? "field_71466_p" : "fontRendererObj"); + fontField.setAccessible(true); + Class fr = fontField.getType(); + drawText = fr.getMethod(srg() ? "func_175063_a" : "drawStringWithShadow", String.class, float.class, float.class, int.class); + textWidth = fr.getMethod(srg() ? "func_78256_a" : "getStringWidth", String.class); + fontHeight = fr.getField(srg() ? "field_78288_b" : "FONT_HEIGHT"); + Class gui = Class.forName("net.minecraft.client.gui.Gui", false, loader); + drawRect = gui.getMethod(srg() ? "func_73734_a" : "drawRect", int.class, int.class, int.class, int.class, int.class); + Class sr = Class.forName("net.minecraft.client.gui.ScaledResolution", false, loader); + scaled = sr.getConstructor(mc); + scaledW = sr.getMethod(srg() ? "func_78326_a" : "getScaledWidth"); + scaledH = sr.getMethod(srg() ? "func_78328_b" : "getScaledHeight"); + resolved = true; + } catch (Throwable t) { + broken = true; + log.error("drawing not available", t); + } + return resolved; + } + + private Object font() throws IllegalAccessException { + return fontField.get(ClientThread.minecraft()); + } + + @Override + public int text(String text, float x, float y, int color) { + if (!resolve()) return 0; + try { + return (Integer) drawText.invoke(font(), text, x, y, color); + } catch (Exception e) { + return 0; + } + } + + @Override + public int textWidth(String text) { + if (!resolve()) return 0; + try { + return (Integer) textWidth.invoke(font(), text); + } catch (Exception e) { + return 0; + } + } + + @Override + public int fontHeight() { + if (!resolve()) return 9; + try { + return fontHeight.getInt(font()); + } catch (Exception e) { + return 9; + } + } + + @Override + public void rect(int x1, int y1, int x2, int y2, int color) { + if (!resolve()) return; + try { + drawRect.invoke(null, x1, y1, x2, y2, color); + } catch (Exception ignored) { + } + } + + /** GUI-scaled screen size {width, height}. */ + int[] screenSize() { + if (!resolve()) return new int[] {0, 0}; + try { + Object sr = scaled.newInstance(ClientThread.minecraft()); + return new int[] {(Integer) scaledW.invoke(sr), (Integer) scaledH.invoke(sr)}; + } catch (Exception e) { + return new int[] {0, 0}; + } + } +} diff --git a/java/core/src/main/java/prism/core/GameImpl.java b/java/core/src/main/java/prism/core/GameImpl.java index 1715acc..7eb3122 100644 --- a/java/core/src/main/java/prism/core/GameImpl.java +++ b/java/core/src/main/java/prism/core/GameImpl.java @@ -4,6 +4,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; +import prism.api.Draw; import prism.api.Game; import prism.api.Logger; @@ -18,11 +19,18 @@ final class GameImpl implements Game { private Constructor textComponent; private boolean resolved, broken; + private final DrawImpl draw; + GameImpl(String mappings, ClassLoader loader) { this.mappings = mappings; this.loader = loader; + this.draw = new DrawImpl(mappings, loader); } + @Override public Draw draw() { return draw; } + + DrawImpl drawImpl() { return draw; } + @Override public String mappings() { return mappings; } @Override public ClassLoader classLoader() { return loader; } diff --git a/java/core/src/main/java/prism/core/Native.java b/java/core/src/main/java/prism/core/Native.java index 44736f7..c4395a1 100644 --- a/java/core/src/main/java/prism/core/Native.java +++ b/java/core/src/main/java/prism/core/Native.java @@ -11,7 +11,7 @@ private Native() {} static native void unload0(); - static native boolean redefineClass0(Class target, byte[] classFile); + static native int retransform0(Class target, java.util.function.Function transformer); private static volatile boolean linked = true; @@ -33,12 +33,16 @@ public static void requestUnload() { } } - /** Replaces a loaded class's bytecode (JVMTI RedefineClasses). For the hook system. */ - public static boolean redefineClass(Class target, byte[] classFile) { + /** + * Retransforms a loaded class (JVMTI): its current bytes go through {@code transformer}, whose + * result becomes the class. {@code null} restores the class as the game loaded it. + * Returns 0, a JVMTI error code, or -1 when the agent can't do it. + */ + public static int retransform(Class target, java.util.function.Function transformer) { try { - return redefineClass0(target, classFile); + return retransform0(target, transformer); } catch (UnsatisfiedLinkError e) { - return false; + return -1; } } } diff --git a/java/core/src/main/java/prism/core/PluginManager.java b/java/core/src/main/java/prism/core/PluginManager.java index bf9f28b..ae5fd46 100644 --- a/java/core/src/main/java/prism/core/PluginManager.java +++ b/java/core/src/main/java/prism/core/PluginManager.java @@ -107,11 +107,11 @@ private void loop() { return; } List changed = scan(); - if (!changed.isEmpty()) game.chat("§d[Prism] §fReloaded " + String.join(", ", changed)); + if (!changed.isEmpty()) game.chat("§d[Prism] §f" + String.join(", ", changed)); } } - /** One pass over the folder. Returns the names of plugins that were (re)loaded. */ + /** One pass over the folder. Returns what changed, e.g. "Loaded Example" or "Reloaded Example". */ private synchronized List scan() { List done = new ArrayList<>(); Map now = new HashMap<>(); @@ -138,11 +138,12 @@ private synchronized List scan() { if (cur != null && cur.signature.equals(sig)) continue; boolean stable = firstScan || sig.equals(lastSeen.get(name)); if (!stable) continue; // still being written; look again next scan - if (cur != null) unload(name); + boolean reload = cur != null; + if (reload) unload(name); Loaded l = load(pluginsDir.resolve(name), sig); if (l != null) { loaded.put(name, l); - done.add(l.info.name()); + done.add(firstScan ? l.info.name() : (reload ? "Reloaded " : "Loaded ") + l.info.name()); } } lastSeen.clear(); diff --git a/java/core/src/main/java/prism/core/Prism.java b/java/core/src/main/java/prism/core/Prism.java index 2da081d..c62aaa2 100644 --- a/java/core/src/main/java/prism/core/Prism.java +++ b/java/core/src/main/java/prism/core/Prism.java @@ -6,17 +6,20 @@ import prism.api.Logger; import prism.api.event.ShutdownEvent; +import prism.core.hook.GameHooks; +import prism.core.hook.Hooks; /** * Started by the native agent once the game's classes are loaded. * Layout of the Prism folder (home): bin/ (agent + core), plugins/, data/, logs/, cache/. */ public final class Prism { - public static final String VERSION = "0.1.0"; + public static final String VERSION = "0.2.0"; private static final AtomicBoolean running = new AtomicBoolean(); private static Bus bus; private static PluginManager plugins; + private static Hooks hooks; private static Thread shutdownHook; private Prism() {} @@ -42,6 +45,12 @@ public static String start(String home, String mappings, Class minecraft) { Tasks.start(); bus = new Bus(); GameImpl game = new GameImpl(mappings, minecraft.getClassLoader()); + hooks = new Hooks(minecraft.getClassLoader(), mappings, CoreLog.forSource("hooks")); + Bus b = bus; + GameHooks.register(hooks, new GameHooks.Poster() { + public E post(E event) { return b.post(event); } + }, pt -> game.drawImpl().screenSize()); + log.info("hooks placed: " + hooks.install()); plugins = new PluginManager(dir, Prism.class.getClassLoader(), bus, game); plugins.start(); shutdownHook = new Thread(Prism::stop, "Prism Shutdown"); @@ -66,6 +75,12 @@ public static void stop() { } catch (Throwable t) { log.error("stop failed", t); } + try { + if (hooks != null) hooks.uninstall(); + } catch (Throwable t) { + log.error("removing hooks failed", t); + } + hooks = null; Tasks.stop(); if (shutdownHook != null && Thread.currentThread() != shutdownHook) { try { diff --git a/java/core/src/main/java/prism/core/hook/GameHooks.java b/java/core/src/main/java/prism/core/hook/GameHooks.java new file mode 100644 index 0000000..f28f92e --- /dev/null +++ b/java/core/src/main/java/prism/core/hook/GameHooks.java @@ -0,0 +1,51 @@ +package prism.core.hook; + +import java.util.function.Function; + +import prism.api.event.KeyEvent; +import prism.api.event.MouseButtonEvent; +import prism.api.event.RenderOverlayEvent; +import prism.api.event.RenderWorldEvent; +import prism.api.event.TickEvent; + +/** The hooks behind Prism's events. Names: MCP (Lunar) and SRG (Forge). */ +public final class GameHooks { + private GameHooks() {} + + public interface Poster { + E post(E event); + } + + public static void register(Hooks hooks, Poster bus, Function screenSize) { + hooks.add(Hook.head("tick", "net/minecraft/client/Minecraft", "runTick", "func_71407_l", "()V", + new int[0], false, args -> { + bus.post(TickEvent.INSTANCE); + return false; + })); + + hooks.add(Hook.tail("overlay", "net/minecraft/client/gui/GuiIngame", "renderGameOverlay", "func_175180_a", "(F)V", + new int[] {1}, args -> { + float pt = (Float) args[0]; + int[] size = screenSize.apply(pt); + bus.post(new RenderOverlayEvent(pt, size[0], size[1])); + return false; + })); + + hooks.add(Hook.beforeCall("world", "net/minecraft/client/renderer/EntityRenderer", + "renderWorldPass", "func_175068_a", "(IFJ)V", + "net/minecraft/client/renderer/EntityRenderer", "renderHand", "func_78476_b", "(FI)V", + new int[] {2}, args -> { + bus.post(new RenderWorldEvent((Float) args[0])); + return false; + })); + + // all keybind input while playing goes through here; mouse buttons come as button - 100 + hooks.add(Hook.head("input", "net/minecraft/client/settings/KeyBinding", "setKeyBindState", "func_74510_a", "(IZ)V", + new int[] {0, 1}, true, args -> { + int code = (Integer) args[0]; + boolean pressed = (Boolean) args[1]; + if (code < 0) return bus.post(new MouseButtonEvent(code + 100, pressed)).isCancelled(); + return bus.post(new KeyEvent(code, pressed)).isCancelled(); + })); + } +} diff --git a/java/core/src/main/java/prism/core/hook/Hook.java b/java/core/src/main/java/prism/core/hook/Hook.java new file mode 100644 index 0000000..5db7adc --- /dev/null +++ b/java/core/src/main/java/prism/core/hook/Hook.java @@ -0,0 +1,68 @@ +package prism.core.hook; + +import java.util.function.Predicate; + +/** + * One place in a game method where Prism calls in. The injected code only uses JDK classes: + * {@code ((Predicate) System.getProperties().get(key)).test(new Object[]{args...})}, and for a + * cancelable hook a {@code true} result returns from the method. That way the game's class + * loader never has to see Prism's classes. + */ +public final class Hook { + public enum At { HEAD, TAIL, BEFORE_CALL } + + final String id; + final String owner; // internal name, e.g. net/minecraft/client/Minecraft + final String[] names; // method name per mapping: {mcp, srg} + final String desc; + final At at; + final String callOwner; // BEFORE_CALL: the called method + final String[] callNames; + final String callDesc; + final int[] argLocals; // local variable slots passed to the handler + final boolean cancelable; + final Predicate handler; + + private Hook(String id, String owner, String[] names, String desc, At at, String callOwner, + String[] callNames, String callDesc, int[] argLocals, boolean cancelable, + Predicate handler) { + this.id = id; + this.owner = owner; + this.names = names; + this.desc = desc; + this.at = at; + this.callOwner = callOwner; + this.callNames = callNames; + this.callDesc = callDesc; + this.argLocals = argLocals; + this.cancelable = cancelable; + this.handler = handler; + } + + static Hook head(String id, String owner, String mcp, String srg, String desc, int[] args, + boolean cancelable, Predicate handler) { + return new Hook(id, owner, new String[] {mcp, srg}, desc, At.HEAD, null, null, null, args, cancelable, handler); + } + + static Hook tail(String id, String owner, String mcp, String srg, String desc, int[] args, + Predicate handler) { + return new Hook(id, owner, new String[] {mcp, srg}, desc, At.TAIL, null, null, null, args, false, handler); + } + + static Hook beforeCall(String id, String owner, String mcp, String srg, String desc, + String callOwner, String callMcp, String callSrg, String callDesc, int[] args, + Predicate handler) { + return new Hook(id, owner, new String[] {mcp, srg}, desc, At.BEFORE_CALL, callOwner, + new String[] {callMcp, callSrg}, callDesc, args, false, handler); + } + + String key() { return "prism.hook." + id; } + + String name(String mappings) { return pick(names, mappings); } + + String callName(String mappings) { return pick(callNames, mappings); } + + private static String pick(String[] n, String mappings) { + return "srg".equals(mappings) ? n[1] : n[0]; + } +} diff --git a/java/core/src/main/java/prism/core/hook/Hooks.java b/java/core/src/main/java/prism/core/hook/Hooks.java new file mode 100644 index 0000000..363ae13 --- /dev/null +++ b/java/core/src/main/java/prism/core/hook/Hooks.java @@ -0,0 +1,103 @@ +package prism.core.hook; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +import prism.api.Logger; +import prism.core.Native; + +/** + * Places hooks into game classes when Prism starts and takes them out again when it stops. + * Hooks need JVMTI retransformation (the agent turns it on). Each class is patched in one go, + * starting from the bytes the game is running, so other patches (Lunar's own) are kept. + */ +public final class Hooks { + private static final Predicate NOOP = args -> false; + + private final ClassLoader gameLoader; + private final String mappings; + private final Logger log; + private final List hooks = new ArrayList<>(); + private final List> patched = new ArrayList<>(); + + public Hooks(ClassLoader gameLoader, String mappings, Logger log) { + this.gameLoader = gameLoader; + this.mappings = mappings; + this.log = log; + } + + public void add(Hook h) { hooks.add(h); } + + /** Patches every class that has hooks. Returns how many hooks were placed. */ + public int install() { + if ("notch".equals(mappings)) { + log.warn("hooks: vanilla (notch) names aren't supported yet"); + return 0; + } + Map> byClass = new LinkedHashMap<>(); + for (Hook h : hooks) { + System.getProperties().put(h.key(), h.handler); // before any patched code can run + byClass.computeIfAbsent(h.owner, k -> new ArrayList<>()).add(h); + } + int placed = 0; + for (Map.Entry> e : byClass.entrySet()) { + List list = e.getValue(); + Class cls; + try { + cls = Class.forName(e.getKey().replace('/', '.'), false, gameLoader); + } catch (Throwable t) { + for (Hook h : list) log.warn("hook " + h.id + ": class " + e.getKey() + " not found"); + continue; + } + Patcher.Result[] result = new Patcher.Result[1]; + Throwable[] failure = new Throwable[1]; + int code = Native.retransform(cls, bytes -> { + try { + result[0] = Patcher.patch(bytes, list, mappings); + return result[0].bytes; + } catch (Throwable t) { + failure[0] = t; + return null; + } + }); + if (failure[0] != null) log.error("hooks: patching " + e.getKey() + " failed", failure[0]); + if (code != 0 || result[0] == null) { + for (Hook h : list) log.warn("hook " + h.id + ": not placed (JVMTI " + code + ")"); + continue; + } + if (result[0].bytes != null) patched.add(cls); + for (int i = 0; i < list.size(); i++) { + String problem = result[0].problems[i]; + if (problem == null) { + placed++; + log.info("hook " + list.get(i).id + ": ok"); + } else { + log.warn("hook " + list.get(i).id + ": " + problem); + } + } + } + return placed; + } + + /** Puts every patched class back the way the game had it. */ + public void uninstall() { + boolean allRestored = true; + for (Class cls : patched) { + int code = Native.retransform(cls, null); + if (code != 0) { + allRestored = false; + log.warn("hooks: couldn't restore " + cls.getName() + " (JVMTI " + code + ")"); + } + } + patched.clear(); + for (Hook h : hooks) { + // a class that couldn't be restored still calls in: leave a no-op there, never null + if (allRestored) System.getProperties().remove(h.key()); + else System.getProperties().put(h.key(), NOOP); + } + log.info("hooks removed"); + } +} diff --git a/java/core/src/main/java/prism/core/hook/Patcher.java b/java/core/src/main/java/prism/core/hook/Patcher.java new file mode 100644 index 0000000..cf617af --- /dev/null +++ b/java/core/src/main/java/prism/core/hook/Patcher.java @@ -0,0 +1,195 @@ +package prism.core.hook; + +import java.util.List; + +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FrameNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.IntInsnNode; +import org.objectweb.asm.tree.JumpInsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.LdcInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TypeInsnNode; +import org.objectweb.asm.tree.VarInsnNode; + +/** Adds hook calls to a class's bytecode. Reports per hook whether it was placed. */ +final class Patcher { + /** Result per hook, same order as the input list: null = placed, else why not. */ + static final class Result { + byte[] bytes; + String[] problems; + } + + static Result patch(byte[] original, List hooks, String mappings) { + ClassNode cn = new ClassNode(); + new ClassReader(original).accept(cn, ClassReader.EXPAND_FRAMES); + Result r = new Result(); + r.problems = new String[hooks.size()]; + boolean changed = false; + for (int i = 0; i < hooks.size(); i++) { + Hook h = hooks.get(i); + MethodNode m = find(cn, h.name(mappings), h.desc); + if (m == null) { + r.problems[i] = "method " + h.name(mappings) + h.desc + " not found"; + continue; + } + if (h.cancelable && (h.at != Hook.At.HEAD || Type.getReturnType(m.desc) != Type.VOID_TYPE)) { + r.problems[i] = "cancelable hooks must be at the head of a void method"; + continue; + } + int placed = place(m, h, mappings); + if (placed == 0) r.problems[i] = "no injection point in " + m.name; + else changed = true; + } + if (changed) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + cn.accept(cw); + r.bytes = cw.toByteArray(); + } + return r; + } + + private static MethodNode find(ClassNode cn, String name, String desc) { + for (MethodNode m : cn.methods) if (m.name.equals(name) && m.desc.equals(desc)) return m; + return null; + } + + private static int place(MethodNode m, Hook h, String mappings) { + int count = 0; + switch (h.at) { + case HEAD: { + AbstractInsnNode first = m.instructions.getFirst(); + m.instructions.insertBefore(first, call(m, h, first)); + count = 1; + break; + } + case TAIL: + for (AbstractInsnNode n : m.instructions.toArray()) { + int op = n.getOpcode(); + if (op >= Opcodes.IRETURN && op <= Opcodes.RETURN) { + m.instructions.insertBefore(n, call(m, h, null)); + count++; + } + } + break; + case BEFORE_CALL: + String callName = h.callName(mappings); + for (AbstractInsnNode n : m.instructions.toArray()) { + if (n instanceof MethodInsnNode) { + MethodInsnNode mi = (MethodInsnNode) n; + if (mi.owner.equals(h.callOwner) && mi.name.equals(callName) && mi.desc.equals(h.callDesc)) { + m.instructions.insertBefore(n, call(m, h, null)); + count++; + } + } + } + break; + } + return count; + } + + /** + * ((Predicate) System.getProperties().get(key)).test(new Object[]{...}) + * then either pop, or (cancelable, HEAD only) "if true: return". + */ + private static InsnList call(MethodNode m, Hook h, AbstractInsnNode next) { + InsnList l = new InsnList(); + l.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "getProperties", "()Ljava/util/Properties;", false)); + l.add(new LdcInsnNode(h.key())); + l.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/util/Properties", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false)); + l.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/util/function/Predicate")); + l.add(new IntInsnNode(Opcodes.BIPUSH, h.argLocals.length)); + l.add(new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object")); + Type[] params = Type.getArgumentTypes(m.desc); + boolean isStatic = (m.access & Opcodes.ACC_STATIC) != 0; + for (int i = 0; i < h.argLocals.length; i++) { + int slot = h.argLocals[i]; + Type t = typeOfSlot(params, isStatic, slot); + l.add(new InsnNode(Opcodes.DUP)); + l.add(new IntInsnNode(Opcodes.BIPUSH, i)); + l.add(new VarInsnNode(t.getOpcode(Opcodes.ILOAD), slot)); + box(l, t); + l.add(new InsnNode(Opcodes.AASTORE)); + } + l.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, "java/util/function/Predicate", "test", "(Ljava/lang/Object;)Z", true)); + if (!h.cancelable) { + l.add(new InsnNode(Opcodes.POP)); + return l; + } + // if (!result) jump over the return + LabelNode resume = existingLabelWithFrame(next); + boolean needFrame = resume == null; + if (needFrame) resume = new LabelNode(); + l.add(new JumpInsnNode(Opcodes.IFEQ, resume)); + l.add(new InsnNode(Opcodes.RETURN)); // cancelable hooks are only placed on void methods + if (needFrame) { + l.add(resume); + l.add(new FrameNode(Opcodes.F_NEW, 0, null, 0, null)); + FrameNode f = (FrameNode) l.getLast(); + f.local = initialLocals(m, isStatic, h.owner); + f.stack = new java.util.ArrayList<>(); + } + return l; + } + + /** The method starts with a label that already has a frame: jump there instead of adding one. */ + private static LabelNode existingLabelWithFrame(AbstractInsnNode first) { + AbstractInsnNode n = first; + LabelNode label = null; + while (n != null && (n instanceof LabelNode || n.getType() == AbstractInsnNode.LINE)) { + if (n instanceof LabelNode && label == null) label = (LabelNode) n; + n = n.getNext(); + } + return label != null && n instanceof FrameNode ? label : null; + } + + private static List initialLocals(MethodNode m, boolean isStatic, String owner) { + List locals = new java.util.ArrayList<>(); + if (!isStatic) locals.add(owner); + for (Type t : Type.getArgumentTypes(m.desc)) { + switch (t.getSort()) { + case Type.BOOLEAN: case Type.BYTE: case Type.CHAR: case Type.SHORT: case Type.INT: + locals.add(Opcodes.INTEGER); break; + case Type.FLOAT: locals.add(Opcodes.FLOAT); break; + case Type.LONG: locals.add(Opcodes.LONG); break; + case Type.DOUBLE: locals.add(Opcodes.DOUBLE); break; + default: locals.add(t.getInternalName()); + } + } + return locals; + } + + private static Type typeOfSlot(Type[] params, boolean isStatic, int slot) { + int s = isStatic ? 0 : 1; + if (!isStatic && slot == 0) return Type.getObjectType("java/lang/Object"); + for (Type t : params) { + if (s == slot) return t; + s += t.getSize(); + } + throw new IllegalArgumentException("slot " + slot + " is not a parameter"); + } + + private static void box(InsnList l, Type t) { + String box; + switch (t.getSort()) { + case Type.BOOLEAN: box = "java/lang/Boolean"; break; + case Type.BYTE: box = "java/lang/Byte"; break; + case Type.CHAR: box = "java/lang/Character"; break; + case Type.SHORT: box = "java/lang/Short"; break; + case Type.INT: box = "java/lang/Integer"; break; + case Type.FLOAT: box = "java/lang/Float"; break; + case Type.LONG: box = "java/lang/Long"; break; + case Type.DOUBLE: box = "java/lang/Double"; break; + default: return; + } + l.add(new MethodInsnNode(Opcodes.INVOKESTATIC, box, "valueOf", "(" + t.getDescriptor() + ")L" + box + ";", false)); + } +} diff --git a/java/example-plugin/build.gradle b/java/example-plugin/build.gradle index 82ecee8..3fc5b52 100644 --- a/java/example-plugin/build.gradle +++ b/java/example-plugin/build.gradle @@ -1,3 +1,4 @@ // A minimal plugin. Drop the built jar into the Prism plugins folder. base { archivesName = 'example-plugin' } +jar { archiveVersion = '' } dependencies { compileOnly project(':api') } diff --git a/java/example-plugin/src/main/java/example/ExamplePlugin.java b/java/example-plugin/src/main/java/example/ExamplePlugin.java index ff71e3a..ef6a067 100644 --- a/java/example-plugin/src/main/java/example/ExamplePlugin.java +++ b/java/example-plugin/src/main/java/example/ExamplePlugin.java @@ -1,15 +1,27 @@ package example; +import prism.api.Draw; import prism.api.Plugin; import prism.api.PluginContext; -import prism.api.event.PluginEnableEvent; +import prism.api.event.KeyEvent; +import prism.api.event.RenderOverlayEvent; +import prism.api.event.TickEvent; -/** Says hello in chat and logs when other plugins load. */ +/** Says hello, counts ticks, draws a small label on the HUD and logs key presses. */ public class ExamplePlugin implements Plugin { + private int ticks; + @Override public void onEnable(PluginContext ctx) { - ctx.log().info("hello from " + ctx.info()); ctx.game().chat("§d[Example] §fHello!"); - ctx.events().on(PluginEnableEvent.class, e -> ctx.log().info("saw " + e.plugin() + " load")); + ctx.events().on(TickEvent.class, e -> ticks++); + ctx.events().on(RenderOverlayEvent.class, e -> { + Draw d = ctx.game().draw(); + String label = "§dPrism §7" + (ticks / 20) + "s"; + d.text(label, e.width() - d.textWidth(label) - 4, e.height() - d.fontHeight() - 4, 0xFFFFFFFF); + }); + ctx.events().on(KeyEvent.class, e -> { + if (e.pressed()) ctx.log().info("key " + e.key()); + }); } } diff --git a/java/settings.gradle b/java/settings.gradle index cfaf91a..d0707ae 100644 --- a/java/settings.gradle +++ b/java/settings.gradle @@ -1,2 +1,3 @@ +pluginManagement { repositories { gradlePluginPortal(); mavenCentral() } } rootProject.name = 'prism' include 'api', 'core', 'example-plugin' diff --git a/native/agent/src/boot.rs b/native/agent/src/boot.rs index a087cca..e4133cc 100644 --- a/native/agent/src/boot.rs +++ b/native/agent/src/boot.rs @@ -130,23 +130,91 @@ extern "system" fn n_unload(_: *mut JNIEnv, _: jclass) { UNLOAD.store(true, Ordering::SeqCst); } -extern "system" fn n_redefine( +// The class being retransformed by Native.retransform0 on this thread, and its transformer. +thread_local! { + static ACTIVE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Native.retransform0(Class target, Function transformer): retransforms `target`, +/// passing its current bytes through `transformer` (null = back to the original class). +/// Returns 0 or the JVMTI error code (-1 when JVMTI is not available). +extern "system" fn n_retransform( env: *mut JNIEnv, _: jclass, target: jclass, - bytes: jbyteArray, -) -> jboolean { + transformer: jobject, +) -> jint { let p = JVMTI.load(Ordering::SeqCst); - if p.is_null() || target.is_null() || bytes.is_null() { - return JNI_FALSE; + if p.is_null() || target.is_null() { + return -1; } let ti: Jvmti = unsafe { std::mem::transmute(p) }; - let data = Env(env).byte_array(bytes); - let r = ti.redefine(target, &data); + let _ = env; + ACTIVE.with(|a| a.set(Some((target as usize, transformer as usize)))); + ti.class_file_load_hook_events(true); + let r = ti.retransform(target); + ti.class_file_load_hook_events(false); + ACTIVE.with(|a| a.set(None)); if r != 0 { - log(&format!("RedefineClasses failed: JVMTI error {r}")); + log(&format!("RetransformClasses failed: JVMTI error {r}")); + } + r +} + +/// ClassFileLoadHook: only acts on the class Native.retransform0 is working on, on its thread. +extern "system" fn class_file_load_hook( + _jvmti: *mut c_void, + jni: *mut JNIEnv, + class_being_redefined: jclass, + _loader: jobject, + _name: *const std::ffi::c_char, + _pd: jobject, + len: jint, + data: *const u8, + new_len: *mut jint, + new_data: *mut *mut u8, +) { + let Some((target, transformer)) = ACTIVE.with(|a| a.get()) else { + return; + }; + let (target, transformer) = (target as jclass, transformer as jobject); + if class_being_redefined.is_null() || transformer.is_null() || jni.is_null() || data.is_null() { + return; + } + let env = Env(jni); + if !env.same_object(class_being_redefined, target) { + return; + } + let p = JVMTI.load(Ordering::SeqCst); + if p.is_null() { + return; + } + let ti: Jvmti = unsafe { std::mem::transmute(p) }; + if !env.push_frame(16) { + return; + } + let result = (|| -> Result>, String> { + let input = env.new_byte_array(unsafe { std::slice::from_raw_parts(data, len as usize) }); + let function = env.find_class("java/util/function/Function")?; + let apply = env.method(function, "apply", "(Ljava/lang/Object;)Ljava/lang/Object;")?; + let out = env.call_object(transformer, apply, &[jvalue { l: input }])?; + Ok((!out.is_null()).then(|| env.byte_array(out))) + })(); + env.pop_frame(); + match result { + Ok(Some(bytes)) => { + let mem = ti.allocate(bytes.len()); + if !mem.is_null() { + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), mem, bytes.len()); + *new_len = bytes.len() as jint; + *new_data = mem; + } + } + } + Ok(None) => {} + Err(e) => log(&format!("transformer failed: {e}")), } - (r == 0) as jboolean } // ------------------------------------------------------------------ the agent thread @@ -165,8 +233,11 @@ pub fn run(vm: *mut JavaVM, paths: Paths, extra_unload: impl Fn() -> bool) { }; let ti = Jvmti::get(vm); if let Some(t) = ti { - let redefine = t.enable_redefine(); - log(&format!("JVMTI ready (redefine classes: {redefine})")); + let retransform = t.enable_retransform(); + if retransform { + t.set_class_file_load_hook(class_file_load_hook); + } + log(&format!("JVMTI ready (retransform classes: {retransform})")); JVMTI.store( unsafe { std::mem::transmute::(t) }, Ordering::SeqCst, @@ -242,9 +313,9 @@ fn start_core(env: Env, paths: &Paths, game: &Game) -> Result { ("log0", "(Ljava/lang/String;)V", n_log as *mut c_void), ("unload0", "()V", n_unload as *mut c_void), ( - "redefineClass0", - "(Ljava/lang/Class;[B)Z", - n_redefine as *mut c_void, + "retransform0", + "(Ljava/lang/Class;Ljava/util/function/Function;)I", + n_retransform as *mut c_void, ), ], )?; diff --git a/native/agent/src/jvm.rs b/native/agent/src/jvm.rs index 0c721e8..543535c 100644 --- a/native/agent/src/jvm.rs +++ b/native/agent/src/jvm.rs @@ -216,6 +216,25 @@ impl Env { jni!(self, NewObjectArray, len, cls, first) } + pub fn new_byte_array(&self, data: &[u8]) -> jbyteArray { + let a = jni!(self, NewByteArray, data.len() as jsize); + if !a.is_null() { + jni!( + self, + SetByteArrayRegion, + a, + 0, + data.len() as jsize, + data.as_ptr() as *const jbyte + ); + } + a + } + + pub fn same_object(&self, a: jobject, b: jobject) -> bool { + jni!(self, IsSameObject, a, b) != JNI_FALSE + } + pub fn byte_array(&self, a: jbyteArray) -> Vec { let len = self.array_len(a) as usize; let mut out = vec![0u8; len]; @@ -319,12 +338,19 @@ const JVMTI_VERSION_1_2: jint = 0x3001_0200; #[derive(Clone, Copy)] pub struct Jvmti(*mut *const *const c_void); -#[repr(C)] -struct ClassDefinition { - klass: jclass, - class_byte_count: jint, - class_bytes: *const u8, -} +/// jvmtiEventClassFileLoadHook +pub type ClassFileLoadHook = extern "system" fn( + jvmti: *mut c_void, + jni: *mut JNIEnv, + class_being_redefined: jclass, + loader: jobject, + name: *const c_char, + protection_domain: jobject, + class_data_len: jint, + class_data: *const u8, + new_class_data_len: *mut jint, + new_class_data: *mut *mut u8, +); impl Jvmti { pub fn get(vm: *mut JavaVM) -> Option { @@ -343,29 +369,61 @@ impl Jvmti { f(*self, p); } - /// Asks for can_redefine_classes (bit 9 of the capabilities). Returns whether it was granted. - pub fn enable_redefine(&self) -> bool { + /// Asks for the capabilities the hook system needs: can_retransform_classes (bit 37) and + /// can_generate_all_class_hook_events (bit 26). Returns whether they were granted. + pub fn enable_retransform(&self) -> bool { let mut caps = [0u32; 4]; let potential: extern "system" fn(Jvmti, *mut u32) -> jint = unsafe { std::mem::transmute(self.slot(140)) }; - if potential(*self, caps.as_mut_ptr()) != 0 || caps[0] & (1 << 9) == 0 { + let want = [1u32 << 26, 1u32 << (37 - 32), 0, 0]; + if potential(*self, caps.as_mut_ptr()) != 0 + || caps[0] & want[0] == 0 + || caps[1] & want[1] == 0 + { return false; } - let want = [1u32 << 9, 0, 0, 0]; let add: extern "system" fn(Jvmti, *const u32) -> jint = unsafe { std::mem::transmute(self.slot(142)) }; add(*self, want.as_ptr()) == 0 } - pub fn redefine(&self, cls: jclass, bytes: &[u8]) -> jint { - let def = ClassDefinition { - klass: cls, - class_byte_count: bytes.len() as jint, - class_bytes: bytes.as_ptr(), - }; - let f: extern "system" fn(Jvmti, jint, *const ClassDefinition) -> jint = - unsafe { std::mem::transmute(self.slot(87)) }; - f(*self, 1, &def) + /// Installs `hook` as the ClassFileLoadHook callback (event 54, slot 4 of the callbacks struct). + pub fn set_class_file_load_hook(&self, hook: ClassFileLoadHook) -> jint { + let callbacks: [*const c_void; 5] = [ + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + std::ptr::null(), + hook as *const c_void, + ]; + let f: extern "system" fn(Jvmti, *const [*const c_void; 5], jint) -> jint = + unsafe { std::mem::transmute(self.slot(122)) }; + f(*self, &callbacks, std::mem::size_of_val(&callbacks) as jint) + } + + /// Turns ClassFileLoadHook events on or off (only on while Prism retransforms a class). + pub fn class_file_load_hook_events(&self, on: bool) -> jint { + // SetEventNotificationMode is variadic in C + let f: unsafe extern "C" fn(Jvmti, jint, jint, jobject, ...) -> jint = + unsafe { std::mem::transmute(self.slot(2)) }; + unsafe { f(*self, on as jint, 54, null_mut()) } + } + + pub fn retransform(&self, cls: jclass) -> jint { + let f: extern "system" fn(Jvmti, jint, *const jclass) -> jint = + unsafe { std::mem::transmute(self.slot(152)) }; + f(*self, 1, &cls) + } + + /// Memory the JVM takes ownership of (for new class bytes). + pub fn allocate(&self, len: usize) -> *mut u8 { + let mut p: *mut u8 = null_mut(); + let f: extern "system" fn(Jvmti, i64, *mut *mut u8) -> jint = + unsafe { std::mem::transmute(self.slot(46)) }; + if f(*self, len as i64, &mut p) != 0 { + return null_mut(); + } + p } /// Calls `visit` with the loader of every loaded class whose signature is in `sigs`. diff --git a/tests/fake-game/src/net/minecraft/client/Minecraft.java b/tests/fake-game/src/net/minecraft/client/Minecraft.java index 1aea2f3..12e5434 100644 --- a/tests/fake-game/src/net/minecraft/client/Minecraft.java +++ b/tests/fake-game/src/net/minecraft/client/Minecraft.java @@ -2,16 +2,25 @@ import java.util.ArrayDeque; import java.util.Queue; +import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiIngame; +import net.minecraft.client.renderer.EntityRenderer; +import net.minecraft.client.settings.KeyBinding; /** Stand-in with the same names Lunar uses (MCP), for testing the agent and core. */ public class Minecraft { private static Minecraft theMinecraft; public GuiIngame ingameGUI; + public FontRenderer fontRendererObj = new FontRenderer(); + public EntityRenderer entityRenderer = new EntityRenderer(); + public static int ticks; + private static int frame; private final Queue scheduledTasks = new ArrayDeque<>(); public static Minecraft getMinecraft() { return theMinecraft; } + public void runTick() { ticks++; } + public Object addScheduledTask(Runnable r) { synchronized (scheduledTasks) { scheduledTasks.add(r); } return null; @@ -22,11 +31,20 @@ public static void run() throws Exception { theMinecraft = new Minecraft(); theMinecraft.ingameGUI = new GuiIngame(); System.out.println("GAME: started"); - while (true) { // game loop, 50 fps + while (true) { // game loop, 50 fps, a tick every other frame synchronized (theMinecraft.scheduledTasks) { Runnable r; while ((r = theMinecraft.scheduledTasks.poll()) != null) r.run(); } + if (frame++ % 2 == 0) theMinecraft.runTick(); + theMinecraft.entityRenderer.renderWorldPass(2, 0.5f, System.nanoTime()); + theMinecraft.ingameGUI.renderGameOverlay(0.5f); + if (new java.io.File(System.getProperty("fake.keys", "/nonexistent")).exists()) { + new java.io.File(System.getProperty("fake.keys")).delete(); + KeyBinding.setKeyBindState(30, true); // A + KeyBinding.setKeyBindState(31, true); // S + KeyBinding.setKeyBindState(-100, true); // left mouse + } Thread.sleep(20); } } diff --git a/tests/fake-game/src/net/minecraft/client/gui/FontRenderer.java b/tests/fake-game/src/net/minecraft/client/gui/FontRenderer.java new file mode 100644 index 0000000..7b974a4 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/gui/FontRenderer.java @@ -0,0 +1,10 @@ +package net.minecraft.client.gui; +public class FontRenderer { + public int FONT_HEIGHT = 9; + public static int draws; + public int drawStringWithShadow(String text, float x, float y, int color) { + if (draws++ == 0) System.out.println("DRAW text '" + text + "' at " + (int) x + "," + (int) y); + return text.length() * 6; + } + public int getStringWidth(String text) { return text.length() * 6; } +} diff --git a/tests/fake-game/src/net/minecraft/client/gui/Gui.java b/tests/fake-game/src/net/minecraft/client/gui/Gui.java new file mode 100644 index 0000000..51625fe --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/gui/Gui.java @@ -0,0 +1,5 @@ +package net.minecraft.client.gui; +public class Gui { + public static int rects; + public static void drawRect(int l, int t, int r, int b, int color) { rects++; } +} diff --git a/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java b/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java index e6bee9b..65ab4ee 100644 --- a/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java +++ b/tests/fake-game/src/net/minecraft/client/gui/GuiIngame.java @@ -2,4 +2,7 @@ public class GuiIngame { private final GuiNewChat chat = new GuiNewChat(); public GuiNewChat getChatGUI() { return chat; } + public void renderGameOverlay(float partialTicks) { + if (partialTicks < 0) return; // a second return, to check TAIL hooks every exit + } } diff --git a/tests/fake-game/src/net/minecraft/client/gui/ScaledResolution.java b/tests/fake-game/src/net/minecraft/client/gui/ScaledResolution.java new file mode 100644 index 0000000..da52853 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/gui/ScaledResolution.java @@ -0,0 +1,7 @@ +package net.minecraft.client.gui; +import net.minecraft.client.Minecraft; +public class ScaledResolution { + public ScaledResolution(Minecraft mc) {} + public int getScaledWidth() { return 427; } + public int getScaledHeight() { return 240; } +} diff --git a/tests/fake-game/src/net/minecraft/client/renderer/EntityRenderer.java b/tests/fake-game/src/net/minecraft/client/renderer/EntityRenderer.java new file mode 100644 index 0000000..351bd8f --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/renderer/EntityRenderer.java @@ -0,0 +1,11 @@ +package net.minecraft.client.renderer; +public class EntityRenderer { + public boolean renderHand = true; + public void renderWorldPass(int pass, float partialTicks, long finishTimeNano) { + long x = finishTimeNano + pass; + if (this.renderHand) { + this.renderHand(partialTicks, pass); + } + } + private void renderHand(float partialTicks, int pass) {} +} diff --git a/tests/fake-game/src/net/minecraft/client/settings/KeyBinding.java b/tests/fake-game/src/net/minecraft/client/settings/KeyBinding.java new file mode 100644 index 0000000..24bed95 --- /dev/null +++ b/tests/fake-game/src/net/minecraft/client/settings/KeyBinding.java @@ -0,0 +1,6 @@ +package net.minecraft.client.settings; +public class KeyBinding { + public static void setKeyBindState(int keyCode, boolean pressed) { + System.out.println("GAME KEY " + keyCode + " " + pressed); + } +} diff --git a/tests/hook-plugin/plugin.properties b/tests/hook-plugin/plugin.properties new file mode 100644 index 0000000..d34eb7e --- /dev/null +++ b/tests/hook-plugin/plugin.properties @@ -0,0 +1,4 @@ +id=hooktest +name=HookTest +version=1 +main=hooktest.HookTestPlugin diff --git a/tests/hook-plugin/src/hooktest/HookTestPlugin.java b/tests/hook-plugin/src/hooktest/HookTestPlugin.java new file mode 100644 index 0000000..db4b81c --- /dev/null +++ b/tests/hook-plugin/src/hooktest/HookTestPlugin.java @@ -0,0 +1,31 @@ +package hooktest; + +import prism.api.Plugin; +import prism.api.PluginContext; +import prism.api.event.KeyEvent; +import prism.api.event.MouseButtonEvent; +import prism.api.event.RenderOverlayEvent; +import prism.api.event.RenderWorldEvent; +import prism.api.event.TickEvent; + +/** Test plugin: counts every hook event, blocks key A, reports once a second. */ +public class HookTestPlugin implements Plugin { + int ticks, overlays, worlds; + + @Override + public void onEnable(PluginContext ctx) { + ctx.events().on(TickEvent.class, e -> ticks++); + ctx.events().on(RenderOverlayEvent.class, e -> { + overlays++; + ctx.game().draw().rect(0, 0, 10, 10, 0x80000000); + if (overlays == 1) ctx.log().info("overlay size " + e.width() + "x" + e.height() + " pt " + e.partialTicks()); + }); + ctx.events().on(RenderWorldEvent.class, e -> worlds++); + ctx.events().on(KeyEvent.class, e -> { + ctx.log().info("key event " + e.key() + " " + e.pressed()); + if (e.key() == 30) e.cancel(); + }); + ctx.events().on(MouseButtonEvent.class, e -> ctx.log().info("mouse event " + e.button() + " " + e.pressed())); + ctx.scheduler().every(1000, () -> ctx.log().info("counts tick=" + ticks + " overlay=" + overlays + " world=" + worlds)); + } +} diff --git a/tests/run.sh b/tests/run.sh index f1ec0ce..dce33ab 100755 --- a/tests/run.sh +++ b/tests/run.sh @@ -3,7 +3,7 @@ # agent loaded with jcmd, then we check load, chat, hot reload, removal and unload. set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -W="$(mktemp -d)"; trap 'kill $GAME 2>/dev/null || true; rm -rf "$W"' EXIT +GAME=""; W="$(mktemp -d)"; trap 'kill $GAME 2>/dev/null || true; rm -rf "$W"' EXIT fail() { echo "FAIL: $1"; echo "--- game output"; cat "$W/out.txt"; echo "--- prism.log"; cat "$W/home/logs/prism.log" 2>/dev/null; exit 1; } wait_for() { for _ in $(seq 1 100); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 0.1; done; fail "timed out waiting for '$2' in $(basename "$1")"; } @@ -14,25 +14,43 @@ SRC="$ROOT/tests/fake-game/src" javac -q -d "$W/classes/game" $(find "$SRC/net" -name '*.java') 2>/dev/null || javac -d "$W/classes/game" $(find "$SRC/net" -name '*.java') (cd "$W/classes/game" && jar cf "$W/game.jar" .) javac -d "$W/classes/launcher" "$SRC/launcher/Launcher.java" -cp "$ROOT/java/core/build/libs/prism-core-0.1.0.jar" "$W/home/bin/prism-core.jar" -cp "$ROOT/java/example-plugin/build/libs/example-plugin-0.1.0.jar" "$W/home/plugins/example.jar" +cp "$ROOT/java/core/build/libs/prism-core.jar" "$W/home/bin/prism-core.jar" +cp "$ROOT/java/example-plugin/build/libs/example-plugin.jar" "$W/home/plugins/example.jar" +mkdir -p "$W/hooktest" +javac -d "$W/hooktest" -cp "$ROOT/java/api/build/libs/prism-api.jar" "$ROOT/tests/hook-plugin/src/hooktest/HookTestPlugin.java" +cp "$ROOT/tests/hook-plugin/plugin.properties" "$W/hooktest/" +(cd "$W/hooktest" && jar cf "$W/home/plugins/hooktest.jar" .) -java -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 -XX:+EnableDynamicAgentLoading -cp "$W/classes/launcher" launcher.Launcher "$W/game.jar" > "$W/out.txt" 2>&1 & +java -Dfake.keys="$W/keys" -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 -XX:+EnableDynamicAgentLoading -cp "$W/classes/launcher" launcher.Launcher "$W/game.jar" > "$W/out.txt" 2>&1 & GAME=$! sleep 0.5 # inject while the game is still "loading" jcmd $GAME JVMTI.agent_load "$ROOT/target/debug/libprism_agent.so" "$W/home|$W/home/bin/prism-core.jar" >/dev/null wait_for "$W/out.txt" "GAME: started" -wait_for "$W/out.txt" "CHAT\[Client thread\]: §d\[Prism\] §fLoaded Example" +wait_for "$W/out.txt" "CHAT\[Client thread\]: §d\[Prism\] §fLoaded Example, HookTest" wait_for "$W/out.txt" "CHAT\[Client thread\]: §d\[Example\] §fHello!" grep -q "mcp names" "$W/home/logs/prism.log" || fail "mappings not detected as mcp" echo "ok injected, core started on the game's class loader, plugin loaded, chat on client thread" +# hooks +grep -q "hooks placed: 4" "$W/home/logs/prism.log" || fail "not all 4 hooks placed" +wait_for "$W/home/logs/prism.log" "counts tick=[1-9][0-9]* overlay=[1-9][0-9]* world=[1-9]" +grep -q "overlay size 427x240 pt 0.5" "$W/home/logs/prism.log" || fail "overlay event values wrong" +wait_for "$W/out.txt" "DRAW text '§dPrism" +echo "ok tick, HUD and world events fire; drawing works" +touch "$W/keys" +wait_for "$W/out.txt" "GAME KEY -100 true" +grep -q "GAME KEY 31 true" "$W/out.txt" || fail "key 31 should reach the game" +grep -q "GAME KEY 30 " "$W/out.txt" && fail "key 30 should have been cancelled" +grep -q "key event 30 true" "$W/home/logs/prism.log" || fail "no key event" +grep -q "mouse event 0 true" "$W/home/logs/prism.log" || fail "no mouse event" +echo "ok key and mouse events, cancel works" + # hot reload: replace the jar with a new version (different properties -> different file) mkdir -p "$W/p2"; (cd "$W/p2" && unzip -q "$W/home/plugins/example.jar" && sed -i 's/version=1.0.0/version=1.0.1/' plugin.properties && jar cf "$W/example2.jar" .) cp "$W/example2.jar" "$W/home/plugins/example.jar" wait_for "$W/home/logs/prism.log" "enabled Example 1.0.1" -wait_for "$W/out.txt" "Reloaded Example" +wait_for "$W/out.txt" "§fReloaded Example" grep -q "disabled Example 1.0.0" "$W/home/logs/prism.log" || fail "old version not disabled" echo "ok hot reload" @@ -42,7 +60,7 @@ wait_for "$W/out.txt" "broken.jar failed to load" echo "ok broken plugin reported" rm "$W/home/plugins/broken.jar" -rm "$W/home/plugins/example.jar" +rm "$W/home/plugins/example.jar" "$W/home/plugins/hooktest.jar" wait_for "$W/home/logs/prism.log" "disabled Example 1.0.1" echo "ok plugin removed" @@ -50,13 +68,18 @@ touch "$W/home/bin/unload-$GAME" wait_for "$W/home/logs/agent.log" "unloaded" grep -q "stopped" "$W/home/logs/prism.log" 2>/dev/null || grep -q "stopped" "$W/home/logs/prism.old.log" || fail "core not stopped" kill -0 $GAME || fail "game died after unload" -echo "ok unloaded, game still running" +grep -q "hooks removed" "$W/home/logs/prism.log" "$W/home/logs/prism.old.log" 2>/dev/null || fail "hooks not removed" +touch "$W/keys" +wait_for "$W/out.txt" "GAME KEY 30 true" +echo "ok unloaded, hooks removed (game code back to normal), game still running" # inject again after unload (the app's Inject button after Unload) -cp "$ROOT/java/example-plugin/build/libs/example-plugin-0.1.0.jar" "$W/home/plugins/example.jar" +cp "$ROOT/java/example-plugin/build/libs/example-plugin.jar" "$W/home/plugins/example.jar" : > "$W/out.txt.mark"; LINES=$(wc -l < "$W/out.txt") jcmd $GAME JVMTI.agent_load "$ROOT/target/debug/libprism_agent.so" "$W/home|$W/home/bin/prism-core.jar" >/dev/null for _ in $(seq 1 100); do tail -n +$((LINES+1)) "$W/out.txt" | grep -q "Loaded Example" && break; sleep 0.1; done tail -n +$((LINES+1)) "$W/out.txt" | grep -q "Loaded Example" || fail "re-inject didn't load" -echo "ok injected again" +for _ in $(seq 1 50); do grep -q "hooks placed: 4" "$W/home/logs/prism.log" && break; sleep 0.1; done +grep -q "hooks placed: 4" "$W/home/logs/prism.log" || fail "hooks not placed after re-inject" +echo "ok injected again, hooks placed again" echo "ALL PASSED"