Example usage for org.objectweb.asm.commons GeneratorAdapter throwException

List of usage examples for org.objectweb.asm.commons GeneratorAdapter throwException

Introduction

In this page you can find the example usage for org.objectweb.asm.commons GeneratorAdapter throwException.

Prototype

public void throwException() 

Source Link

Document

Generates the instruction to throw an exception.

Usage

From source file:co.cask.cdap.internal.io.FieldAccessorGenerator.java

License:Apache License

private void initializeReflectionField(GeneratorAdapter mg, Field field) {
    /*//w  w  w. ja  v  a 2s .  c  o m
     Save the reflected Field object for accessing private field.
     try {
       Field field = Fields.findField(classType, "fieldName");
       field.setAccessible(true);
            
       this.field = field;
     } catch (Exception e) {
       throw Throwables.propagate(e);
     }
    */
    Label beginTry = mg.newLabel();
    Label endTry = mg.newLabel();
    Label catchHandle = mg.newLabel();
    mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(Exception.class));
    mg.mark(beginTry);

    // Field field = Fields.findField(classType, "fieldName")
    mg.loadArg(0);
    mg.push(field.getName());
    mg.invokeStatic(Type.getType(Fields.class),
            getMethod(Field.class, "findField", java.lang.reflect.Type.class, String.class));
    mg.dup();

    // field.setAccessible(true);
    mg.push(true);
    mg.invokeVirtual(Type.getType(Field.class), getMethod(void.class, "setAccessible", boolean.class));

    // this.field = field;
    // need to swap the this reference and the one in top stack (from dup() ).
    mg.loadThis();
    mg.swap();
    mg.putField(Type.getObjectType(className), "field", Type.getType(Field.class));
    mg.mark(endTry);
    Label endCatch = mg.newLabel();
    mg.goTo(endCatch);
    mg.mark(catchHandle);
    int exception = mg.newLocal(Type.getType(IllegalAccessException.class));
    mg.storeLocal(exception);
    mg.loadLocal(exception);
    mg.invokeStatic(Type.getType(Throwables.class),
            getMethod(RuntimeException.class, "propagate", Throwable.class));
    mg.throwException();
    mg.mark(endCatch);
}

From source file:co.cask.cdap.internal.io.FieldAccessorGenerator.java

License:Apache License

/**
 * Generates the try-catch block that wrap around the given reflection method call.
 * @param method The method to be called within the try-catch block.
 *///from ww  w .  j a v a  2  s.  c  om
private void invokeReflection(Method method, String signature) {
    GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, method, signature, new Type[0], classWriter);
    /**
     * try {
     *   // Call method
     * } catch (IllegalAccessException e) {
     *   throw Throwables.propagate(e);
     * }
     */
    Label beginTry = mg.newLabel();
    Label endTry = mg.newLabel();
    Label catchHandle = mg.newLabel();
    mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(IllegalAccessException.class));
    mg.mark(beginTry);
    mg.loadThis();
    mg.getField(Type.getObjectType(className), "field", Type.getType(Field.class));
    mg.loadArgs();
    mg.invokeVirtual(Type.getType(Field.class), method);
    mg.mark(endTry);
    mg.returnValue();
    mg.mark(catchHandle);
    int exception = mg.newLocal(Type.getType(IllegalAccessException.class));
    mg.storeLocal(exception);
    mg.loadLocal(exception);
    mg.invokeStatic(Type.getType(Throwables.class),
            getMethod(RuntimeException.class, "propagate", Throwable.class));
    mg.throwException();
    mg.endMethod();

}

From source file:co.cask.common.internal.io.FieldAccessorGenerator.java

License:Apache License

private void initializeReflectionField(GeneratorAdapter mg, Field field) {
    /*/*from w  w  w .  jav  a  2  s .  c om*/
     Save the reflected Field object for accessing private field.
     try {
       Field field = Fields.findField(classType, "fieldName");
       field.setAccessible(true);
            
       this.field = field;
     } catch (Exception e) {
       throw Throwables.propagate(e);
     }
    */
    Label beginTry = mg.newLabel();
    Label endTry = mg.newLabel();
    Label catchHandle = mg.newLabel();
    mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(Exception.class));
    mg.mark(beginTry);

    // Field field = findField(classType, "fieldName")
    mg.loadArg(0);
    mg.push(field.getName());
    mg.invokeStatic(Type.getType(Fields.class),
            getMethod(Field.class, "findField", TypeToken.class, String.class));
    mg.dup();

    // field.setAccessible(true);
    mg.push(true);
    mg.invokeVirtual(Type.getType(Field.class), getMethod(void.class, "setAccessible", boolean.class));

    // this.field = field;
    // need to swap the this reference and the one in top stack (from dup() ).
    mg.loadThis();
    mg.swap();
    mg.putField(Type.getObjectType(className), "field", Type.getType(Field.class));
    mg.mark(endTry);
    Label endCatch = mg.newLabel();
    mg.goTo(endCatch);
    mg.mark(catchHandle);
    int exception = mg.newLocal(Type.getType(IllegalAccessException.class));
    mg.storeLocal(exception);
    mg.loadLocal(exception);
    mg.invokeStatic(Type.getType(Throwables.class),
            getMethod(RuntimeException.class, "propagate", Throwable.class));
    mg.throwException();
    mg.mark(endCatch);
}

From source file:com.alibaba.hotswap.processor.constructor.ConstructorVisitor.java

License:Open Source License

private void addEmptyUniformConstructor() {
    int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNTHETIC;
    String name = HotswapConstants.INIT;
    String desc = HotswapConstants.UNIFORM_CONSTRUCTOR_DESC;

    MethodVisitor hotswapInit = cv.visitMethod(access, name, desc, null, null);
    GeneratorAdapter hotswapInitAdapter = new GeneratorAdapter(hotswapInit, access, name, desc);
    hotswapInitAdapter.visitCode();/*from  w  w  w . j  a va 2 s  .co m*/
    hotswapInitAdapter.push(this.className);
    hotswapInitAdapter.loadArg(1);
    hotswapInitAdapter.invokeStatic(Type.getType(HotswapMethodUtil.class),
            Method.getMethod("Throwable noSuchMethodError(String, int)"));
    hotswapInitAdapter.throwException();
    hotswapInitAdapter.endMethod();
}

From source file:com.alibaba.hotswap.processor.constructor.ConstructorVisitor.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
private void addUniformConstructor(ClassMeta classMeta) {
    int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_SYNTHETIC;
    String name = HotswapConstants.INIT;
    String desc = HotswapConstants.UNIFORM_CONSTRUCTOR_DESC;

    MethodVisitor hotswapInit = new ConstructorInvokeModifier(cv.visitMethod(access, name, desc, null, null),
            access, name, desc);/*  ww  w.j  a va2s . c  om*/
    GeneratorAdapter hotswapInitAdapter = new GeneratorAdapter(hotswapInit, access, name, desc);

    hotswapInitAdapter.visitCode();

    TreeMap<MethodMeta, MethodNode> initMethodMap = new TreeMap<MethodMeta, MethodNode>(
            new ConstructorIndexComparator());

    for (MethodNode node : initNodes.values()) {
        MethodMeta meta = new MethodMeta(node.access, node.name, node.desc, node.signature,
                ((String[]) node.exceptions.toArray(new String[node.exceptions.size()])));
        meta.setIndex(HotswapMethodIndexHolder.getMethodIndex(className, node.name, node.desc));
        classMeta.refreshInitMeta(meta, true);
        initMethodMap.put(meta, node);
    }

    List<MethodMeta> keys = new ArrayList<MethodMeta>(initMethodMap.keySet());
    List<MethodNode> values = new ArrayList<MethodNode>(initMethodMap.values());

    Label defaultLabel = new Label();
    int[] indexes = new int[keys.size()];
    Label[] labels = new Label[keys.size()];

    for (int i = 0; i < keys.size(); i++) {
        indexes[i] = keys.get(i).getIndex();
        labels[i] = new Label();
    }

    for (int i = 0; i < values.size(); i++) {
        MethodNode node = values.get(i);
        for (int j = 0; j < node.tryCatchBlocks.size(); j++) {
            ((TryCatchBlockNode) node.tryCatchBlocks.get(j)).accept(hotswapInitAdapter);
        }
    }

    hotswapInitAdapter.loadArg(1);
    hotswapInitAdapter.visitLookupSwitchInsn(defaultLabel, indexes, labels);

    for (int i = 0; i < keys.size(); i++) {
        MethodMeta methodMeta = keys.get(i);
        hotswapInitAdapter.visitLabel(labels[i]);
        MethodNode node = values.get(i);

        storeArgs(hotswapInitAdapter, hotswapInit, methodMeta);
        MethodVisitor methodVisitor = new ConstructorLVTAdjustModifier(hotswapInit, 3);

        node.instructions.accept(methodVisitor);

        for (int j = 0; j < (node.localVariables == null ? 0 : node.localVariables.size()); j++) {
            ((LocalVariableNode) node.localVariables.get(j)).accept(methodVisitor);
        }
    }
    hotswapInitAdapter.mark(defaultLabel);

    hotswapInitAdapter.push(this.className);
    hotswapInitAdapter.loadArg(1);
    hotswapInitAdapter.invokeStatic(Type.getType(HotswapMethodUtil.class),
            Method.getMethod("Throwable noSuchMethodError(String, int)"));
    hotswapInitAdapter.throwException();
    hotswapInitAdapter.endMethod();
}

From source file:com.android.build.gradle.internal.incremental.StringSwitch.java

License:Apache License

/**
 * Generates a standard error exception with message similar to:
 *
 *    String switch could not find 'equals.(Ljava/lang/Object;)Z' with hashcode 0
 *    in com/example/basic/GrandChild//  www . j  a  v a2  s  . c  o  m
 *
 * @param mv The generator adaptor used to emit the lookup switch code.
 * @param visitedClassName The abstract string trie structure.
 */
void writeMissingMessageWithHash(GeneratorAdapter mv, String visitedClassName) {
    mv.newInstance(INSTANT_RELOAD_EXCEPTION_TYPE);
    mv.dup();
    mv.push("String switch could not find '%s' with hashcode %s in %s");
    mv.push(3);
    mv.newArray(OBJECT_TYPE);
    mv.dup();
    mv.push(0);
    visitString();
    mv.arrayStore(OBJECT_TYPE);
    mv.dup();
    mv.push(1);
    visitString();
    visitHashMethod(mv);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
    mv.arrayStore(OBJECT_TYPE);
    mv.dup();
    mv.push(2);
    mv.push(visitedClassName);
    mv.arrayStore(OBJECT_TYPE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false);
    mv.invokeConstructor(INSTANT_RELOAD_EXCEPTION_TYPE, Method.getMethod("void <init> (String)"));
    mv.throwException();
}

From source file:com.mogujie.instantrun.IntSwitch.java

License:Apache License

void writeMissingMessageWithHash(GeneratorAdapter mv, String visitedClassName) {
    mv.newInstance(INSTANT_RELOAD_EXCEPTION_TYPE);
    mv.dup();//from www.j av a  2  s  .c om
    mv.push("int switch could not find %d in %s");
    mv.push(3);
    mv.newArray(OBJECT_TYPE);
    mv.dup();
    mv.push(0);
    visitInt();
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
    mv.arrayStore(OBJECT_TYPE);
    mv.dup();
    mv.push(2);
    mv.push(visitedClassName);
    mv.arrayStore(OBJECT_TYPE);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/String", "format",
            "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", false);
    mv.invokeConstructor(INSTANT_RELOAD_EXCEPTION_TYPE, Method.getMethod("void <init> (String)"));
    mv.throwException();
}

From source file:io.datakernel.codegen.ExpressionSwitch.java

License:Apache License

@Override
public Type load(Context ctx) {
    VarLocal varReadedSubClass = newLocal(ctx, nom.type(ctx));
    nom.load(ctx);/*from   w w  w . ja  v  a  2s  . co m*/
    varReadedSubClass.store(ctx);

    Label labelExit = new Label();
    GeneratorAdapter g = ctx.getGeneratorAdapter();

    for (int i = 0; i < list.size(); i++) {
        Label labelNext = new Label();

        g.push(i);
        varReadedSubClass.load(ctx);
        g.ifCmp(INT_TYPE, GeneratorAdapter.NE, labelNext);

        list.get(i).load(ctx);
        g.goTo(labelExit);

        g.mark(labelNext);
    }

    if (defaultExp != null) {
        defaultExp.load(ctx);
    } else {
        final Variable sb = let(constructor(StringBuilder.class));
        call(sb, "append", value("Key '")).load(ctx);
        call(sb, "append", cast(varReadedSubClass, getType(int.class))).load(ctx);
        call(sb, "append", value(String.format("' not in range [0-%d)", list.size()))).load(ctx);
        constructor(IllegalArgumentException.class, call(sb, "toString")).load(ctx);
        g.throwException();
    }
    g.mark(labelExit);

    return type(ctx);
}

From source file:io.datakernel.codegen.ExpressionSwitchForKey.java

License:Apache License

@Override
public Type load(Context ctx) {
    VarLocal varKey = newLocal(ctx, key.type(ctx));
    key.load(ctx);/*from  w  ww  . j a  va  2  s.co m*/
    varKey.store(ctx);

    Label labelExit = new Label();
    GeneratorAdapter g = ctx.getGeneratorAdapter();

    final boolean keyPrimitiveType = Utils.isPrimitiveType(key.type(ctx));
    for (int i = 0; i < listKey.size(); i++) {
        Label labelNext = new Label();
        if (keyPrimitiveType) {
            listKey.get(i).load(ctx);
            varKey.load(ctx);
            g.ifCmp(key.type(ctx), GeneratorAdapter.NE, labelNext);
        } else {
            call(listKey.get(i), "equals", varKey).load(ctx);
            g.push(true);
            g.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, labelNext);
        }

        listValue.get(i).load(ctx);
        g.goTo(labelExit);

        g.mark(labelNext);
    }

    if (defaultExp != null) {
        defaultExp.load(ctx);
    } else {
        final Variable sb = let(constructor(StringBuilder.class));
        call(sb, "append", value("Key '")).load(ctx);
        call(sb, "append", keyPrimitiveType ? varKey : call(key, "toString")).load(ctx);
        call(sb, "append", value("' not in keyList: [")).load(ctx);
        final Iterator<Expression> iterator = listKey.iterator();
        while (iterator.hasNext()) {
            final Expression expression = iterator.next();
            final boolean primitiveType = Utils.isPrimitiveType(expression.type(ctx));
            call(sb, "append", primitiveType ? expression : call(expression, "toString")).load(ctx);
            if (iterator.hasNext()) {
                call(sb, "append", value(", ")).load(ctx);
            }
        }
        call(sb, "append", value("]")).load(ctx);

        constructor(IllegalArgumentException.class, call(sb, "toString")).load(ctx);
        g.throwException();
    }
    g.mark(labelExit);

    return type(ctx);
}

From source file:lucee.transformer.bytecode.Page.java

License:Open Source License

private void writeOutInitComponent(BytecodeContext statConstr, BytecodeContext constr, List<LitString> keys,
        ClassWriter cw, Tag component) throws BytecodeException {
    final GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL,
            INIT_COMPONENT, null, new Type[] { Types.PAGE_EXCEPTION }, cw);
    BytecodeContext bc = new BytecodeContext(null, statConstr, constr, this, keys, cw, name, adapter,
            INIT_COMPONENT, writeLog(), suppressWSbeforeArg, output);
    Label methodBegin = new Label();
    Label methodEnd = new Label();

    adapter.visitLocalVariable("this", "L" + name + ";", null, methodBegin, methodEnd, 0);
    adapter.visitLabel(methodBegin);//from www .  ja v  a2  s .  c  o  m

    // Scope oldData=null;
    final int oldData = adapter.newLocal(Types.VARIABLES);
    ASMConstants.NULL(adapter);
    adapter.storeLocal(oldData);

    int localBC = adapter.newLocal(Types.BODY_CONTENT);
    ConditionVisitor cv = new ConditionVisitor();
    cv.visitBefore();
    cv.visitWhenBeforeExpr();
    adapter.loadArg(1);
    adapter.invokeVirtual(Types.COMPONENT_IMPL, GET_OUTPUT);
    cv.visitWhenAfterExprBeforeBody(bc);
    ASMConstants.NULL(adapter);
    cv.visitWhenAfterBody(bc);

    cv.visitOtherviseBeforeBody();
    adapter.loadArg(0);
    adapter.invokeVirtual(Types.PAGE_CONTEXT, PUSH_BODY);
    cv.visitOtherviseAfterBody();
    cv.visitAfter(bc);
    adapter.storeLocal(localBC);

    // c.init(pc,this);
    adapter.loadArg(1);
    adapter.loadArg(0);
    adapter.visitVarInsn(Opcodes.ALOAD, 0);
    adapter.invokeVirtual(Types.COMPONENT_IMPL, INIT);

    //int oldCheckArgs=   pc.undefinedScope().setMode(Undefined.MODE_NO_LOCAL_AND_ARGUMENTS);
    final int oldCheckArgs = adapter.newLocal(Types.INT_VALUE);
    adapter.loadArg(0);
    adapter.invokeVirtual(Types.PAGE_CONTEXT, UNDEFINED_SCOPE);
    adapter.push(Undefined.MODE_NO_LOCAL_AND_ARGUMENTS);
    adapter.invokeInterface(Types.UNDEFINED, SET_MODE);
    adapter.storeLocal(oldCheckArgs);

    TryCatchFinallyVisitor tcf = new TryCatchFinallyVisitor(new OnFinally() {

        public void _writeOut(BytecodeContext bc) {

            // undefined.setMode(oldMode);
            adapter.loadArg(0);
            adapter.invokeVirtual(Types.PAGE_CONTEXT, UNDEFINED_SCOPE);
            adapter.loadLocal(oldCheckArgs, Types.INT_VALUE);
            adapter.invokeInterface(Types.UNDEFINED, SET_MODE);
            adapter.pop();

            // c.afterCall(pc,_oldData);
            adapter.loadArg(1);
            adapter.loadArg(0);
            adapter.loadLocal(oldData);
            adapter.invokeVirtual(Types.COMPONENT_IMPL, AFTER_CALL);

        }
    }, null);
    tcf.visitTryBegin(bc);
    // oldData=c.beforeCall(pc);
    adapter.loadArg(1);
    adapter.loadArg(0);
    adapter.invokeVirtual(Types.COMPONENT_IMPL, BEFORE_CALL);
    adapter.storeLocal(oldData);
    ExpressionUtil.visitLine(bc, component.getStart());
    writeOutCallBody(bc, component.getBody(), IFunction.PAGE_TYPE_COMPONENT);
    ExpressionUtil.visitLine(bc, component.getEnd());
    int t = tcf.visitTryEndCatchBeging(bc);
    // BodyContentUtil.flushAndPop(pc,bc);
    adapter.loadArg(0);
    adapter.loadLocal(localBC);
    adapter.invokeStatic(Types.BODY_CONTENT_UTIL, FLUSH_AND_POP);

    // throw Caster.toPageException(t);
    adapter.loadLocal(t);
    adapter.invokeStatic(Types.CASTER, TO_PAGE_EXCEPTION);
    adapter.throwException();
    tcf.visitCatchEnd(bc);

    adapter.loadArg(0);
    adapter.loadLocal(localBC);
    adapter.invokeStatic(Types.BODY_CONTENT_UTIL, CLEAR_AND_POP);

    adapter.returnValue();
    adapter.visitLabel(methodEnd);

    adapter.endMethod();

}