2021-06-11 14:02:28 +02:00
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Techcable <Techcable@outlook.com>
Date: Thu, 3 Mar 2016 13:20:33 -0700
Subject: [PATCH] Use ASM for event executors.
Uses method handles for private or static methods.
2021-06-12 04:23:18 +02:00
diff --git a/build.gradle.kts b/build.gradle.kts
2024-12-04 04:50:18 +01:00
index 64f7695cf37e9e60712f8b56d3aee0256e71c8e6..3a026fc8671fee2b99ea0a23a4278453c7fab267 100644
2021-06-12 04:23:18 +02:00
--- a/build.gradle.kts
+++ b/build.gradle.kts
2024-11-09 22:49:07 +01:00
@@ -59,6 +59,9 @@ dependencies {
2021-08-14 06:11:12 +02:00
apiAndDocs("net.kyori:adventure-text-serializer-legacy")
apiAndDocs("net.kyori:adventure-text-serializer-plain")
2022-06-12 23:07:40 +02:00
apiAndDocs("net.kyori:adventure-text-logger-slf4j")
2021-07-20 00:58:48 +02:00
+
2024-10-21 00:06:54 +02:00
+ implementation("org.ow2.asm:asm:9.7.1")
+ implementation("org.ow2.asm:asm-commons:9.7.1")
2021-11-27 07:54:18 +01:00
// Paper end
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
compileOnly("org.apache.maven:maven-resolver-provider:3.9.6")
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java b/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java
new file mode 100644
2024-09-30 01:48:34 +02:00
index 0000000000000000000000000000000000000000..5a702481d28d90cb503faad0d9b9c3231bbff940
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/event/executor/MethodHandleEventExecutor.java
2024-09-30 01:48:34 +02:00
@@ -0,0 +1,46 @@
2021-06-11 14:02:28 +02:00
+package com.destroystokyo.paper.event.executor;
+
2024-09-30 01:48:34 +02:00
+import com.destroystokyo.paper.util.SneakyThrow;
2021-06-11 14:02:28 +02:00
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.reflect.Method;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventException;
+import org.bukkit.event.Listener;
+import org.bukkit.plugin.EventExecutor;
2024-09-30 01:48:34 +02:00
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+@ApiStatus.Internal
+@NullMarked
2021-06-11 14:02:28 +02:00
+public class MethodHandleEventExecutor implements EventExecutor {
2024-09-30 01:48:34 +02:00
+
2021-06-11 14:02:28 +02:00
+ private final Class<? extends Event> eventClass;
+ private final MethodHandle handle;
+
2024-09-30 01:48:34 +02:00
+ public MethodHandleEventExecutor(final Class<? extends Event> eventClass, final MethodHandle handle) {
2021-06-11 14:02:28 +02:00
+ this.eventClass = eventClass;
+ this.handle = handle;
+ }
+
2024-09-30 01:48:34 +02:00
+ public MethodHandleEventExecutor(final Class<? extends Event> eventClass, final Method m) {
2021-06-11 14:02:28 +02:00
+ this.eventClass = eventClass;
+ try {
+ m.setAccessible(true);
+ this.handle = MethodHandles.lookup().unreflect(m);
2024-09-30 01:48:34 +02:00
+ } catch (final IllegalAccessException e) {
2021-06-11 14:02:28 +02:00
+ throw new AssertionError("Unable to set accessible", e);
+ }
+ }
+
+ @Override
2024-09-30 01:48:34 +02:00
+ public void execute(final Listener listener, final Event event) throws EventException {
+ if (!this.eventClass.isInstance(event)) return;
2021-06-11 14:02:28 +02:00
+ try {
2024-09-30 01:48:34 +02:00
+ this.handle.invoke(listener, event);
+ } catch (final Throwable t) {
2021-06-11 14:02:28 +02:00
+ SneakyThrow.sneaky(t);
+ }
+ }
+}
diff --git a/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java b/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java
new file mode 100644
2024-09-30 01:48:34 +02:00
index 0000000000000000000000000000000000000000..bbdb5b472df116b71c459bdc6cc4b74267ea0f5e
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/event/executor/StaticMethodHandleEventExecutor.java
2024-09-30 01:48:34 +02:00
@@ -0,0 +1,44 @@
2021-06-11 14:02:28 +02:00
+package com.destroystokyo.paper.event.executor;
+
2024-09-30 01:48:34 +02:00
+import com.destroystokyo.paper.util.SneakyThrow;
+import com.google.common.base.Preconditions;
2021-06-11 14:02:28 +02:00
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventException;
+import org.bukkit.event.Listener;
+import org.bukkit.plugin.EventExecutor;
2024-09-30 01:48:34 +02:00
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.NullMarked;
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+@ApiStatus.Internal
+@NullMarked
2021-06-11 14:02:28 +02:00
+public class StaticMethodHandleEventExecutor implements EventExecutor {
2024-09-30 01:48:34 +02:00
+
2021-06-11 14:02:28 +02:00
+ private final Class<? extends Event> eventClass;
+ private final MethodHandle handle;
+
2024-09-30 01:48:34 +02:00
+ public StaticMethodHandleEventExecutor(final Class<? extends Event> eventClass, final Method m) {
2021-06-11 14:02:28 +02:00
+ Preconditions.checkArgument(Modifier.isStatic(m.getModifiers()), "Not a static method: %s", m);
+ Preconditions.checkArgument(eventClass != null, "eventClass is null");
+ this.eventClass = eventClass;
+ try {
+ m.setAccessible(true);
+ this.handle = MethodHandles.lookup().unreflect(m);
2024-09-30 01:48:34 +02:00
+ } catch (final IllegalAccessException e) {
2021-06-11 14:02:28 +02:00
+ throw new AssertionError("Unable to set accessible", e);
+ }
+ }
+
+ @Override
2024-09-30 01:48:34 +02:00
+ public void execute(final Listener listener, final Event event) throws EventException {
+ if (!this.eventClass.isInstance(event)) return;
2021-06-11 14:02:28 +02:00
+ try {
2024-09-30 01:48:34 +02:00
+ this.handle.invoke(event);
+ } catch (final Throwable throwable) {
2021-06-11 14:02:28 +02:00
+ SneakyThrow.sneaky(throwable);
+ }
+ }
+}
diff --git a/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java b/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java
new file mode 100644
2024-09-30 01:48:34 +02:00
index 0000000000000000000000000000000000000000..abfcb6e8383ff311940d82afe4ff990649a082dc
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/event/executor/asm/ASMEventExecutorGenerator.java
2024-09-30 01:48:34 +02:00
@@ -0,0 +1,59 @@
2021-06-11 14:02:28 +02:00
+package com.destroystokyo.paper.event.executor.asm;
+
+import java.lang.reflect.Method;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.bukkit.plugin.EventExecutor;
2024-09-30 01:48:34 +02:00
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.NullMarked;
2021-06-11 14:02:28 +02:00
+import org.objectweb.asm.ClassWriter;
+import org.objectweb.asm.Type;
+import org.objectweb.asm.commons.GeneratorAdapter;
+
2024-09-30 01:48:34 +02:00
+import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
+import static org.objectweb.asm.Opcodes.INVOKEINTERFACE;
+import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
+import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
+import static org.objectweb.asm.Opcodes.V1_8;
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+@ApiStatus.Internal
+@NullMarked
+public final class ASMEventExecutorGenerator {
2022-10-28 02:27:33 +02:00
+
+ private static final String EXECUTE_DESCRIPTOR = "(Lorg/bukkit/event/Listener;Lorg/bukkit/event/Event;)V";
+
2024-09-30 01:48:34 +02:00
+ public static byte[] generateEventExecutor(final Method m, final String name) {
+ final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
+ writer.visit(V1_8, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class), new String[]{Type.getInternalName(EventExecutor.class)});
2021-06-11 14:02:28 +02:00
+ // Generate constructor
+ GeneratorAdapter methodGenerator = new GeneratorAdapter(writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null), ACC_PUBLIC, "<init>", "()V");
+ methodGenerator.loadThis();
+ methodGenerator.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // Invoke the super class (Object) constructor
+ methodGenerator.returnValue();
+ methodGenerator.endMethod();
+ // Generate the execute method
2022-10-28 02:27:33 +02:00
+ methodGenerator = new GeneratorAdapter(writer.visitMethod(ACC_PUBLIC, "execute", EXECUTE_DESCRIPTOR, null, null), ACC_PUBLIC, "execute", EXECUTE_DESCRIPTOR);
2021-06-11 14:02:28 +02:00
+ methodGenerator.loadArg(0);
+ methodGenerator.checkCast(Type.getType(m.getDeclaringClass()));
+ methodGenerator.loadArg(1);
+ methodGenerator.checkCast(Type.getType(m.getParameterTypes()[0]));
+ methodGenerator.visitMethodInsn(m.getDeclaringClass().isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, Type.getInternalName(m.getDeclaringClass()), m.getName(), Type.getMethodDescriptor(m), m.getDeclaringClass().isInterface());
2022-01-20 20:54:57 +01:00
+ // The only purpose of this switch statement is to generate the correct pop instruction, should the event handler method return something other than void.
+ // Non-void event handlers will be unsupported in a future release.
+ switch (Type.getType(m.getReturnType()).getSize()) {
+ // case 0 is omitted because the only type that has size 0 is void - no pop instruction needed.
+ case 1 -> methodGenerator.pop(); // handles reference types and most primitives
+ case 2 -> methodGenerator.pop2(); // handles long and double
2021-06-11 14:02:28 +02:00
+ }
+ methodGenerator.returnValue();
+ methodGenerator.endMethod();
+ writer.visitEnd();
+ return writer.toByteArray();
+ }
+
+ public static AtomicInteger NEXT_ID = new AtomicInteger(1);
2024-09-30 01:48:34 +02:00
+
2021-06-11 14:02:28 +02:00
+ public static String generateName() {
2024-09-30 01:48:34 +02:00
+ final int id = NEXT_ID.getAndIncrement();
2021-06-11 14:02:28 +02:00
+ return "com.destroystokyo.paper.event.executor.asm.generated.GeneratedEventExecutor" + id;
+ }
+}
diff --git a/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java b/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java
new file mode 100644
2024-09-30 01:48:34 +02:00
index 0000000000000000000000000000000000000000..581561fbd32c81ab1774ba8f0b7f3cec9392d99a
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/event/executor/asm/ClassDefiner.java
2024-09-30 01:48:34 +02:00
@@ -0,0 +1,35 @@
2021-06-11 14:02:28 +02:00
+package com.destroystokyo.paper.event.executor.asm;
+
2024-09-30 01:48:34 +02:00
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.NullMarked;
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+@ApiStatus.Internal
+@NullMarked
2021-06-11 14:02:28 +02:00
+public interface ClassDefiner {
+
+ /**
+ * Returns if the defined classes can bypass access checks
+ *
+ * @return if classes bypass access checks
+ */
2024-09-30 01:48:34 +02:00
+ default boolean isBypassAccessChecks() {
2021-06-11 14:02:28 +02:00
+ return false;
+ }
+
+ /**
+ * Define a class
+ *
+ * @param parentLoader the parent classloader
+ * @param name the name of the class
+ * @param data the class data to load
+ * @return the defined class
+ * @throws ClassFormatError if the class data is invalid
+ * @throws NullPointerException if any of the arguments are null
+ */
2024-09-30 01:48:34 +02:00
+ Class<?> defineClass(ClassLoader parentLoader, String name, byte[] data);
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+ static ClassDefiner getInstance() {
2021-06-11 14:02:28 +02:00
+ return SafeClassDefiner.INSTANCE;
+ }
+
+}
diff --git a/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java b/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java
new file mode 100644
2024-09-30 01:48:34 +02:00
index 0000000000000000000000000000000000000000..48bcc72293c2a31b6e2dd2dcd6a79d618c72a137
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/event/executor/asm/SafeClassDefiner.java
2024-09-30 01:48:34 +02:00
@@ -0,0 +1,66 @@
2021-06-11 14:02:28 +02:00
+package com.destroystokyo.paper.event.executor.asm;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.MapMaker;
2024-09-30 01:48:34 +02:00
+import java.util.concurrent.ConcurrentMap;
+import org.jetbrains.annotations.ApiStatus;
+import org.jspecify.annotations.NullMarked;
2021-06-11 14:02:28 +02:00
+
2024-09-30 01:48:34 +02:00
+@ApiStatus.Internal
+@NullMarked
2021-06-11 14:02:28 +02:00
+public class SafeClassDefiner implements ClassDefiner {
2024-09-30 01:48:34 +02:00
+
2021-06-11 14:02:28 +02:00
+ /* default */ static final SafeClassDefiner INSTANCE = new SafeClassDefiner();
+
2024-09-30 01:48:34 +02:00
+ private SafeClassDefiner() {
+ }
2021-06-11 14:02:28 +02:00
+
+ private final ConcurrentMap<ClassLoader, GeneratedClassLoader> loaders = new MapMaker().weakKeys().makeMap();
+
+ @Override
2024-09-30 01:48:34 +02:00
+ public Class<?> defineClass(final ClassLoader parentLoader, final String name, final byte[] data) {
+ final GeneratedClassLoader loader = this.loaders.computeIfAbsent(parentLoader, GeneratedClassLoader::new);
2021-06-11 14:02:28 +02:00
+ synchronized (loader.getClassLoadingLock(name)) {
+ Preconditions.checkState(!loader.hasClass(name), "%s already defined", name);
2024-09-30 01:48:34 +02:00
+ final Class<?> c = loader.define(name, data);
2021-06-11 14:02:28 +02:00
+ assert c.getName().equals(name);
+ return c;
+ }
+ }
+
+ private static class GeneratedClassLoader extends ClassLoader {
2024-09-30 01:48:34 +02:00
+
2021-06-11 14:02:28 +02:00
+ static {
+ ClassLoader.registerAsParallelCapable();
+ }
+
2024-09-30 01:48:34 +02:00
+ protected GeneratedClassLoader(final ClassLoader parent) {
2021-06-11 14:02:28 +02:00
+ super(parent);
+ }
+
2024-09-30 01:48:34 +02:00
+ private Class<?> define(final String name, final byte[] data) {
+ synchronized (this.getClassLoadingLock(name)) {
+ assert !this.hasClass(name);
+ final Class<?> c = this.defineClass(name, data, 0, data.length);
+ this.resolveClass(c);
2021-06-11 14:02:28 +02:00
+ return c;
+ }
+ }
+
+ @Override
2024-09-30 01:48:34 +02:00
+ public Object getClassLoadingLock(final String name) {
2021-06-11 14:02:28 +02:00
+ return super.getClassLoadingLock(name);
+ }
+
2024-09-30 01:48:34 +02:00
+ public boolean hasClass(final String name) {
+ synchronized (this.getClassLoadingLock(name)) {
2021-06-11 14:02:28 +02:00
+ try {
+ Class.forName(name);
+ return true;
2024-09-30 01:48:34 +02:00
+ } catch (final ClassNotFoundException e) {
2021-06-11 14:02:28 +02:00
+ return false;
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/bukkit/plugin/EventExecutor.java b/src/main/java/org/bukkit/plugin/EventExecutor.java
index a850f0780de05463fc0d3f9e15ff7f19d88b2aed..9026e108ccd3a88aee1267ee275137befa646455 100644
--- a/src/main/java/org/bukkit/plugin/EventExecutor.java
+++ b/src/main/java/org/bukkit/plugin/EventExecutor.java
@@ -5,9 +5,75 @@ import org.bukkit.event.EventException;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
+// Paper start
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.function.Function;
+
+import com.destroystokyo.paper.event.executor.MethodHandleEventExecutor;
+import com.destroystokyo.paper.event.executor.StaticMethodHandleEventExecutor;
+import com.destroystokyo.paper.event.executor.asm.ASMEventExecutorGenerator;
+import com.destroystokyo.paper.event.executor.asm.ClassDefiner;
+import com.google.common.base.Preconditions;
+// Paper end
+
/**
* Interface which defines the class for event call backs to plugins
*/
public interface EventExecutor {
public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException;
+
+ // Paper start
+ ConcurrentMap<Method, Class<? extends EventExecutor>> eventExecutorMap = new ConcurrentHashMap<Method, Class<? extends EventExecutor>>() {
+ @NotNull
+ @Override
+ public Class<? extends EventExecutor> computeIfAbsent(@NotNull Method key, @NotNull Function<? super Method, ? extends Class<? extends EventExecutor>> mappingFunction) {
+ Class<? extends EventExecutor> executorClass = get(key);
+ if (executorClass != null)
+ return executorClass;
+
+ //noinspection SynchronizationOnLocalVariableOrMethodParameter
+ synchronized (key) {
+ executorClass = get(key);
+ if (executorClass != null)
+ return executorClass;
+
+ return super.computeIfAbsent(key, mappingFunction);
+ }
+ }
+ };
+
+ @NotNull
+ public static EventExecutor create(@NotNull Method m, @NotNull Class<? extends Event> eventClass) {
+ Preconditions.checkNotNull(m, "Null method");
+ Preconditions.checkArgument(m.getParameterCount() != 0, "Incorrect number of arguments %s", m.getParameterCount());
+ Preconditions.checkArgument(m.getParameterTypes()[0] == eventClass, "First parameter %s doesn't match event class %s", m.getParameterTypes()[0], eventClass);
+ ClassDefiner definer = ClassDefiner.getInstance();
+ if (Modifier.isStatic(m.getModifiers())) {
+ return new StaticMethodHandleEventExecutor(eventClass, m);
+ } else if (definer.isBypassAccessChecks() || Modifier.isPublic(m.getDeclaringClass().getModifiers()) && Modifier.isPublic(m.getModifiers())) {
+ // get the existing generated EventExecutor class for the Method or generate one
+ Class<? extends EventExecutor> executorClass = eventExecutorMap.computeIfAbsent(m, (__) -> {
+ String name = ASMEventExecutorGenerator.generateName();
+ byte[] classData = ASMEventExecutorGenerator.generateEventExecutor(m, name);
+ return definer.defineClass(m.getDeclaringClass().getClassLoader(), name, classData).asSubclass(EventExecutor.class);
+ });
+
+ try {
+ EventExecutor asmExecutor = executorClass.newInstance();
+ // Define a wrapper to conform to bukkit stupidity (passing in events that don't match and wrapper exception)
+ return (listener, event) -> {
+ if (!eventClass.isInstance(event)) return;
+ asmExecutor.execute(listener, event);
+ };
+ } catch (InstantiationException | IllegalAccessException e) {
+ throw new AssertionError("Unable to initialize generated event executor", e);
+ }
+ } else {
+ return new MethodHandleEventExecutor(eventClass, m);
+ }
+ }
+ // Paper end
}