Example usage for org.objectweb.asm MethodVisitor visitTryCatchBlock

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

Introduction

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

Prototype

public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) 

Source Link

Document

Visits a try catch block.

Usage

From source file:org.springsource.loaded.SystemClassReflectionRewriter.java

License:Apache License

public static void generateJLCGDFS(ClassWriter cw, String classname) {
    FieldVisitor fv = cw.visitField(ACC_PUBLIC_STATIC, "__sljlcgdfs", "Ljava/lang/reflect/Method;", null, null);
    fv.visitEnd();//from  w  w  w .j  a v a  2  s  .c o m

    MethodVisitor mv = cw.visitMethod(ACC_PRIVATE + ACC_STATIC, "__sljlcgdfs",
            "(Ljava/lang/Class;)[Ljava/lang/reflect/Field;", null, null);
    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
    Label l3 = new Label();
    mv.visitLabel(l3);
    mv.visitFieldInsn(GETSTATIC, classname, "__sljlcgdfs", "Ljava/lang/reflect/Method;");
    mv.visitJumpInsn(IFNONNULL, l0);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getDeclaredFields", "()[Ljava/lang/reflect/Field;",
            false);
    mv.visitInsn(ARETURN);
    mv.visitLabel(l0);
    mv.visitFieldInsn(GETSTATIC, classname, "__sljlcgdfs", "Ljava/lang/reflect/Method;");
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ICONST_1);
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
    mv.visitInsn(DUP);
    mv.visitInsn(ICONST_0);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitInsn(AASTORE);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/reflect/Method", "invoke",
            "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;", false);
    mv.visitTypeInsn(CHECKCAST, "[Ljava/lang/reflect/Field;");
    mv.visitLabel(l1);
    mv.visitInsn(ARETURN);
    mv.visitLabel(l2);
    mv.visitVarInsn(ASTORE, 1);
    Label l5 = new Label();
    mv.visitLabel(l5);
    mv.visitInsn(ACONST_NULL);
    mv.visitInsn(ARETURN);
    Label l6 = new Label();
    mv.visitLabel(l6);
    //      mv.visitLocalVariable("clazz", "Ljava/lang/Class;", "Ljava/lang/Class<*>;", l3, l6, 0);
    //      mv.visitLocalVariable("e", "Ljava/lang/Exception;", null, l5, l6, 1);
    mv.visitMaxs(6, 2);
    mv.visitEnd();
}

From source file:org.teiid.jboss.rest.RestASMBasedWebArchiveBuilder.java

License:Open Source License

private void buildRestService(String vdbName, int vdbVersion, String modelName, Procedure procedure,
        String method, String uri, ClassWriter cw, String contentType, String charSet,
        boolean passthroughAuth) {

    List<ProcedureParameter> params = new ArrayList<ProcedureParameter>(procedure.getParameters().size());
    boolean usingReturn = false;
    boolean hasLobInput = false;
    for (ProcedureParameter p : procedure.getParameters()) {
        if (p.getType() == Type.In || p.getType() == Type.InOut) {
            params.add(p);/*  w  w  w  .j a v  a  2s  . c o m*/
        } else if (p.getType() == Type.ReturnValue && procedure.getResultSet() == null) {
            usingReturn = true;
        }
        if (!hasLobInput) {
            String runtimeType = p.getRuntimeType();
            hasLobInput = DataTypeManager.isLOB(runtimeType);
        }
    }
    int paramsSize = params.size();
    MethodVisitor mv;

    boolean useMultipart = false;
    if (method.toUpperCase().equals("POST") && hasLobInput) {
        useMultipart = true;
    }

    AnnotationVisitor av0;
    {

        StringBuilder paramSignature = new StringBuilder();
        paramSignature.append("(");
        for (int i = 0; i < paramsSize; i++) {
            paramSignature.append("Ljava/lang/String;");
        }
        paramSignature.append(")");

        if (useMultipart) {
            mv = cw.visitMethod(ACC_PUBLIC, procedure.getName() + contentType.replace('/', '_'),
                    "(Lorg/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput;)Ljavax/ws/rs/core/StreamingOutput;",
                    null, new String[] { "javax/ws/rs/WebApplicationException" });
        } else {
            mv = cw.visitMethod(ACC_PUBLIC, procedure.getName() + contentType.replace('/', '_'),
                    paramSignature + "Ljavax/ws/rs/core/StreamingOutput;", null,
                    new String[] { "javax/ws/rs/WebApplicationException" });
        }
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/Produces;", true);
            {
                AnnotationVisitor av1 = av0.visitArray("value");
                av1.visit(null, contentType);
                av1.visitEnd();
            }
            av0.visitEnd();
        }
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/" + method.toUpperCase() + ";", true);
            av0.visitEnd();
        }
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/Path;", true);
            av0.visit("value", uri);
            av0.visitEnd();
        }
        {
            av0 = mv.visitAnnotation("Ljavax/annotation/security/PermitAll;", true);
            av0.visitEnd();
        }

        if (useMultipart) {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/Consumes;", true);
            {
                AnnotationVisitor av1 = av0.visitArray("value");
                av1.visit(null, "multipart/form-data");
                av1.visitEnd();
            }
            av0.visitEnd();
        }

        if (!useMultipart) {
            // post only accepts Form inputs, not path params
            HashSet<String> pathParms = getPathParameters(uri);
            for (int i = 0; i < paramsSize; i++) {
                String paramType = "Ljavax/ws/rs/FormParam;";
                if (method.toUpperCase().equals("GET")) {
                    paramType = "Ljavax/ws/rs/QueryParam;";
                }
                if (pathParms.contains(params.get(i).getName())) {
                    paramType = "Ljavax/ws/rs/PathParam;";
                }

                av0 = mv.visitParameterAnnotation(i, paramType, true);
                av0.visit("value", params.get(i).getName());
                av0.visitEnd();
            }
        }

        mv.visitCode();
        Label l0 = new Label();
        Label l1 = new Label();
        Label l2 = new Label();
        mv.visitTryCatchBlock(l0, l1, l2, "java/sql/SQLException");
        mv.visitLabel(l0);

        if (!useMultipart) {
            mv.visitTypeInsn(NEW, "java/util/LinkedHashMap");
            mv.visitInsn(DUP);
            mv.visitMethodInsn(INVOKESPECIAL, "java/util/LinkedHashMap", "<init>", "()V");

            mv.visitVarInsn(ASTORE, paramsSize + 1);
            for (int i = 0; i < paramsSize; i++) {
                mv.visitVarInsn(ALOAD, paramsSize + 1);
                mv.visitLdcInsn(params.get(i).getName());
                mv.visitVarInsn(ALOAD, i + 1);
                mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "put",
                        "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
                mv.visitInsn(POP);
            }
            mv.visitVarInsn(ALOAD, 0);
            mv.visitLdcInsn(vdbName);
            mv.visitIntInsn(BIPUSH, vdbVersion);

            mv.visitLdcInsn(procedure.getSQLString());

            mv.visitVarInsn(ALOAD, paramsSize + 1);
            mv.visitLdcInsn(charSet == null ? "" : charSet);
            mv.visitInsn(passthroughAuth ? ICONST_1 : ICONST_0);
            mv.visitInsn(usingReturn ? ICONST_1 : ICONST_0);
            mv.visitMethodInsn(INVOKEVIRTUAL, "org/teiid/jboss/rest/" + modelName, "execute",
                    "(Ljava/lang/String;ILjava/lang/String;Ljava/util/LinkedHashMap;Ljava/lang/String;ZZ)Ljavax/ws/rs/core/StreamingOutput;");
            mv.visitLabel(l1);
            mv.visitInsn(ARETURN);
            mv.visitLabel(l2);
            mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/sql/SQLException" });
            mv.visitVarInsn(ASTORE, paramsSize + 1);
            mv.visitTypeInsn(NEW, "javax/ws/rs/WebApplicationException");
            mv.visitInsn(DUP);
            mv.visitVarInsn(ALOAD, paramsSize + 1);
            mv.visitFieldInsn(GETSTATIC, "javax/ws/rs/core/Response$Status", "INTERNAL_SERVER_ERROR",
                    "Ljavax/ws/rs/core/Response$Status;");
            mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/WebApplicationException", "<init>",
                    "(Ljava/lang/Throwable;Ljavax/ws/rs/core/Response$Status;)V");
            mv.visitInsn(ATHROW);
            mv.visitMaxs(7, paramsSize + 2);
            mv.visitEnd();
        } else {
            mv.visitVarInsn(ALOAD, 0);
            mv.visitLdcInsn(vdbName);
            mv.visitIntInsn(BIPUSH, vdbVersion);
            mv.visitLdcInsn(procedure.getSQLString());
            mv.visitVarInsn(ALOAD, 1);
            mv.visitLdcInsn(charSet == null ? "" : charSet);
            mv.visitInsn(passthroughAuth ? ICONST_1 : ICONST_0);
            mv.visitInsn(usingReturn ? ICONST_1 : ICONST_0);
            mv.visitMethodInsn(INVOKEVIRTUAL, "org/teiid/jboss/rest/" + modelName, "executePost",
                    "(Ljava/lang/String;ILjava/lang/String;Lorg/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput;Ljava/lang/String;ZZ)Ljavax/ws/rs/core/StreamingOutput;");
            mv.visitLabel(l1);
            mv.visitInsn(ARETURN);
            mv.visitLabel(l2);
            mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/sql/SQLException" });
            mv.visitVarInsn(ASTORE, 2);
            mv.visitTypeInsn(NEW, "javax/ws/rs/WebApplicationException");
            mv.visitInsn(DUP);
            mv.visitVarInsn(ALOAD, 2);
            mv.visitFieldInsn(GETSTATIC, "javax/ws/rs/core/Response$Status", "INTERNAL_SERVER_ERROR",
                    "Ljavax/ws/rs/core/Response$Status;");
            mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/WebApplicationException", "<init>",
                    "(Ljava/lang/Throwable;Ljavax/ws/rs/core/Response$Status;)V");
            mv.visitInsn(ATHROW);
            mv.visitMaxs(8, 3);
            mv.visitEnd();
        }
    }
}

From source file:org.teiid.jboss.rest.RestASMBasedWebArchiveBuilder.java

License:Open Source License

private void buildQueryProcedure(String vdbName, int vdbVersion, String modelName, String context,
        ClassWriter cw, boolean passthroughAuth) {
    MethodVisitor mv;
    {/*from  ww w . ja v  a2  s .c o  m*/
        AnnotationVisitor av0;
        mv = cw.visitMethod(ACC_PUBLIC, "sqlQuery" + context,
                "(Ljava/lang/String;)Ljavax/ws/rs/core/StreamingOutput;", null, null);
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/Produces;", true);
            {
                AnnotationVisitor av1 = av0.visitArray("value");
                av1.visit(null, "application/" + context);
                av1.visitEnd();
            }
            av0.visitEnd();
        }
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/POST;", true);
            av0.visitEnd();
        }
        {
            av0 = mv.visitAnnotation("Ljavax/ws/rs/Path;", true);
            av0.visit("value", "/query");
            av0.visitEnd();
        }
        {
            av0 = mv.visitParameterAnnotation(0, "Ljavax/ws/rs/FormParam;", true);
            av0.visit("value", "sql");
            av0.visitEnd();
        }
        mv.visitCode();
        Label l0 = new Label();
        Label l1 = new Label();
        Label l2 = new Label();
        mv.visitTryCatchBlock(l0, l1, l2, "java/sql/SQLException");
        mv.visitLabel(l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitLdcInsn(vdbName);
        mv.visitIntInsn(BIPUSH, vdbVersion);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitInsn(context.equals("xml") ? ICONST_0 : ICONST_1);
        mv.visitInsn(passthroughAuth ? ICONST_1 : ICONST_0);
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/teiid/jboss/rest/" + modelName, "executeQuery",
                "(Ljava/lang/String;ILjava/lang/String;ZZ)Ljavax/ws/rs/core/StreamingOutput;");
        mv.visitLabel(l1);
        mv.visitInsn(ARETURN);
        mv.visitLabel(l2);
        mv.visitFrame(F_SAME1, 0, null, 1, new Object[] { "java/sql/SQLException" });
        mv.visitVarInsn(ASTORE, 2);
        mv.visitTypeInsn(NEW, "javax/ws/rs/WebApplicationException");
        mv.visitInsn(DUP);
        mv.visitVarInsn(ALOAD, 2);
        mv.visitFieldInsn(GETSTATIC, "javax/ws/rs/core/Response$Status", "INTERNAL_SERVER_ERROR",
                "Ljavax/ws/rs/core/Response$Status;");
        mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/WebApplicationException", "<init>",
                "(Ljava/lang/Throwable;Ljavax/ws/rs/core/Response$Status;)V");
        mv.visitInsn(ATHROW);
        mv.visitMaxs(6, 3);
        mv.visitEnd();
    }
}

From source file:org.yx.asm.ProxyMethodWritor.java

License:Apache License

public static void writeVoid(MethodVisitor mv, AsmMethod asmMethod) {
    Box db = asmMethod.method.getAnnotation(Box.class);
    if (db == null) {
        return;/*from w w w.  jav  a2  s  .c o  m*/
    }
    String superowener = Type.getInternalName(asmMethod.superClz);
    String currentClz = asmMethod.currentClz.replace('.', '/');

    List<Object> argTypes = AsmUtils.getImplicitFrame(
            asmMethod.desc.substring(asmMethod.desc.indexOf("(") + 1, asmMethod.desc.indexOf(")")));
    int localVariableIndex = argLength(argTypes);

    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
    Label l3 = new Label();
    Label l4 = new Label();
    mv.visitTryCatchBlock(l0, l3, l4, null);
    mv.visitTypeInsn(NEW, AOPEXCUTOR);
    mv.visitInsn(DUP);
    mv.visitInsn(db.embed() ? ICONST_1 : ICONST_0);
    mv.visitMethodInsn(INVOKESPECIAL, AOPEXCUTOR, "<init>", "(Z)V", false);
    mv.visitVarInsn(ASTORE, localVariableIndex + 1);
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitLdcInsn(db.dbName());
    mv.visitFieldInsn(GETSTATIC, "org/yx/db/DBType", db.dbType().toString(), "Lorg/yx/db/DBType;");
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "begin", "(Ljava/lang/String;Lorg/yx/db/DBType;)V", false);
    mv.visitVarInsn(ALOAD, 0);

    loadArgs(mv, argTypes, 0);
    mv.visitMethodInsn(INVOKESPECIAL, superowener, asmMethod.name, asmMethod.desc, false);

    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "commit", "()V", false);
    mv.visitLabel(l1);
    Label l5 = new Label();
    mv.visitJumpInsn(GOTO, l5);
    mv.visitLabel(l2);

    List<Object> list = new ArrayList<Object>();
    list.add(currentClz);
    list.addAll(argTypes);
    list.add(AOPEXCUTOR);
    Object[] frames = list.toArray(new Object[list.size()]);
    mv.visitFrame(Opcodes.F_FULL, frames.length, frames, 1, new Object[] { "java/lang/Exception" });
    mv.visitVarInsn(ASTORE, localVariableIndex + 2);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitVarInsn(ALOAD, localVariableIndex + 2);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "rollback", "(Ljava/lang/Throwable;)V", false);
    mv.visitLabel(l3);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    Label l6 = new Label();
    mv.visitJumpInsn(GOTO, l6);
    mv.visitLabel(l4);
    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" });
    mv.visitVarInsn(ASTORE, localVariableIndex + 3);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    mv.visitVarInsn(ALOAD, localVariableIndex + 3);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l5);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    mv.visitLabel(l6);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitInsn(RETURN);
    mv.visitMaxs(Math.max(3, localVariableIndex + 1), 4 + localVariableIndex);
    mv.visitEnd();
}

From source file:org.yx.asm.ProxyMethodWritor.java

License:Apache License

public static void writeWithReturn(MethodVisitor mv, AsmMethod asmMethod) {
    Box db = asmMethod.method.getAnnotation(Box.class);
    if (db == null) {
        return;//ww  w .j a v  a2s.  c o m
    }
    String superowener = Type.getInternalName(asmMethod.superClz);
    String currentClz = asmMethod.currentClz.replace('.', '/');
    List<Object> argTypes = AsmUtils.getImplicitFrame(
            asmMethod.desc.substring(asmMethod.desc.indexOf("(") + 1, asmMethod.desc.indexOf(")")));
    Object returnType = AsmUtils.getImplicitFrame(asmMethod.desc.substring(asmMethod.desc.indexOf(")") + 1))
            .get(0);
    int localVariableIndex = argLength(argTypes);

    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception");
    Label l3 = new Label();
    mv.visitTryCatchBlock(l0, l1, l3, null);
    Label l4 = new Label();
    mv.visitTryCatchBlock(l2, l4, l3, null);
    mv.visitTypeInsn(NEW, AOPEXCUTOR);
    mv.visitInsn(DUP);
    mv.visitInsn(db.embed() ? ICONST_1 : ICONST_0);
    mv.visitMethodInsn(INVOKESPECIAL, AOPEXCUTOR, "<init>", "(Z)V", false);
    mv.visitVarInsn(ASTORE, localVariableIndex + 1);
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitLdcInsn(db.dbName());
    mv.visitFieldInsn(GETSTATIC, "org/yx/db/DBType", db.dbType().toString(), "Lorg/yx/db/DBType;");
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "begin", "(Ljava/lang/String;Lorg/yx/db/DBType;)V", false);
    mv.visitVarInsn(ALOAD, 0);

    loadArgs(mv, argTypes, 0);
    mv.visitMethodInsn(INVOKESPECIAL, superowener, asmMethod.name, asmMethod.desc, false);
    int methodReturnFrameIndex = localVariableIndex + 2;
    store(mv, returnType, methodReturnFrameIndex);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "commit", "()V", false);

    mv.visitLabel(l1);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    load(mv, returnType, methodReturnFrameIndex);
    jReturn(mv, returnType);
    mv.visitLabel(l2);

    List<Object> list = new ArrayList<Object>();
    list.add(currentClz);
    list.addAll(argTypes);
    list.add(AOPEXCUTOR);
    Object[] frames = list.toArray(new Object[list.size()]);

    mv.visitFrame(Opcodes.F_FULL, frames.length, frames, 1, new Object[] { "java/lang/Exception" });
    mv.visitVarInsn(ASTORE, localVariableIndex + 2);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitVarInsn(ALOAD, localVariableIndex + 2);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "rollback", "(Ljava/lang/Throwable;)V", false);
    mv.visitLabel(l4);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    Label l5 = new Label();
    mv.visitJumpInsn(GOTO, l5);
    mv.visitLabel(l3);
    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { "java/lang/Throwable" });
    mv.visitVarInsn(ASTORE, localVariableIndex + 3);
    mv.visitVarInsn(ALOAD, localVariableIndex + 1);
    mv.visitMethodInsn(INVOKEVIRTUAL, AOPEXCUTOR, "close", "()V", false);
    mv.visitVarInsn(ALOAD, localVariableIndex + 3);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l5);
    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
    mv.visitTypeInsn(NEW, "org/yx/exception/SumkException");
    mv.visitInsn(DUP);
    mv.visitLdcInsn(new Integer(-364533425));
    mv.visitLdcInsn("you are locky to see me^_^");
    mv.visitMethodInsn(INVOKESPECIAL, "org/yx/exception/SumkException", "<init>", "(ILjava/lang/String;)V",
            false);
    mv.visitInsn(ATHROW);
    mv.visitMaxs(Math.max(4, localVariableIndex + 1), 4 + localVariableIndex);
    mv.visitEnd();
}

From source file:pt.minha.kernel.instrument.SyncToMonitorClassVisitor.java

License:Open Source License

public void makeStub(int access, String name, String desc, String signature, String[] exceptions) {
    Method m = new Method(name, desc);

    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
    mv.visitCode();//  w ww  .  j  ava 2  s. co m

    Label begin = new Label();
    Label pre_invoke = new Label();
    Label pos_leave = new Label();
    Label in_catch = new Label();
    Label pre_rethrow = new Label();
    Label end = new Label();

    mv.visitTryCatchBlock(pre_invoke, pos_leave, in_catch, null);
    mv.visitTryCatchBlock(in_catch, pre_rethrow, in_catch, null);

    mv.visitLabel(begin);

    int offset;
    if ((access & Opcodes.ACC_STATIC) == 0) {
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        offset = 1;
    } else {
        mv.visitFieldInsn(Opcodes.GETSTATIC, clz, "_fake_class",
                "L" + ClassConfig.fake_prefix + "java/lang/Object;");
        offset = 0;
    }

    int length = 0;
    for (Type t : m.getArgumentTypes())
        length += t.getSize();

    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ASTORE, offset + length);
    mv.visitInsn(Opcodes.MONITORENTER);

    mv.visitLabel(pre_invoke);

    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitVarInsn(Opcodes.ALOAD, 0);

    int i = offset;
    for (Type t : m.getArgumentTypes()) {
        // t.getOpcode() should work for long and double too... :-( 
        if (t.getClassName().equals("long"))
            mv.visitVarInsn(Opcodes.LLOAD, i);
        else if (t.getClassName().equals("double"))
            mv.visitVarInsn(Opcodes.DLOAD, i);
        else
            mv.visitVarInsn(t.getOpcode(Opcodes.ILOAD), i);
        i += t.getSize();
    }

    boolean itf = (access & Opcodes.ACC_INTERFACE) != 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, clz, "_" + name, desc, itf);
    else
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, clz, "_" + name, desc, itf);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pos_leave);

    if (m.getReturnType().equals(Type.VOID_TYPE))
        mv.visitInsn(Opcodes.RETURN);
    else
        mv.visitInsn(m.getReturnType().getOpcode(Opcodes.IRETURN));

    mv.visitLabel(in_catch);

    mv.visitVarInsn(Opcodes.ALOAD, offset + length);
    mv.visitInsn(Opcodes.MONITOREXIT);

    mv.visitLabel(pre_rethrow);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(end);

    i = 0;
    if ((access & Opcodes.ACC_STATIC) == 0)
        mv.visitLocalVariable("this", "L" + clz + ";", null, begin, end, i++);
    for (Type t : m.getArgumentTypes())
        mv.visitLocalVariable("arg" + i, t.getDescriptor(), null, begin, end, i++);

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

From source file:rubah.bytecode.transformers.AddGettersAndSetters.java

License:Open Source License

/**
 * Use unsafe to ensure ability to write to final fields
 * @param isStatic/*www  . j  ava 2 s .  c o m*/
 * @param name
 * @param type
 */
private void generateFinalSetter(boolean isStatic, String name, Clazz owner, Clazz type) {
    String setterName = generateSetterName(owner.getASMType(), name);

    if (this.foundGettersSetters.contains(setterName))
        return;

    int fieldLocal = 1 + type.getASMType().getSize();
    int unsafeLocal = fieldLocal + 1;

    MethodVisitor mv = this.visitMethod((isStatic ? (ACCESS | ACC_STATIC) : ACCESS), setterName,
            Type.getMethodDescriptor(Type.VOID_TYPE, type.getASMType()), null, null);
    mv.visitCode();
    Label l0 = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitTryCatchBlock(l0, l1, l2, "java/lang/SecurityException");
    Label l3 = new Label();
    mv.visitTryCatchBlock(l0, l1, l3, "java/lang/NoSuchFieldException");
    mv.visitLabel(l0);
    mv.visitLdcInsn(owner.getASMType().getASMType());
    mv.visitLdcInsn(name);
    mv.visitMethodInsn(INVOKEVIRTUAL, CLASS_TYPE.getInternalName(), "getDeclaredField",
            Type.getMethodDescriptor(FIELD_TYPE, STRING_TYPE), false);
    mv.visitVarInsn(ASTORE, fieldLocal);
    mv.visitMethodInsn(INVOKESTATIC, Type.getType(Rubah.class).getInternalName(), "getUnsafe",
            Type.getMethodDescriptor(UNSAFE_TYPE), false);
    mv.visitVarInsn(ASTORE, unsafeLocal);
    mv.visitVarInsn(ALOAD, unsafeLocal);

    if (isStatic) {
        mv.visitVarInsn(ALOAD, unsafeLocal);
        mv.visitVarInsn(ALOAD, fieldLocal);
        mv.visitMethodInsn(INVOKEVIRTUAL, UNSAFE_TYPE.getInternalName(), "staticFieldBase",
                "(Ljava/lang/reflect/Field;)Ljava/lang/Object;", false);
        mv.visitVarInsn(ALOAD, unsafeLocal);
        mv.visitVarInsn(ALOAD, fieldLocal);
        mv.visitMethodInsn(INVOKEVIRTUAL, UNSAFE_TYPE.getInternalName(), "staticFieldOffset",
                Type.getMethodDescriptor(Type.LONG_TYPE, FIELD_TYPE), false);
        mv.visitVarInsn(type.getASMType().getOpcode(ILOAD), 0);
    } else {
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, unsafeLocal);
        mv.visitVarInsn(ALOAD, fieldLocal);
        mv.visitMethodInsn(INVOKEVIRTUAL, UNSAFE_TYPE.getInternalName(), "objectFieldOffset",
                Type.getMethodDescriptor(Type.LONG_TYPE, FIELD_TYPE), false);
        mv.visitVarInsn(type.getASMType().getOpcode(ILOAD), 1);
    }

    this.generatePutObjectInvocation(mv, type.getASMType());

    mv.visitLabel(l1);
    Label l6 = new Label();
    mv.visitJumpInsn(GOTO, l6);
    mv.visitLabel(l2);
    mv.visitVarInsn(ASTORE, 2);
    mv.visitTypeInsn(NEW, "java/lang/Error");
    mv.visitInsn(DUP);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Error", "<init>", "(Ljava/lang/Throwable;)V", false);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l3);
    mv.visitVarInsn(ASTORE, 2);
    mv.visitTypeInsn(NEW, "java/lang/Error");
    mv.visitInsn(DUP);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Error", "<init>", "(Ljava/lang/Throwable;)V", false);
    mv.visitInsn(ATHROW);
    mv.visitLabel(l6);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:sg.atom.core.actor.internal.codegenerator.BeanCreator.java

License:Apache License

/**
 * Writes the bean constructor to the given ClassWriter.
 *
 * @param beanClass the original bean class to extend
 * @param bcd the descriptor of the bean
 * @param classNameInternal the internal name of the new class
 * @param cw the ClassWriter to write to
 * @param snippetWriter if not null, this will be invoked to add a snippet
 * after the invocation of the super constructor
 *///from  www  .j  a  v  a 2  s  . co m
public static void writeConstructor(Class<?> beanClass, BeanClassDescriptor bcd, String classNameInternal,
        ClassWriter cw, SnippetWriter snippetWriter) {
    String classNameDescriptor = "L" + classNameInternal + ";";

    int localPropertySize = 0;
    ArrayList<PropertyDescriptor> localVarProperties = new ArrayList<PropertyDescriptor>();
    for (int i = 0; i < bcd.getPropertyCount(); i++) {
        PropertyDescriptor pd = bcd.getProperty(i);
        if (pd.getPropertySource().isGenerating() || (pd.getDefaultValue() != null)) {
            localVarProperties.add(pd);
            localPropertySize += Type.getType(pd.getPropertyClass()).getSize();
        }
    }

    final int locVarThis = 0;
    final int locVarController = 1;
    final int locVarProps = 2;
    final int locVarPropertiesOffset = 3;
    final int locVarP = 3 + localPropertySize;
    final int locVarK = 4 + localPropertySize;
    final int locVarV = 5 + localPropertySize;

    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>",
            "(Lorg/actorsguildframework/internal/Controller;Lorg/actorsguildframework/Props;)V", null, null);
    mv.visitCode();
    Label lTry = new Label();
    Label lCatch = new Label();
    mv.visitTryCatchBlock(lTry, lCatch, lCatch, "java/lang/ClassCastException");

    Label lBegin = new Label();
    mv.visitLabel(lBegin);
    mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(beanClass), "<init>", "()V");

    if (snippetWriter != null) {
        snippetWriter.write(mv);
    }

    Label lPropertyInit = new Label();
    mv.visitLabel(lPropertyInit);
    // load default values into the local variables for each property that must be set
    int varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        if (pd.getDefaultValue() != null) {
            mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(pd.getDefaultValue().getDeclaringClass()),
                    pd.getDefaultValue().getName(), Type.getDescriptor(pd.getDefaultValue().getType()));
        } else {
            GenerationUtils.generateLoadDefault(mv, pd.getPropertyClass());
        }
        mv.visitVarInsn(pt.getOpcode(Opcodes.ISTORE), locVarPropertiesOffset + varCount);
        varCount += pt.getSize();
    }

    // loop through the props argument's list
    mv.visitVarInsn(Opcodes.ALOAD, locVarProps);
    mv.visitVarInsn(Opcodes.ASTORE, locVarP);
    Label lWhile = new Label();
    Label lEndWhile = new Label();
    Label lWhileBody = new Label();
    mv.visitLabel(lWhile);
    mv.visitJumpInsn(Opcodes.GOTO, lEndWhile);
    mv.visitLabel(lWhileBody);

    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitInsn(Opcodes.DUP);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "getKey",
            "()Ljava/lang/String;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarK);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "getValue",
            "()Ljava/lang/Object;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarV);

    mv.visitLabel(lTry);
    // write an if for each property
    Label lEndIf = new Label();
    varCount = 0;
    int ifCount = 0;
    for (int i = 0; i < bcd.getPropertyCount(); i++) {
        PropertyDescriptor pd = bcd.getProperty(i);
        boolean usesLocal = pd.getPropertySource().isGenerating() || (pd.getDefaultValue() != null);
        Class<?> propClass = pd.getPropertyClass();
        Type pt = Type.getType(propClass);
        mv.visitVarInsn(Opcodes.ALOAD, locVarK);
        mv.visitLdcInsn(pd.getName());
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z");
        Label lElse = new Label();
        mv.visitJumpInsn(Opcodes.IFEQ, lElse);

        if (!usesLocal) {
            mv.visitVarInsn(Opcodes.ALOAD, locVarThis); // for setter invocation, load 'this'
        }
        if (propClass.isPrimitive()) {
            mv.visitLdcInsn(pd.getName());
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(BeanHelper.class),
                    String.format("get%s%sFromPropValue",
                            propClass.getName().substring(0, 1).toUpperCase(Locale.US),
                            propClass.getName().substring(1)),
                    "(Ljava/lang/String;Ljava/lang/Object;)" + pt.getDescriptor());
        } else if (!propClass.equals(Object.class)) {
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);
            mv.visitTypeInsn(Opcodes.CHECKCAST, pt.getInternalName());
        } else {
            mv.visitVarInsn(Opcodes.ALOAD, locVarV);
        }

        if (!usesLocal) {
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classNameInternal, pd.getSetter().getName(),
                    Type.getMethodDescriptor(pd.getSetter()));
        } else {
            mv.visitVarInsn(pt.getOpcode(Opcodes.ISTORE), varCount + locVarPropertiesOffset);
        }

        mv.visitJumpInsn(Opcodes.GOTO, lEndIf);
        mv.visitLabel(lElse);

        ifCount++;
        if (usesLocal) {
            varCount += pt.getSize();
        }
    }

    // else (==> if not prop matched) throw IllegalArgumentException
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn("Unknown property \"%s\".");
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(Opcodes.ALOAD, locVarK);
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>",
            "(Ljava/lang/String;)V");
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(lCatch);
    mv.visitInsn(Opcodes.POP); // pop the exception object (not needed)
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class));
    mv.visitInsn(Opcodes.DUP);
    mv.visitLdcInsn("Incompatible type for property \"%s\". Got %s.");
    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitVarInsn(Opcodes.ALOAD, locVarK);
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitInsn(Opcodes.DUP);
    mv.visitInsn(Opcodes.ICONST_1);
    mv.visitVarInsn(Opcodes.ALOAD, locVarV);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Class", "getName", "()Ljava/lang/String;");
    mv.visitInsn(Opcodes.AASTORE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;");
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>",
            "(Ljava/lang/String;)V");
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitLabel(lEndIf);
    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/actorsguildframework/Props", "tail",
            "()Lorg/actorsguildframework/Props;");
    mv.visitVarInsn(Opcodes.ASTORE, locVarP);

    mv.visitLabel(lEndWhile);
    mv.visitVarInsn(Opcodes.ALOAD, locVarP);
    mv.visitJumpInsn(Opcodes.IFNONNULL, lWhileBody);

    // write local variables back into properties 
    varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
        if (pd.getPropertySource() == PropertySource.ABSTRACT_METHOD) {
            mv.visitVarInsn(pt.getOpcode(Opcodes.ILOAD), locVarPropertiesOffset + varCount);
            mv.visitFieldInsn(Opcodes.PUTFIELD, classNameInternal,
                    String.format(PROP_FIELD_NAME_TEMPLATE, pd.getName()), pt.getDescriptor());
        } else if (pd.getPropertySource() == PropertySource.USER_WRITTEN) {
            mv.visitVarInsn(pt.getOpcode(Opcodes.ILOAD), locVarPropertiesOffset + varCount);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classNameInternal, pd.getSetter().getName(),
                    Type.getMethodDescriptor(pd.getSetter()));
        } else {
            throw new RuntimeException("Internal error");
        }
        varCount += pt.getSize();
    }

    // if bean is thread-safe, publish all writes now
    if (bcd.isThreadSafe()) {
        mv.visitVarInsn(Opcodes.ALOAD, locVarThis);
        mv.visitInsn(Opcodes.DUP);
        mv.visitInsn(Opcodes.MONITORENTER);
        mv.visitInsn(Opcodes.MONITOREXIT);
    }

    mv.visitInsn(Opcodes.RETURN);
    Label lEnd = new Label();
    mv.visitLabel(lEnd);

    mv.visitLocalVariable("this", classNameDescriptor, null, lBegin, lEnd, locVarThis);
    mv.visitLocalVariable("controller", "Lorg/actorsguildframework/internal/Controller;", null, lBegin, lEnd,
            locVarController);
    mv.visitLocalVariable("props", "Lorg/actorsguildframework/Props;", null, lBegin, lEnd, locVarProps);
    varCount = 0;
    for (PropertyDescriptor pd : localVarProperties) {
        Type pt = Type.getType(pd.getPropertyClass());
        mv.visitLocalVariable("__" + pd.getName(), pt.getDescriptor(),
                GenericTypeHelper.getSignature(pd.getPropertyType()), lPropertyInit, lEnd,
                locVarPropertiesOffset + varCount);
        varCount += pt.getSize();
    }
    mv.visitLocalVariable("p", "Lorg/actorsguildframework/Props;", null, lPropertyInit, lEnd, locVarP);
    mv.visitLocalVariable("k", "Ljava/lang/String;", null, lWhile, lEndWhile, locVarK);
    mv.visitLocalVariable("v", "Ljava/lang/Object;", null, lWhile, lEndWhile, locVarV);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}