Example usage for org.objectweb.asm MethodVisitor visitCode

List of usage examples for org.objectweb.asm MethodVisitor visitCode

Introduction

In this page you can find the example usage for org.objectweb.asm MethodVisitor visitCode.

Prototype

public void visitCode() 

Source Link

Document

Starts the visit of the method's code, if any (i.e.

Usage

From source file:fr.insalyon.citi.golo.compiler.JavaBytecodeUnionGenerator.java

License:Apache License

private void makeToString(ClassWriter classWriter, Union.Value value) {
    MethodVisitor visitor = classWriter.visitMethod(ACC_PUBLIC, "toString", "()Ljava/lang/String;", null, null);
    visitor.visitCode();
    if (!value.hasMembers()) {
        visitor.visitLdcInsn(// ww w  .j  a  v a  2 s  . c  o m
                "union " + value.getUnion().getPackageAndClass().className() + "." + value.getName());
    } else {
        visitor.visitTypeInsn(NEW, "java/lang/StringBuilder");
        visitor.visitInsn(DUP);
        visitor.visitLdcInsn(
                "union " + value.getUnion().getPackageAndClass().className() + "." + value.getName() + "{");
        visitor.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V",
                false);
        visitor.visitVarInsn(ASTORE, 1);
        boolean first = true;
        for (String member : value.getMembers()) {
            visitor.visitVarInsn(ALOAD, 1);
            visitor.visitLdcInsn((first ? "" : ", ") + member + "=");
            visitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                    "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
            visitor.visitInsn(POP);

            visitor.visitVarInsn(ALOAD, 1);
            visitor.visitVarInsn(ALOAD, 0);
            visitor.visitFieldInsn(GETFIELD, value.getPackageAndClass().toJVMType(), member,
                    "Ljava/lang/Object;");
            visitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                    "(Ljava/lang/Object;)Ljava/lang/StringBuilder;", false);
            visitor.visitInsn(POP);
            first = false;
        }

        visitor.visitVarInsn(ALOAD, 1);
        visitor.visitLdcInsn("}");
        visitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
        visitor.visitInsn(POP);
        visitor.visitVarInsn(ALOAD, 1);
        visitor.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;",
                false);
    }
    visitor.visitInsn(ARETURN);
    visitor.visitMaxs(0, 0);
    visitor.visitEnd();
}

From source file:fr.insalyon.citi.golo.compiler.JavaBytecodeUnionGenerator.java

License:Apache License

private void makeEquals(ClassWriter cw, Union.Value value) {
    String target = value.getPackageAndClass().toJVMType();
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "equals", "(Ljava/lang/Object;)Z", null, null);
    Label notSameInstance = new Label();
    Label notNull = new Label();
    Label sameType = new Label();
    Label allAttrsEquals = new Label();
    Label attrNotEqual = new Label();
    mv.visitCode();

    // if (other == this) { return true; }
    mv.visitVarInsn(ALOAD, 1);/*w  w w  . j a  v  a 2 s.c om*/
    mv.visitVarInsn(ALOAD, 0);
    mv.visitJumpInsn(IF_ACMPNE, notSameInstance);
    mv.visitInsn(ICONST_1);
    mv.visitInsn(IRETURN);
    mv.visitLabel(notSameInstance);

    // if (other == null) { return false; }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitJumpInsn(IFNONNULL, notNull);
    mv.visitInsn(ICONST_0);
    mv.visitInsn(IRETURN);
    mv.visitLabel(notNull);

    // if (!(other instanceof <value>)) { return false; }
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(INSTANCEOF, target);
    mv.visitJumpInsn(IFNE, sameType);
    mv.visitInsn(ICONST_0);
    mv.visitInsn(IRETURN);
    mv.visitLabel(sameType);

    // cast other to <value>
    mv.visitVarInsn(ALOAD, 1);
    mv.visitTypeInsn(CHECKCAST, target);
    mv.visitVarInsn(ASTORE, 2);

    // java.util.Objects.equals(<member>, other.<member>)
    for (String member : value.getMembers()) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, target, member, "Ljava/lang/Object;");
        mv.visitVarInsn(ALOAD, 2);
        mv.visitFieldInsn(GETFIELD, target, member, "Ljava/lang/Object;");
        mv.visitMethodInsn(INVOKESTATIC, "java/util/Objects", "equals",
                "(Ljava/lang/Object;Ljava/lang/Object;)Z", false);
        mv.visitJumpInsn(IFEQ, attrNotEqual);
    }
    mv.visitInsn(ICONST_1);
    mv.visitJumpInsn(GOTO, allAttrsEquals);
    mv.visitLabel(attrNotEqual);
    mv.visitInsn(ICONST_0);
    mv.visitLabel(allAttrsEquals);
    mv.visitInsn(IRETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:fr.insalyon.citi.golo.compiler.JavaBytecodeUnionGenerator.java

License:Apache License

private void makeHashCode(ClassWriter cw, Union.Value value) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "hashCode", "()I", null, null);
    mv.visitCode();
    loadInteger(mv, value.getMembers().size());
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
    int i = 0;//  w w w . j  av a 2  s.c  o m
    for (String member : value.getMembers()) {
        mv.visitInsn(DUP);
        loadInteger(mv, i);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, value.getPackageAndClass().toJVMType(), member, "Ljava/lang/Object;");
        mv.visitInsn(AASTORE);
    }
    mv.visitMethodInsn(INVOKESTATIC, "java/util/Objects", "hash", "([Ljava/lang/Object;)I", false);
    mv.visitInsn(IRETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:fr.insalyon.citi.golo.compiler.JavaBytecodeUnionGenerator.java

License:Apache License

private void makeValuedConstructor(ClassWriter cw, Union.Value value) {
    MethodVisitor mv = cw.visitMethod(ACC_PROTECTED, "<init>", argsSignature(value.getMembers().size()) + "V",
            null, null);//from  w  ww  . j a v  a 2 s.c o m
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, value.getUnion().getPackageAndClass().toJVMType(), "<init>", "()V",
            false);
    int idx = 1;
    for (String member : value.getMembers()) {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, idx++);
        mv.visitFieldInsn(PUTFIELD, value.getPackageAndClass().toJVMType(), member, "Ljava/lang/Object;");
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:fr.insalyon.citi.golo.runtime.adapters.JavaBytecodeAdapterGenerator.java

License:Apache License

private void makeFrontendOverrides(ClassWriter classWriter, AdapterDefinition adapterDefinition) {
    for (Method method : getAllVirtualMethods(adapterDefinition)) {
        int access = isPublic(method.getModifiers()) ? ACC_PUBLIC : ACC_PROTECTED;
        if (method.isVarArgs()) {
            access = access & ACC_VARARGS;
        }//from  w w  w  .ja va  2 s .c  o m
        String name = method.getName();
        String descriptor = Type.getMethodDescriptor(method);
        Class<?>[] exceptionTypes = method.getExceptionTypes();
        String[] exceptions = new String[exceptionTypes.length];
        for (int i = 0; i < exceptionTypes.length; i++) {
            exceptions[i] = Type.getInternalName(exceptionTypes[i]);
        }
        MethodVisitor methodVisitor = classWriter.visitMethod(access, name, descriptor, null, exceptions);
        methodVisitor.visitCode();
        Class<?>[] parameterTypes = method.getParameterTypes();
        Type[] indyTypes = new Type[parameterTypes.length + 1];
        indyTypes[0] = Type.getType(Object.class);
        methodVisitor.visitVarInsn(ALOAD, 0);
        int argIndex = 1;
        for (int i = 0; i < parameterTypes.length; i++) {
            argIndex = loadArgument(methodVisitor, parameterTypes[i], argIndex);
            indyTypes[i + 1] = Type.getType(parameterTypes[i]);
        }
        methodVisitor.visitInvokeDynamicInsn(method.getName(),
                Type.getMethodDescriptor(Type.getReturnType(method), indyTypes), ADAPTER_HANDLE);
        makeReturn(methodVisitor, method.getReturnType());
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
    }
}

From source file:fr.insalyon.citi.golo.runtime.adapters.JavaBytecodeAdapterGenerator.java

License:Apache License

private void makeConstructors(ClassWriter classWriter, AdapterDefinition adapterDefinition) {
    try {//  w w  w .  j  av a  2 s  .c o m
        Class<?> parentClass = Class.forName(adapterDefinition.getParent(), true,
                adapterDefinition.getClassLoader());
        for (Constructor constructor : parentClass.getDeclaredConstructors()) {
            if (Modifier.isPublic(constructor.getModifiers())
                    || Modifier.isProtected(constructor.getModifiers())) {
                Class[] parameterTypes = constructor.getParameterTypes();
                Type[] adapterParameterTypes = new Type[parameterTypes.length + 1];
                adapterParameterTypes[0] = Type.getType(AdapterDefinition.class);
                for (int i = 1; i < adapterParameterTypes.length; i++) {
                    adapterParameterTypes[i] = Type.getType(parameterTypes[i - 1]);
                }
                String descriptor = Type.getMethodDescriptor(Type.VOID_TYPE, adapterParameterTypes);
                MethodVisitor methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", descriptor, null,
                        null);
                methodVisitor.visitCode();
                methodVisitor.visitVarInsn(ALOAD, 0);
                methodVisitor.visitVarInsn(ALOAD, 1);
                methodVisitor.visitFieldInsn(PUTFIELD, jvmType(adapterDefinition.getName()), DEFINITION_FIELD,
                        "Lfr/insalyon/citi/golo/runtime/adapters/AdapterDefinition;");
                methodVisitor.visitVarInsn(ALOAD, 0);
                int argIndex = 2;
                for (Class parameterType : parameterTypes) {
                    argIndex = loadArgument(methodVisitor, parameterType, argIndex);
                }
                methodVisitor.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(parentClass), "<init>",
                        Type.getConstructorDescriptor(constructor));
                methodVisitor.visitInsn(RETURN);
                methodVisitor.visitMaxs(0, 0);
                methodVisitor.visitEnd();
            }
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.liglab.adele.cilia.dependency.ProxyGenerator.java

License:Apache License

/**
 * Generates a delegated method.//from w ww .  j  av a 2  s  .  c o m
 *
 * @param cw        the class writer
 * @param method    the method object to delegate
 * @param className the generated class name
 * @param itfName   the internal specification class name
 */
private static void generateDelegator(ClassWriter cw, Method method, String className, String itfName) {
    String methodName = method.getName();
    String desc = Type.getMethodDescriptor(method);
    String[] exceptions = getInternalClassNames(method.getExceptionTypes());
    int modifiers = method.getModifiers() & ~(Modifier.ABSTRACT | Modifier.NATIVE | Modifier.SYNCHRONIZED);
    Type[] types = Type.getArgumentTypes(method);

    int freeRoom = 1;
    for (int t = 0; t < types.length; t++) {
        freeRoom = freeRoom + types[t].getSize();
    }

    MethodVisitor mv = cw.visitMethod(modifiers, methodName, desc, null, exceptions);
    mv.visitCode();

    mv.visitVarInsn(ALOAD, 0);
    mv.visitFieldInsn(GETFIELD, className, DEPENDENCY, DEPENDENCY_DESC); // The dependency is on the stack.
    mv.visitMethodInsn(INVOKEVIRTUAL, DEPENDENCY_INTERNAL_NAME, "getService", // Call getService
            "()Ljava/lang/Object;"); // The service object is on the stack.
    int varSvc = freeRoom;
    freeRoom = freeRoom + 1; // Object Reference.
    mv.visitVarInsn(ASTORE, varSvc); // Store the service object.

    Label notNull = new Label();
    Label isNull = new Label();
    mv.visitVarInsn(ALOAD, varSvc); // Load the service
    mv.visitJumpInsn(IFNONNULL, notNull); // If not null go to not null
    // Null branch - throw the exception
    mv.visitLabel(isNull);
    mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
    mv.visitInsn(DUP);
    mv.visitLdcInsn("No service available");
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "(Ljava/lang/String;)V");
    mv.visitInsn(ATHROW);
    // End of the null branch

    // Not null, go one the execution
    mv.visitLabel(notNull);

    // Invoke the method on the service object.
    mv.visitVarInsn(ALOAD, varSvc);
    // Push argument on the stack.
    int i = 1; // Arguments. (non static method)
    for (int t = 0; t < types.length; t++) {
        mv.visitVarInsn(types[t].getOpcode(ILOAD), i);
        i = i + types[t].getSize();
    }
    // Invocation
    mv.visitMethodInsn(INVOKEINTERFACE, itfName, methodName, desc);

    // Return the result
    Type returnType = Type.getReturnType(desc);
    if (returnType.getSort() != Type.VOID) {
        mv.visitInsn(returnType.getOpcode(IRETURN));
    } else {
        mv.visitInsn(RETURN);
    }

    // End of the method.
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:fr.liglab.adele.cilia.dependency.ProxyGenerator.java

License:Apache License

/**
 * Generates the constructors. The constructor receives a dependency
 * and set the {@link ProxyGenerator#DEPENDENCY} field.
 *
 * @param cw        the class writer/*www .ja  va 2 s . c om*/
 * @param className the generated class name.
 */
private static void generateConstructor(ClassWriter cw, String className, String parent) {
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", '(' + DEPENDENCY_DESC + ")V", null, null);
    mv.visitCode();

    mv.visitVarInsn(ALOAD, 0); // Load this
    mv.visitInsn(DUP); // Dup
    mv.visitMethodInsn(INVOKESPECIAL, parent, "<init>", "()V"); // Call  super
    mv.visitVarInsn(ALOAD, 1); // Load the argument
    mv.visitFieldInsn(PUTFIELD, className, DEPENDENCY, DEPENDENCY_DESC); // Assign the dependency field
    mv.visitInsn(RETURN); // Return void

    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:global.namespace.neuron.di.internal.ProxyClassVisitor.java

License:Apache License

private void insertConstructor() {
    final MethodVisitor mv = cv.visitMethod(ACC_PRIVATE_SYNTHETIC, CONSTRUCTOR_NAME,
            ACCEPTS_NOTHING_AND_RETURNS_VOID_DESC, null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);// ww w.  ja  va  2s  . c  o m
    mv.visitMethodInsn(INVOKESPECIAL, superName, CONSTRUCTOR_NAME, ACCEPTS_NOTHING_AND_RETURNS_VOID_DESC,
            false);
    for (final Method method : bindableMethods) {
        if (0 == (method.getModifiers() & ACC_ABSTRACT)) {
            final Class<?> declaringClass = method.getDeclaringClass();
            final boolean isInterface = declaringClass.isInterface();
            final String owner = getInternalName(declaringClass);
            final String name = method.getName();
            final String desc = getMethodDescriptor(method);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitInvokeDynamicInsn("get", "(" + proxyDesc + ")" + dependencyProviderDesc, metaFactoryHandle,
                    acceptsNothingAndReturnsObjectType,
                    new Handle(H_INVOKESPECIAL, owner, name, desc, isInterface),
                    acceptsNothingAndReturnsObjectType);
            mv.visitFieldInsn(PUTFIELD, proxyName, name + PROVIDER, dependencyProviderDesc);
        }
    }
    mv.visitInsn(RETURN);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
}

From source file:global.namespace.neuron.di.internal.ProxyClassVisitor.java

License:Apache License

private void insertMethods() {
    for (final Method method : bindableMethods) {
        new Object() {

            final int access = method.getModifiers() & ~ACC_ABSTRACT_NATIVE | ACC_SYNTHETIC;
            final String name = method.getName();
            final String desc = getMethodDescriptor(method);

            final Class<?> returnType = method.getReturnType();
            final String returnTypeName = getInternalName(returnType);
            final String returnTypeDesc = getDescriptor(returnType);

            final Class<?> boxedReturnType = boxed(returnType);
            final String boxedReturnTypeName = getInternalName(boxedReturnType);
            final String boxedReturnTypeDesc = getDescriptor(boxedReturnType);

            final int returnOpCode = returnOpCode(method);

            {/* w  w  w .j  a  v a  2 s  .  com*/
                generateProxyField();
                generateProxyCallMethod();
            }

            void generateProxyField() {
                cv.visitField(ACC_PRIVATE_SYNTHETIC, name + PROVIDER, dependencyProviderDesc, null, null)
                        .visitEnd();
            }

            void generateProxyCallMethod() {
                final MethodVisitor mv = beginMethod(name);
                mv.visitFieldInsn(GETFIELD, proxyName, name + PROVIDER, dependencyProviderDesc);
                mv.visitMethodInsn(INVOKEINTERFACE, dependencyProviderName, "get",
                        ACCEPTS_NOTHING_AND_RETURNS_OBJECT_DESC, true);
                if (!boxedReturnType.isAssignableFrom(Object.class)) {
                    mv.visitTypeInsn(CHECKCAST,
                            boxedReturnType.isArray() ? boxedReturnTypeDesc : boxedReturnTypeName);
                }
                if (boxedReturnType != returnType) {
                    assert !returnType.isArray();
                    mv.visitMethodInsn(INVOKEVIRTUAL, boxedReturnTypeName, returnTypeName.concat("Value"),
                            "()".concat(returnTypeDesc), false);
                }
                endMethod(mv);
            }

            MethodVisitor beginMethod(final String name) {
                final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null);
                mv.visitCode();
                mv.visitVarInsn(ALOAD, 0);
                return mv;
            }

            void endMethod(final MethodVisitor mv) {
                mv.visitInsn(returnOpCode);
                mv.visitMaxs(-1, -1);
                mv.visitEnd();
            }
        };
    }
}