Search in sources :

Example 86 with FieldVisitor

use of org.objectweb.asm.FieldVisitor in project BKCommonLib by bergerhealer.

the class EntityAddRemoveHandler_1_17 method generateLevelCallbackHookType.

private static Class<?> generateLevelCallbackHookType(FastField<Object> callbacksField) {
    try {
        Class<?> levelCallbackType = callbacksField.getType();
        String levelCallbackDesc = MPLType.getDescriptor(levelCallbackType);
        String bkcCallbackDesc = MPLType.getDescriptor(LevelCallbackHandler.class);
        ExtendedClassWriter<Object> cw = ExtendedClassWriter.builder(levelCallbackType).setFlags(ClassWriter.COMPUTE_MAXS).setExactName(EntityAddRemoveHandler_1_17.class.getName() + "$Hook").build();
        FieldVisitor fv;
        MethodVisitor mv;
        // Add field with the base instance
        {
            fv = cw.visitField(ACC_PUBLIC | ACC_FINAL, "base", levelCallbackDesc, null, null);
            fv.visitEnd();
        }
        // Add field with the callback instance
        {
            fv = cw.visitField(ACC_PUBLIC | ACC_FINAL, "callback", bkcCallbackDesc, null, null);
            fv.visitEnd();
        }
        // Add constructor initializing the base instance and the callback handler instance
        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(" + levelCallbackDesc + bkcCallbackDesc + ")V", null, null);
            mv.visitCode();
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitVarInsn(ALOAD, 1);
            mv.visitFieldInsn(PUTFIELD, cw.getInternalName(), "base", levelCallbackDesc);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitVarInsn(ALOAD, 2);
            mv.visitFieldInsn(PUTFIELD, cw.getInternalName(), "callback", bkcCallbackDesc);
            mv.visitInsn(RETURN);
            mv.visitMaxs(0, 0);
            mv.visitEnd();
        }
        // Override all methods defined by the interface that must be implemented
        for (Method method : levelCallbackType.getMethods()) {
            String name = MPLType.getName(method);
            Class<?>[] params = method.getParameterTypes();
            final String callbackMethodName;
            if (name.equals("b") && params.length == 1 && params[0] == Object.class) {
                callbackMethodName = "onEntityAdded";
            } else if (name.equals("a") && params.length == 1 && params[0] == Object.class) {
                callbackMethodName = "onEntityRemoved";
            } else {
                callbackMethodName = null;
            }
            mv = cw.visitMethod(ACC_PUBLIC, MPLType.getName(method), MPLType.getMethodDescriptor(method), null, null);
            mv.visitCode();
            if (callbackMethodName != null) {
                // Locate the Method instance in the callback class we're going to be calling
                // This shouldn't ever fail.
                Method callbackMethod = Stream.of(LevelCallbackHandler.class.getMethods()).filter(m -> m.getName().equals(callbackMethodName)).findFirst().get();
                // Call the base method, store any return value in a temporary value on the stack
                mv.visitVarInsn(ALOAD, 0);
                mv.visitFieldInsn(GETFIELD, cw.getInternalName(), "base", levelCallbackDesc);
                int reg = MPLType.visitVarILoad(mv, 1, method.getParameterTypes());
                ExtendedClassWriter.visitInvoke(mv, levelCallbackType, method);
                if (method.getReturnType() != void.class) {
                    mv.visitVarInsn(MPLType.getOpcode(method.getReturnType(), ISTORE), reg);
                }
                // Then call our callback hook with the input arguments, discard return value
                mv.visitVarInsn(ALOAD, 0);
                mv.visitFieldInsn(GETFIELD, cw.getInternalName(), "callback", bkcCallbackDesc);
                MPLType.visitVarILoad(mv, 1, method.getParameterTypes());
                ExtendedClassWriter.visitInvoke(mv, LevelCallbackHandler.class, callbackMethod);
                // Finally, return the original return value of the base method (if any)
                if (method.getReturnType() != void.class) {
                    mv.visitVarInsn(MPLType.getOpcode(method.getReturnType(), ILOAD), reg);
                }
            } else {
                // Call base method directly
                mv.visitVarInsn(ALOAD, 0);
                mv.visitFieldInsn(GETFIELD, cw.getInternalName(), "base", levelCallbackDesc);
                MPLType.visitVarILoad(mv, 1, method.getParameterTypes());
                ExtendedClassWriter.visitInvoke(mv, levelCallbackType, method);
            }
            mv.visitInsn(MPLType.getOpcode(method.getReturnType(), IRETURN));
            mv.visitMaxs(0, 0);
            mv.visitEnd();
        }
        // Generate!
        return cw.generate();
    } catch (Throwable t) {
        Logging.LOGGER_REFLECTION.log(Level.SEVERE, "Failed to initialize level hook callback proxy class", t);
        return null;
    }
}
Also used : Method(java.lang.reflect.Method) FieldVisitor(org.objectweb.asm.FieldVisitor) MethodVisitor(org.objectweb.asm.MethodVisitor)

Example 87 with FieldVisitor

use of org.objectweb.asm.FieldVisitor in project BKCommonLib by bergerhealer.

the class NullPacketDataSerializerInit method initialize.

/**
 * Makes sure to initialize the NullPacketDataSerializer.
 * A new class is generated and loaded with a static field storing the instance,
 * with the correct type. Inside generated code, it can be accessed
 * the following way:<br>
 * <br>
 * <pre>com.bergerkiller.bukkit.common.internal.logic.NullPacketDataSerializer.INSTANCE</pre>
 */
public static synchronized void initialize() {
    if (is_initialized) {
        return;
    } else {
        is_initialized = true;
    }
    // Only used on 1.17 and later
    if (CommonBootstrap.evaluateMCVersion("<", "1.17")) {
        return;
    }
    // any of this library's code, so it's fine to keep using that one.
    try {
        Class.forName(CLASS_NAME);
        return;
    } catch (ClassNotFoundException ex) {
    /* expected */
    }
    try {
        Class<?> dataSerializerType = Resolver.loadClass("net.minecraft.network.PacketDataSerializer", false);
        if (dataSerializerType == null) {
            throw new IllegalStateException("PacketDataSerializer class not found in server");
        }
        final ExtendedClassWriter<Object> cw = ExtendedClassWriter.builder(dataSerializerType).setExactName(CLASS_NAME).build();
        // Add a static INSTANCE field
        {
            FieldVisitor fv;
            fv = cw.visitField(ACC_PUBLIC | ACC_STATIC, "INSTANCE", cw.getTypeDescriptor(), null, null);
            fv.visitEnd();
        }
        // Override all non-final non-private member methods of PacketDataSerializer
        ReflectionUtil.getAllMethods(dataSerializerType).filter(m -> {
            int modifiers = m.getModifiers();
            return !Modifier.isStatic(modifiers) && !Modifier.isPrivate(modifiers) && !Modifier.isFinal(modifiers);
        }).forEach(m -> {
            cw.visitMethodReturnConstant(m, BoxedType.getDefaultValue(m.getReturnType()));
        });
        // Instantiate and assign to the INSTANCE field
        Object instance = cw.generateInstanceNull();
        Field f = instance.getClass().getDeclaredField("INSTANCE");
        f.set(null, instance);
    } catch (Throwable t) {
        Logging.LOGGER_REFLECTION.log(Level.SEVERE, "Failed to initialize null packet data serializer", t);
    }
}
Also used : CommonBootstrap(com.bergerkiller.bukkit.common.internal.CommonBootstrap) Opcodes(org.objectweb.asm.Opcodes) ReflectionUtil(com.bergerkiller.mountiplex.reflection.ReflectionUtil) Modifier(java.lang.reflect.Modifier) FieldVisitor(org.objectweb.asm.FieldVisitor) Resolver(com.bergerkiller.mountiplex.reflection.resolver.Resolver) ExtendedClassWriter(com.bergerkiller.mountiplex.reflection.util.ExtendedClassWriter) Logging(com.bergerkiller.bukkit.common.Logging) BoxedType(com.bergerkiller.mountiplex.reflection.util.BoxedType) Field(java.lang.reflect.Field) Level(java.util.logging.Level) Field(java.lang.reflect.Field) FieldVisitor(org.objectweb.asm.FieldVisitor)

Example 88 with FieldVisitor

use of org.objectweb.asm.FieldVisitor in project Payara by payara.

the class CompositeUtil method createField.

/**
 * Add the field to the class, adding the @XmlAttribute annotation for marshalling purposes.
 */
private void createField(ClassWriter cw, String name, Class<?> type) {
    String internalType = getInternalTypeString(type);
    FieldVisitor field = cw.visitField(ACC_PRIVATE, getPropertyName(name), internalType, null, null);
    field.visitAnnotation("Ljavax/xml/bind/annotation/XmlAttribute;", true).visitEnd();
    field.visitEnd();
}
Also used : JsonString(javax.json.JsonString) FieldVisitor(org.objectweb.asm.FieldVisitor)

Example 89 with FieldVisitor

use of org.objectweb.asm.FieldVisitor in project baseio by generallycloud.

the class HelloGeneratorClass method generatorHelloClass.

/**
 * 使用构造Hello类class字节码<br/>
 * package中的Hello.java只是代码原型,本例中只供对比用,没有实际使用到这个类。<br/>
 * ASM代码生成工具使用 bytecode
 *
 * @return
 * @throws Exception
 * @author SHANHY
 * @create 2016年2月3日
 */
public static byte[] generatorHelloClass() {
    ClassWriter cw = new ClassWriter(0);
    FieldVisitor fv;
    MethodVisitor mv;
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "test/others/asm/Hello", null, "java/lang/Object", null);
    cw.visitSource("Hello.java", null);
    {
        fv = cw.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "FLAG", "Ljava/lang/String;", null, "\u6211\u662f\u5e38\u91cf");
        fv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        mv.visitInsn(RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "🐳", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitInsn(ICONST_0);
        mv.visitVarInsn(ISTORE, 1);
        Label l1 = new Label();
        mv.visitLabel(l1);
        Label l2 = new Label();
        mv.visitJumpInsn(GOTO, l2);
        Label l3 = new Label();
        mv.visitLabel(l3);
        mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] { Opcodes.INTEGER }, 0, null);
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitLdcInsn(">>>>>>>>>>\u6211\u662f\u5e38\u91cf");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitIincInsn(1, 1);
        mv.visitLabel(l2);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitVarInsn(ILOAD, 1);
        mv.visitIntInsn(BIPUSH, 8);
        mv.visitJumpInsn(IF_ICMPLT, l3);
        Label l5 = new Label();
        mv.visitLabel(l5);
        mv.visitInsn(RETURN);
        Label l6 = new Label();
        mv.visitLabel(l6);
        mv.visitMaxs(2, 2);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC, "testList", "()Ljava/util/List;", "()Ljava/util/List<Ljava/lang/String;>;", null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitTypeInsn(NEW, "java/util/ArrayList");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V", false);
        mv.visitVarInsn(ASTORE, 1);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitLdcInsn("Tome");
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        mv.visitInsn(POP);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitLdcInsn("Jack");
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        mv.visitInsn(POP);
        Label l3 = new Label();
        mv.visitLabel(l3);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitLdcInsn("Lily");
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        mv.visitInsn(POP);
        Label l4 = new Label();
        mv.visitLabel(l4);
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
        mv.visitInsn(DUP);
        mv.visitLdcInsn(">>>>>>>>>>testList > list.size = ");
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V", false);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I", true);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
        Label l5 = new Label();
        mv.visitLabel(l5);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(ARETURN);
        Label l6 = new Label();
        mv.visitLabel(l6);
        mv.visitMaxs(4, 2);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(ACC_PUBLIC + ACC_VARARGS, "testMapList", "(Z[Ljava/util/Map;)Ljava/util/List;", "(Z[Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;)Ljava/util/List<Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;>;", null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitTypeInsn(NEW, "java/util/ArrayList");
        mv.visitInsn(DUP);
        mv.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "<init>", "()V", false);
        mv.visitVarInsn(ASTORE, 3);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitVarInsn(ILOAD, 1);
        Label l2 = new Label();
        mv.visitJumpInsn(IFEQ, l2);
        Label l3 = new Label();
        mv.visitLabel(l3);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitInsn(DUP);
        mv.visitVarInsn(ASTORE, 7);
        mv.visitInsn(ARRAYLENGTH);
        mv.visitVarInsn(ISTORE, 6);
        mv.visitInsn(ICONST_0);
        mv.visitVarInsn(ISTORE, 5);
        Label l4 = new Label();
        mv.visitJumpInsn(GOTO, l4);
        Label l5 = new Label();
        mv.visitLabel(l5);
        mv.visitFrame(Opcodes.F_FULL, 8, new Object[] { "test/others/asm/Hello", Opcodes.INTEGER, "[Ljava/util/Map;", "java/util/List", Opcodes.TOP, Opcodes.INTEGER, Opcodes.INTEGER, "[Ljava/util/Map;" }, 0, new Object[] {});
        mv.visitVarInsn(ALOAD, 7);
        mv.visitVarInsn(ILOAD, 5);
        mv.visitInsn(AALOAD);
        mv.visitVarInsn(ASTORE, 4);
        Label l6 = new Label();
        mv.visitLabel(l6);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitVarInsn(ALOAD, 4);
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
        mv.visitInsn(POP);
        Label l7 = new Label();
        mv.visitLabel(l7);
        mv.visitIincInsn(5, 1);
        mv.visitLabel(l4);
        mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
        mv.visitVarInsn(ILOAD, 5);
        mv.visitVarInsn(ILOAD, 6);
        mv.visitJumpInsn(IF_ICMPLT, l5);
        mv.visitLabel(l2);
        mv.visitFrame(Opcodes.F_FULL, 4, new Object[] { "test/others/asm/Hello", Opcodes.INTEGER, "[Ljava/util/Map;", "java/util/List" }, 0, new Object[] {});
        mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
        mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
        mv.visitInsn(DUP);
        mv.visitLdcInsn(">>>>>>>>>>testMapList > list.size = ");
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V", false);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I", true);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
        Label l8 = new Label();
        mv.visitLabel(l8);
        mv.visitVarInsn(ALOAD, 3);
        mv.visitInsn(ARETURN);
        Label l9 = new Label();
        mv.visitLabel(l9);
        mv.visitMaxs(4, 8);
        mv.visitEnd();
    }
    cw.visitEnd();
    return cw.toByteArray();
}
Also used : Label(org.objectweb.asm.Label) FieldVisitor(org.objectweb.asm.FieldVisitor) ClassWriter(org.objectweb.asm.ClassWriter) MethodVisitor(org.objectweb.asm.MethodVisitor)

Example 90 with FieldVisitor

use of org.objectweb.asm.FieldVisitor in project SpongeCommon by SpongePowered.

the class SubtypeFilterDelegate method createFields.

public void createFields(ClassWriter cw) {
    FieldVisitor fv = cw.visitField(0, "classes", "Ljava/util/Set;", "Ljava/util/Set<Ljava/lang/Class<*>;>;", null);
    fv.visitEnd();
}
Also used : FieldVisitor(org.objectweb.asm.FieldVisitor)

Aggregations

FieldVisitor (org.objectweb.asm.FieldVisitor)90 MethodVisitor (org.objectweb.asm.MethodVisitor)59 Label (org.objectweb.asm.Label)33 ClassWriter (org.objectweb.asm.ClassWriter)28 AnnotationVisitor (org.objectweb.asm.AnnotationVisitor)9 ClassReader (org.objectweb.asm.ClassReader)8 Type (org.objectweb.asm.Type)7 Method (java.lang.reflect.Method)6 ClassVisitor (org.objectweb.asm.ClassVisitor)6 IOException (java.io.IOException)4 GeneratorAdapter (org.objectweb.asm.commons.GeneratorAdapter)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 LitString (lucee.transformer.expression.literal.LitString)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 PrintWriter (java.io.PrintWriter)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 URL (java.net.URL)2