Fix: Resolve hooks on launchers with remapped class loaders

Inject through the top-level orangexbridge package instead of imported cn.* names, build a fresh Javassist pool with agent-provided runtime class bytes, and fall back to safe class paths. Fixes Lunar GenesisClassLoader hook failures where resource class files still use obfuscated names.
This commit is contained in:
xiaozhou233 committed 2026-11-07 13:51:57 +08:00
1 parent cfb0ba4a48
commit 4b55871a8b
13 files changed
+344 -143

No files matched your search

@@ -0,0 +1,79 @@
package cn.xiaozhou233.orangex.hook;
import javassist.ClassPath;
import javassist.NotFoundException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
/**
* Resolves game classes from the <strong>loaded</strong> class bytes through
* the JuiceAgent.
*
* <p>Some launchers (for example Lunar's Genesis class loader) serve
* MCP-named class resources but the bytes inside still use obfuscated class
* names. Javassist then throws errors such as
* {@code cannot find net.minecraft.util.IThreadListener: od found in ...}.
* The agent can return the current, runtime-named bytecode instead.</p>
*/
final class AgentClassPath implements ClassPath {
private final ClassLoader loader;
AgentClassPath(ClassLoader loader) {
this.loader = loader;
}
@Override
public InputStream openClassfile(String classname) throws NotFoundException {
if (isPlatformClass(classname)
|| classname.startsWith("cn.xiaozhou233.")
|| classname.startsWith("orangexbridge.")) {
return null;
}
byte[] bytes = readBytes(classname);
return bytes == null ? null : new ByteArrayInputStream(bytes);
}
private byte[] readBytes(String classname) {
String internalName = classname.replace('.', '/');
try {
byte[] bytes = JuiceAgentBridge.getClassBytesByName(internalName);
if (bytes != null) {
return bytes;
}
} catch (Throwable ignored) {
// The class may not be loaded yet.
}
if (loader == null) {
return null;
}
try {
Class.forName(classname, false, loader);
return JuiceAgentBridge.getClassBytesByName(internalName);
} catch (Throwable ignored) {
return null;
}
}
private static boolean isPlatformClass(String classname) {
return classname.startsWith("java.")
|| classname.startsWith("javax.")
|| classname.startsWith("jdk.")
|| classname.startsWith("sun.")
|| classname.startsWith("com.sun.")
|| classname.startsWith("javassist.")
|| classname.startsWith("org.greenrobot.")
|| classname.startsWith("com.google.gson.");
}
@Override
public URL find(String classname) {
return null;
}
}
@@ -2,7 +2,6 @@ package cn.xiaozhou233.orangex.hook;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.LoaderClassPath;
import java.io.ByteArrayInputStream;
@@ -12,21 +11,10 @@ public abstract class ClassHook {
protected abstract void transform(CtClass ctClass) throws Exception;
/**
* Fully qualified names of classes referenced by the injected code.
* Their packages are imported so the injected source can use simple names.
*/
protected String[] getInjectedClassNames() {
return new String[0];
}
public final byte[] transform(ClassLoader loader, byte[] classBytes)
throws Exception {
ClassPool pool = ClassPool.getDefault();
pool.appendClassPath(new LoaderClassPath(loader));
ClassPoolUtils.prepare(pool, getInjectedClassNames());
ClassPool pool = ClassPoolUtils.createPool(loader);
CtClass ctClass = pool.makeClass(
new ByteArrayInputStream(classBytes),
false
@@ -2,13 +2,17 @@ package cn.xiaozhou233.orangex.hook;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.LoaderClassPath;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
* Javassist setup shared by all hooks.
*
* <p>A fresh pool is created for each transform instead of using
* {@link ClassPool#getDefault()}: on some launchers the current thread has a
* {@code null} context class loader, which makes the default pool's system
* path throw while resolving imported class names.</p>
*/
public final class ClassPoolUtils {
@@ -18,69 +22,66 @@ public final class ClassPoolUtils {
*/
private static final String ORANGEX_JAR_PROPERTY = "orangex.jar";
private static final Set<String> importedPackages = new HashSet<String>();
private static boolean classPathAdded;
private static boolean bridgeChecked;
/**
* Prepares {@code pool} for compiling injected code.
*
* <p>Solves two problems:</p>
*
* Creates a pool that can resolve:
* <ul>
* <li>{@link ClassPool#getDefault()} only knows the JVM class path. The
* OrangeX jar is injected into the game class loader at runtime, so it
* must be added explicitly, otherwise javassist cannot find OrangeX
* classes.</li>
* <li>Vanilla 1.8.8 contains an obfuscated class in the default package
* named {@code cn}, which collides with the first segment of our
* package. Javassist resolves qualified names from left to right, finds
* that class instead of the package, and fails with the misleading
* {@code no such class: cn$xiaozhou233...}. Importing the packages lets
* injected code use simple class names and avoids the collision.</li>
* <li>OrangeX classes from the injected jar;</li>
* <li>game classes from their runtime (post-transform) bytes through
* the agent, avoiding launchers whose class-loader resources still
* contain obfuscated names;</li>
* <li>anything else via the game loader and the system loader.</li>
* </ul>
*
* @param classNames fully qualified names of the classes referenced by the
* injected code; their packages are imported
* @param loader the game class loader
*/
public static synchronized void prepare(ClassPool pool, String... classNames) {
importPackages(pool, classNames);
if (classPathAdded) {
return;
}
classPathAdded = true;
public static ClassPool createPool(ClassLoader loader) {
ClassPool pool = new ClassPool(false);
File jar = orangeXJar();
if (jar == null) {
if (jar != null) {
try {
pool.insertClassPath(jar.getAbsolutePath());
System.out.println("[OrangeX] javassist classpath: "
+ jar.getAbsolutePath());
} catch (Throwable t) {
System.out.println("[OrangeX] Failed to add javassist classpath: "
+ jar.getAbsolutePath() + " (" + t + ")");
}
} else {
System.out.println("[OrangeX] WARNING: OrangeX.jar not found for javassist; "
+ "injected classes may fail to compile");
pool.insertClassPath(new ClassClassPath(ClassPoolUtils.class));
return;
}
try {
pool.insertClassPath(jar.getAbsolutePath());
System.out.println("[OrangeX] javassist classpath: " + jar.getAbsolutePath());
} catch (Throwable t) {
System.out.println("[OrangeX] Failed to add javassist classpath: "
+ jar.getAbsolutePath() + " (" + t + ")");
// Runtime bytes of already-loaded game classes (MCP-named even when
// the launcher's resource stream is still obfuscated).
pool.appendClassPath(new AgentClassPath(loader));
if (loader != null) {
pool.appendClassPath(new SafeClassPath(new LoaderClassPath(loader)));
}
}
private static void importPackages(ClassPool pool, String[] classNames) {
for (String className : classNames) {
int dot = className.lastIndexOf('.');
if (dot <= 0) {
continue;
}
ClassLoader system = ClassLoader.getSystemClassLoader();
if (system != null) {
pool.appendClassPath(new SafeClassPath(new LoaderClassPath(system)));
} else {
pool.appendClassPath(new ClassClassPath(Object.class));
}
String packageName = className.substring(0, dot);
if (importedPackages.add(packageName)) {
pool.importPackage(packageName);
if (!bridgeChecked) {
bridgeChecked = true;
try {
pool.get("orangexbridge.Hooks");
System.out.println("[OrangeX] javassist bridge OK");
} catch (Throwable t) {
System.out.println("[OrangeX] javassist bridge FAILED");
t.printStackTrace();
}
}
return pool;
}
private static File orangeXJar() {
@@ -6,12 +6,22 @@ import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class HookManager {
@Getter
private static final HookManager INSTANCE = new HookManager();
/**
* Original (pre-injection) bytes of every hook target, keyed by dot name.
* Used by 1.8.9 screen generation so it never has to retransform a class
* that has already been patched.
*/
private static final Map<String, byte[]> TARGET_BYTES =
new ConcurrentHashMap<String, byte[]>();
private final List<ClassHook> hooks = new ArrayList<ClassHook>();
private HookManager() {
@@ -40,6 +50,7 @@ public final class HookManager {
if (classBytes == null) {
continue;
}
TARGET_BYTES.put(className, classBytes);
byte[] bytes = hook.transform(loader, classBytes);
JuiceAgentBridge.retransformClassByName(className, bytes);
@@ -49,4 +60,8 @@ public final class HookManager {
}
}
}
public static byte[] getTargetBytes(String className) {
return TARGET_BYTES.get(className);
}
}
@@ -0,0 +1,37 @@
package cn.xiaozhou233.orangex.hook;
import javassist.ClassPath;
import java.io.InputStream;
import java.net.URL;
/**
* Wraps a {@link ClassPath} so launcher-specific exceptions are treated as
* "not found" instead of aborting Javassist's class path search.
*/
final class SafeClassPath implements ClassPath {
private final ClassPath delegate;
SafeClassPath(ClassPath delegate) {
this.delegate = delegate;
}
@Override
public InputStream openClassfile(String classname) {
try {
return delegate.openClassfile(classname);
} catch (Throwable ignored) {
return null;
}
}
@Override
public URL find(String classname) {
try {
return delegate.find(classname);
} catch (Throwable ignored) {
return null;
}
}
}
@@ -28,14 +28,6 @@ public final class GuiInputHook extends ClassHook {
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.InputEvents",
"cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
@@ -54,27 +46,27 @@ public final class GuiInputHook extends ClassHook {
}
injectBefore(ctClass, "drawScreen", "(IIF)V",
"InputEvents.onDrawScreen($0, $1, $2);");
"orangexbridge.Hooks.inputDraw($0, $1, $2);");
injectBefore(ctClass, "mouseClicked", "(III)V",
"if (InputEvents.onMouseClicked($0, $1, $2, $3)) return;");
"if (orangexbridge.Hooks.inputClick($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseReleased", "(III)V",
"if (InputEvents.onMouseReleased($0, $1, $2, $3)) return;");
"if (orangexbridge.Hooks.inputRelease($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseClickMove", "(IIIJ)V",
"InputEvents.onMouseDragged($0, $1, $2, $3);");
"orangexbridge.Hooks.inputDrag($0, $1, $2, $3);");
// Close with M while the empty screen is open. Repeat events are
// ignored so holding the key does not bounce the screen.
injectBefore(ctClass, "keyTyped", "(CI)V",
"if ($2 == V1_8_9Input.TOGGLE_KEY"
+ " && !V1_8_9Input.isRepeatEvent()"
+ " && InputEvents.onKeyTyped($0, $2)) return;");
"if ($2 == orangexbridge.Legacy.TOGGLE_KEY"
+ " && !orangexbridge.Legacy.isRepeatEvent()"
+ " && orangexbridge.Hooks.inputKeyTyped($0, $2)) return;");
// The empty screen is an overlay: it must not pause singleplayer.
injectAfter(ctClass, "doesGuiPauseGame", "()Z",
"if (InputEvents.isOurInputScreen($0)) { $_ = false; }");
"if (orangexbridge.Hooks.isOurScreen($0)) { $_ = false; }");
}
private void injectBefore(CtClass ctClass, String name,
@@ -26,14 +26,6 @@ public final class KeyPressHook extends ClassHook {
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.InputEvents",
"cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
@@ -58,8 +50,8 @@ public final class KeyPressHook extends ClassHook {
// Static method: $1 is the key code. Ignore auto-repeat so holding
// M does not toggle repeatedly.
method.insertBefore(
"if ($1 == V1_8_9Input.TOGGLE_KEY"
+ " && !V1_8_9Input.isRepeatEvent())"
+ " { InputEvents.onKeyPressed($1); }");
"if ($1 == orangexbridge.Legacy.TOGGLE_KEY"
+ " && !orangexbridge.Legacy.isRepeatEvent())"
+ " { orangexbridge.Hooks.inputKeyPressed($1); }");
}
}
@@ -32,13 +32,6 @@ public final class Render2DHook extends ClassHook {
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.Render2DEvents"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
@@ -108,7 +101,7 @@ public final class Render2DHook extends ClassHook {
throw new IllegalStateException(
"No (F)V HUD method found in " + ctClass.getName());
}
method.insertAfter("Render2DEvents.fire(null, true);");
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
return;
} else {
MappingMethod target = resolver.mapMethod(
@@ -119,7 +112,7 @@ public final class Render2DHook extends ClassHook {
methodDescriptor = target.getTargetDescriptor();
}
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
method.insertAfter("Render2DEvents.fire(null, true);");
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
break;
}
case V26_2: {
@@ -132,7 +125,7 @@ public final class Render2DHook extends ClassHook {
// $0 is this, $1 is the DeltaTracker, $2 is shouldRenderLevel:
// false on the title screen, true while a level (including its
// pause/ClickGUI screens) exists.
method.insertAfter("Render2DEvents.fire($0, $2);");
method.insertAfter("orangexbridge.Hooks.render2d($0, $2);");
break;
}
default:
@@ -18,16 +18,12 @@ public final class TickHook extends ClassHook {
private static final RuntimeInfo runtimeInfo = OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{"cn.xiaozhou233.orangex.event.facade.TickEvents"};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
return resolver.mapClass("net/minecraft/client/Minecraft").getTargetName().replace("/", ".");
return resolver.mapClass("net/minecraft/client/Minecraft")
.getTargetName().replace("/", ".");
case V26_2:
return "net.minecraft.client.Minecraft";
default:
@@ -66,9 +62,8 @@ public final class TickHook extends ClassHook {
CtMethod method = ctClass.getMethod(methodName, methodDesc);
// Simple names: the package is imported by ClassPoolUtils.
// Fully qualified "cn.*" names collide with the vanilla "cn" class.
method.insertBefore("TickEvents.firePre();");
method.insertAfter("TickEvents.firePost();");
// Fully qualified bridge name avoids the default-package "cn" class.
method.insertBefore("orangexbridge.Hooks.tickPre();");
method.insertAfter("orangexbridge.Hooks.tickPost();");
}
}
@@ -1,5 +1,7 @@
package cn.xiaozhou233.orangex.input.internal.v1_8_9;
import cn.xiaozhou233.orangex.hook.ClassPoolUtils;
import cn.xiaozhou233.orangex.hook.HookManager;
import cn.xiaozhou233.orangex.hook.JuiceAgentBridge;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.input.internal.VersionInput;
@@ -11,7 +13,6 @@ import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.LoaderClassPath;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
@@ -201,22 +202,30 @@ public final class V1_8_9Input implements VersionInput {
}
try {
ClassPool pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
ClassPool pool = ClassPoolUtils.createPool(loader);
CtClass base;
try {
base = pool.get(guiScreenClass.getName());
} catch (Throwable notFound) {
// Some launch environments hide transformed class resources;
// fall back to the bytes the agent can read for the loaded class.
byte[] baseBytes = JuiceAgentBridge.getClassBytesByName(
guiScreenClass.getName().replace('.', '/'));
if (baseBytes == null) {
throw new IllegalStateException(
"Cannot load " + guiScreenClass.getName(), notFound);
byte[] cachedBase = HookManager.getTargetBytes(
guiScreenClass.getName());
if (cachedBase != null) {
// Prefer the original bytes captured before our hooks were
// applied: retransforming GuiScreen again could drop the
// injected methods.
base = pool.makeClass(new ByteArrayInputStream(cachedBase));
} else {
try {
base = pool.get(guiScreenClass.getName());
} catch (Throwable notFound) {
// Some launch environments hide transformed class resources;
// fall back to the bytes the agent can read for the loaded class.
byte[] baseBytes = JuiceAgentBridge.getClassBytesByName(
guiScreenClass.getName().replace('.', '/'));
if (baseBytes == null) {
throw new IllegalStateException(
"Cannot load " + guiScreenClass.getName(), notFound);
}
base = pool.makeClass(new ByteArrayInputStream(baseBytes));
}
base = pool.makeClass(new ByteArrayInputStream(baseBytes));
}
CtClass generated = pool.makeClass(GENERATED_SCREEN);
@@ -0,0 +1,70 @@
package orangexbridge;
import cn.xiaozhou233.orangex.event.facade.InputEvents;
import cn.xiaozhou233.orangex.event.facade.Render2DEvents;
import cn.xiaozhou233.orangex.event.facade.TickEvents;
/**
* Injection bridge.
*
* <p>Injected Javassist snippets call this class by its fully-qualified name.
* The package must not start with {@code cn}: vanilla 1.8.9 has an obfuscated
* class named {@code cn} in the default package, which makes Javassist treat
* {@code cn.xiaozhou233...} as a field access instead of a class name.</p>
*
* <p>Using a fixed full name also avoids depending on
* {@code ClassPool#importPackage}, which can be unreliable on launchers with
* custom class loaders.</p>
*/
public final class Hooks {
public static void tickPre() {
TickEvents.firePre();
}
public static void tickPost() {
TickEvents.firePost();
}
public static void render2d(Object context, boolean inWorld) {
Render2DEvents.fire(context, inWorld);
}
public static void render2d(Object context) {
Render2DEvents.fire(context);
}
public static void inputDraw(Object screen, int mouseX, int mouseY) {
InputEvents.onDrawScreen(screen, mouseX, mouseY);
}
public static boolean inputClick(Object screen, int mouseX,
int mouseY, int button) {
return InputEvents.onMouseClicked(screen, mouseX, mouseY, button);
}
public static boolean inputRelease(Object screen, int mouseX,
int mouseY, int button) {
return InputEvents.onMouseReleased(screen, mouseX, mouseY, button);
}
public static void inputDrag(Object screen, int mouseX,
int mouseY, int button) {
InputEvents.onMouseDragged(screen, mouseX, mouseY, button);
}
public static boolean inputKeyTyped(Object screen, int keyCode) {
return InputEvents.onKeyTyped(screen, keyCode);
}
public static void inputKeyPressed(int keyCode) {
InputEvents.onKeyPressed(keyCode);
}
public static boolean isOurScreen(Object screen) {
return InputEvents.isOurInputScreen(screen);
}
private Hooks() {
}
}
@@ -0,0 +1,22 @@
package orangexbridge;
import cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input;
/**
* 1.8.9-only injection bridge.
*
* <p>Kept separate from {@link Hooks} so a 26.2 runtime never has to resolve
* the LWJGL 2 classes used by {@link V1_8_9Input}.</p>
*/
public final class Legacy {
/** LWJGL 2 {@code Keyboard.KEY_M}. */
public static final int TOGGLE_KEY = 50;
public static boolean isRepeatEvent() {
return V1_8_9Input.isRepeatEvent();
}
private Legacy() {
}
}