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"