Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix packet instantiation on 1.20.6 #2941

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/main/java/com/comphenix/protocol/injector/StructureCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Class<?>, Supplier<Object>> PACKET_INSTANCE_CREATORS = new ConcurrentHashMap<>();
Expand Down Expand Up @@ -91,6 +101,19 @@ public static Object newPacket(Class<?> packetClass) {
// shrug, fall back to default behaviour

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment to say fallback to unsafe allocator?

}
}

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Copy link
Collaborator

@Ingrim4 Ingrim4 May 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use FuzzyReflection here in case some JVM implements this differently?

outerThisField.setAccessible(true);
Object realSer = outerThisField.get(serializer);
result.classToCodec.put(packetClass, new WrappedStreamCodec(realSer));
}

// get EnumProtocol and Direction of protocol info
Expand Down