Example usage for org.objectweb.asm Opcodes INVOKESPECIAL

List of usage examples for org.objectweb.asm Opcodes INVOKESPECIAL

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes INVOKESPECIAL.

Prototype

int INVOKESPECIAL

To view the source code for org.objectweb.asm Opcodes INVOKESPECIAL.

Click Source Link

Usage

From source file:com.nginious.http.xsp.XspCompiler.java

License:Apache License

/**
 * Creates subclass of {@link XspService} for the XSP file represented by the specified document
 * tree node structure./*from  w ww  .  jav  a  2  s . c  o  m*/
 * 
 * @param document the document tree node structure
 * @param srcFilePath the XSP file source path
 * @return a descriptor for the generated subclass
 * @throws XspException if unable to create subclass
 */
private ClassDescriptor compileService(DocumentPart document, String srcFilePath) throws XspException {
    ClassWriter writer = new ClassWriter(0);

    // Create class
    String packageName = document.getMetaContent("package");
    String intServiceClazzName = createIntServiceClassName(packageName, srcFilePath);
    String serviceClazzName = createServiceClassName(packageName, srcFilePath);
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intServiceClazzName, "Lcom/nginious/http/xsp/XspService;",
            "com/nginious/http/xsp/XspService", null);

    // Create constructor
    createConstructor(writer, "com/nginious/http/xsp/XspService");

    // Create xsp service method
    MethodVisitor visitor = createXspMethod(writer);

    Label tryLabel = new Label();
    Label startCatchLabel = new Label();
    Label endCatchLabel = new Label();

    // Start try block
    visitor.visitTryCatchBlock(tryLabel, startCatchLabel, endCatchLabel, "java/lang/Throwable");

    visitor.visitLabel(tryLabel);

    visitor.visitTypeInsn(Opcodes.NEW, "com/nginious/http/xsp/expr/HttpRequestVariables");
    visitor.visitInsn(Opcodes.DUP);
    visitor.visitVarInsn(Opcodes.ALOAD, 1);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/expr/HttpRequestVariables", "<init>",
            "(Lcom/nginious/http/HttpRequest;)V");
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "setVariables",
            "(Lcom/nginious/http/xsp/expr/Variables;)V");

    document.compile(intServiceClazzName, writer, visitor);

    visitor.visitLabel(startCatchLabel);
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "removeVariables",
            "()V");

    visitor.visitLdcInsn(true);
    visitor.visitInsn(Opcodes.IRETURN);

    // Start finally block
    visitor.visitLabel(endCatchLabel);
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "removeVariables",
            "()V");
    visitor.visitInsn(Opcodes.ATHROW);

    visitor.visitMaxs(12, 12);
    visitor.visitEnd();

    document.compileMethod(intServiceClazzName, writer);

    writer.visitEnd();
    byte[] clazzBytes = writer.toByteArray();
    return new ClassDescriptor(serviceClazzName, clazzBytes);
}

From source file:com.nginious.http.xsp.XspCompiler.java

License:Apache License

/**
 * Creates a constructor with no arguments for the XSP service class being created with the
 * specified class writer. Bytecode is created for calling the superclass constructor in the
 * superclass with the specified supperclass name.
 * /*from   w  w  w  .j  a v a  2s  .c  om*/
 * @param writer the class writer
 * @param superclassName the superclass name
 * @see XspService
 */
void createConstructor(ClassWriter writer, String superclassName) {
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    visitor.visitCode();
    visitor.visitVarInsn(Opcodes.ALOAD, 0);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassName, "<init>", "()V");
    visitor.visitInsn(Opcodes.RETURN);
    visitor.visitMaxs(1, 1);
    visitor.visitEnd();
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

License:Apache License

/**
 *
 * //from   www .j  a  v a 2s.c o  m
 *
 * @param cw
 * @param mv
 * @param processorName com/nway/commons/dbutils/DynamicBeanProcessorImpl
 * @param beanName com/nway/commons/dbutils/test/User
 * @return [0]:bean[1]createBean
 */
private Object[] prepScript(ClassWriter cw, MethodVisitor mv, String processorName, String beanName) {

    Object[] lab = new Object[2];

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, processorName, null,
            "com/nway/spring/jdbc/bean/DbBeanFactory", null);

    cw.visitSource(processorName.substring(processorName.lastIndexOf('/') + 1) + ".java", null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(6, l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nway/spring/jdbc/bean/DbBeanFactory", "<init>", "()V",
                false);
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + processorName + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "createBean",
                "(Ljava/sql/ResultSet;Ljava/lang/Class;)Ljava/lang/Object;",
                "<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;",
                new String[] { "java/sql/SQLException" });
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(10, l0);
        mv.visitTypeInsn(Opcodes.NEW, beanName);
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, beanName, "<init>", "()V", false);
        mv.visitVarInsn(Opcodes.ASTORE, 3);

        lab[0] = l0;
        lab[1] = mv;
    }

    return lab;
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java

License:Open Source License

/**
 * Calls a constructor with a set of arguments. After execution the stack should have an extra item pushed on it: the object that was
 * created by this constructor./*  www  .j  ava2 s  .  c  o m*/
 * @param constructor constructor to call
 * @param args constructor argument instruction lists -- each instruction list must leave one item on the stack of the type expected
 * by the constructor
 * @return instructions to invoke a constructor
 * @throws NullPointerException if any argument is {@code null} or array contains {@code null}
 * @throws IllegalArgumentException if the length of {@code args} doesn't match the number of parameters in {@code constructor}
 */
public static InsnList construct(Constructor<?> constructor, InsnList... args) {
    Validate.notNull(constructor);
    Validate.notNull(args);
    Validate.noNullElements(args);
    Validate.isTrue(constructor.getParameterCount() == args.length);

    InsnList ret = new InsnList();

    Type clsType = Type.getType(constructor.getDeclaringClass());
    Type methodType = Type.getType(constructor);

    ret.add(new TypeInsnNode(Opcodes.NEW, clsType.getInternalName()));
    ret.add(new InsnNode(Opcodes.DUP));
    for (InsnList arg : args) {
        ret.add(arg);
    }
    ret.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, clsType.getInternalName(), "<init>",
            methodType.getDescriptor(), false));

    return ret;
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java

License:Open Source License

/**
 * Generates instructions to throw an exception of type {@link RuntimeException} with a constant message.
 * @param message message of exception/*from w  w  w.  j  ava  2s.c om*/
 * @return instructions to throw an exception
 * @throws NullPointerException if any argument is {@code null}
 */
public static InsnList throwException(String message) {
    Validate.notNull(message);

    InsnList ret = new InsnList();

    ret.add(new TypeInsnNode(Opcodes.NEW, "java/lang/RuntimeException"));
    ret.add(new InsnNode(Opcodes.DUP));
    ret.add(new LdcInsnNode(message));
    ret.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>",
            "(Ljava/lang/String;)V", false));
    ret.add(new InsnNode(Opcodes.ATHROW));

    return ret;
}

From source file:com.offbynull.coroutines.instrumenter.asm.MethodInvokeUtils.java

License:Open Source License

/**
 * Get the number of arguments required for an invocation of some method. This includes the 'this' argument for non-static methods.
 * <p>/* www .ja va 2  s  .c  om*/
 * NOTE THAT THIS IS NOT THE NUMBER OF ITEMS ON THE STACK. If the method takes in doubles or longs, each double or long encountered
 * would be 2 items on the stack. This method returns the number of arguments required for the method to be invoked, not the number of
 * items required to be on the stack for the method to be invoked.
 * @param invokeNode the invocation instruction (either normal invocation or invokedynamic)
 * @return number of arguments required by this method
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if {@code invokeNode} is neither of type {@link MethodInsnNode} nor {@link InvokeDynamicInsnNode},
 * or if type of invocation ({@link MethodInsnNode}) cannot be determined
 */
public static int getArgumentCountRequiredForInvocation(AbstractInsnNode invokeNode) {
    Validate.notNull(invokeNode);

    if (invokeNode instanceof MethodInsnNode) {
        MethodInsnNode methodInsnNode = (MethodInsnNode) invokeNode;
        int extra;
        int paramCount;

        switch (methodInsnNode.getOpcode()) {
        case Opcodes.INVOKEVIRTUAL:
        case Opcodes.INVOKESPECIAL:
        case Opcodes.INVOKEINTERFACE:
            extra = 1;
            break;
        case Opcodes.INVOKESTATIC:
            extra = 0;
            break;
        default:
            throw new IllegalArgumentException(); // unknown invocation type? probably badly generated instruction node
        }
        Type methodType = Type.getType(methodInsnNode.desc);
        paramCount = methodType.getArgumentTypes().length;

        return paramCount + extra;
    } else if (invokeNode instanceof InvokeDynamicInsnNode) {
        InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) invokeNode;
        int paramCount;

        Type methodType = Type.getType(invokeDynamicInsnNode.desc);
        paramCount = methodType.getArgumentTypes().length;

        return paramCount;
    } else {
        throw new IllegalArgumentException();
    }
}

From source file:com.offbynull.coroutines.instrumenter.asm.SearchUtils.java

License:Open Source License

/**
 * Get the number of items that need to be on the stack for an invocation of some method.
 * @param invokeNode the invocation instruction (either normal invocation or invokedynamic)
 * @return number of items required on the stack for this method
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if {@code invokeNode} is neither of type {@link MethodInsnNode} nor {@link InvokeDynamicInsnNode},
 * or if type of invocation ({@link MethodInsnNode}) cannot be determined
 *//*  w w w .  j a  va2 s .  c om*/
public static int getRequiredStackCountForInvocation(AbstractInsnNode invokeNode) {
    Validate.notNull(invokeNode);

    if (invokeNode instanceof MethodInsnNode) {
        MethodInsnNode methodInsnNode = (MethodInsnNode) invokeNode;
        int extra;
        int paramCount;

        switch (methodInsnNode.getOpcode()) {
        case Opcodes.INVOKEVIRTUAL:
        case Opcodes.INVOKESPECIAL:
        case Opcodes.INVOKEINTERFACE:
            extra = 1;
            break;
        case Opcodes.INVOKESTATIC:
            extra = 0;
            break;
        default:
            throw new IllegalArgumentException(); // unknown invocation type? probably badly generated instruction node
        }
        Type methodType = Type.getType(methodInsnNode.desc);
        paramCount = methodType.getArgumentTypes().length;

        return paramCount + extra;
    } else if (invokeNode instanceof InvokeDynamicInsnNode) {
        InvokeDynamicInsnNode invokeDynamicInsnNode = (InvokeDynamicInsnNode) invokeNode;
        int paramCount;

        Type methodType = Type.getType(invokeDynamicInsnNode.desc);
        paramCount = methodType.getArgumentTypes().length;

        return paramCount;
    } else {
        throw new IllegalArgumentException();
    }
}

From source file:com.offbynull.coroutines.instrumenter.generators.GenericGenerators.java

License:Open Source License

/**
 * Generates instructions to throw an exception of type {@link RuntimeException} with a constant message.
 * @param message message of exception//from   w  w w .  jav a 2  s .  c om
 * @return instructions to throw an exception
 * @throws NullPointerException if any argument is {@code null}
 */
public static InsnList throwRuntimeException(String message) {
    Validate.notNull(message);

    InsnList ret = new InsnList();

    ret.add(new TypeInsnNode(Opcodes.NEW, "java/lang/RuntimeException"));
    ret.add(new InsnNode(Opcodes.DUP));
    ret.add(new LdcInsnNode(message));
    ret.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>",
            "(Ljava/lang/String;)V", false));
    ret.add(new InsnNode(Opcodes.ATHROW));

    return ret;
}

From source file:com.sixrr.metrics.profile.instanceHolder.MetricInstanceHolder.java

License:Apache License

private void loadMetricsFromProviders() {
    for (MetricProvider provider : MetricProvider.EXTENSION_POINT_NAME.getExtensions()) {
        final List<Class<? extends Metric>> classesForProvider = provider.getMetricClasses();

        for (Class<? extends Metric> aClass : classesForProvider) {
            try {
                myMetricInstances.put(aClass.getName(), aClass.newInstance());
            } catch (InstantiationException e) {
                MetricInstanceHolder.LOGGER.error(e);
            } catch (IllegalAccessException e) {
                MetricInstanceHolder.LOGGER.error(e);
            }//from   w  w  w .  java2 s.c o  m
        }
    }

    for (Metric metric : Metric.EP_NAME.getExtensions()) {
        myMetricInstances.put(metric.getClass().getName(), metric);
    }

    // add some magic
    // in Profiles it stored by ClassName. Line Of code is can be handle without new metrics, need only extends  LinesOfCodeProjectMetric with
    // new name
    for (LineOfCodeFileTypeProviderEP ep : LineOfCodeFileTypeProviderEP.EP_NAME.getExtensions()) {
        FileType fileTypeByFileName = FileTypeRegistry.getInstance().findFileTypeByName(ep.fileType);

        if (fileTypeByFileName == null) {
            LOGGER.error("File type is unknown: " + ep.fileType);
            fileTypeByFileName = PlainTextFileType.INSTANCE;
        }
        String lineOfCodeClass = Type.getInternalName(LinesOfCodeProjectMetric.class);
        String className = lineOfCodeClass + "$" + ep.fileType;

        ClassWriter writer = new ClassWriter(Opcodes.F_FULL);
        writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, lineOfCodeClass, null);

        String desc = Type.getConstructorDescriptor(LinesOfCodeProjectMetric.class.getConstructors()[0]);
        MethodVisitor methodVisitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, null, null);

        methodVisitor.visitMaxs(2, 2);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, lineOfCodeClass, "<init>", desc);
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitEnd();
        writer.visitEnd();

        Class<?> aClass = defineClass(className.replace("/", "."), writer.toByteArray());

        try {
            myMetricInstances.put(aClass.getName(),
                    (Metric) aClass.getConstructors()[0].newInstance(fileTypeByFileName));
        } catch (InstantiationException e) {
            LOGGER.error(e);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e);
        }
    }
}

From source file:com.spotify.missinglink.ClassLoader.java

License:Apache License

private static void handleMethodCall(Set<CalledMethod> thisCalls, int lineNumber, MethodInsnNode insn) {
    boolean isStatic;
    switch (insn.getOpcode()) {
    case Opcodes.INVOKEVIRTUAL:
    case Opcodes.INVOKEINTERFACE:
        isStatic = false;//  www.  j a  v a2 s.c  o m
        break;
    case Opcodes.INVOKESPECIAL:
        isStatic = false;
        break;
    case Opcodes.INVOKESTATIC:
        isStatic = true;
        break;
    default:
        throw new RuntimeException("Unexpected method call opcode: " + insn.getOpcode());
    }
    if (insn.owner.charAt(0) != '[') {
        thisCalls.add(new CalledMethodBuilder().owner(TypeDescriptors.fromClassName(insn.owner))
                .descriptor(MethodDescriptors.fromDesc(insn.desc, insn.name)).isStatic(isStatic)
                .lineNumber(lineNumber).build());
    }
}