From 5cb69f875f3b2e20282fd047e1fd8abeed2dd033 Mon Sep 17 00:00:00 2001 From: Brokkonaut Date: Tue, 21 May 2024 08:14:49 +0200 Subject: [PATCH] Fix packet instantiation on 1.20.6 --- .../protocol/injector/StructureCache.java | 23 +++++++++++++++++++ .../injector/packet/PacketRegistry.java | 5 +++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/comphenix/protocol/injector/StructureCache.java b/src/main/java/com/comphenix/protocol/injector/StructureCache.java index 1568d3568..64cf60f35 100644 --- a/src/main/java/com/comphenix/protocol/injector/StructureCache.java +++ b/src/main/java/com/comphenix/protocol/injector/StructureCache.java @@ -54,6 +54,16 @@ * @author Kristian */ public class StructureCache { + private static final sun.misc.Unsafe UNSAFE; + static { + try { + java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + UNSAFE = (sun.misc.Unsafe) f.get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } // Structure modifiers private static final Map, Supplier> PACKET_INSTANCE_CREATORS = new ConcurrentHashMap<>(); @@ -91,6 +101,19 @@ public static Object newPacket(Class packetClass) { // shrug, fall back to default behaviour } } + + try { + UNSAFE.allocateInstance(packetClass); + return () -> { + try { + return UNSAFE.allocateInstance(packetClass); + } catch (InstantiationException e) { + throw new RuntimeException(e); + } + }; + } catch (Exception ignored) { + // shrug, fall back to default behaviour + } } // prefer construction via PacketDataSerializer constructor on 1.17 and above diff --git a/src/main/java/com/comphenix/protocol/injector/packet/PacketRegistry.java b/src/main/java/com/comphenix/protocol/injector/packet/PacketRegistry.java index f422efb1b..c054eb7f0 100644 --- a/src/main/java/com/comphenix/protocol/injector/packet/PacketRegistry.java +++ b/src/main/java/com/comphenix/protocol/injector/packet/PacketRegistry.java @@ -461,7 +461,10 @@ private static synchronized Register createRegisterV1_20_5() { } Object serializer = idCodecEntrySerializerAccessor.invoke(entry); - result.classToCodec.put(packetClass, new WrappedStreamCodec(serializer)); + Field outerThisField = serializer.getClass().getDeclaredField("this$0"); + outerThisField.setAccessible(true); + Object realSer = outerThisField.get(serializer); + result.classToCodec.put(packetClass, new WrappedStreamCodec(realSer)); } // get EnumProtocol and Direction of protocol info