Example usage for org.objectweb.asm Opcodes ATHROW

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

Introduction

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

Prototype

int ATHROW

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

Click Source Link

Usage

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/* w  ww  .  j av  a  2 s.c o m*/
 * @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.offbynull.coroutines.instrumenter.generators.GenericGenerators.java

License:Open Source License

/**
 * Generates instructions to throw the exception type at top of stack. You may run in to problems if the item on top of the stack isn't
 * a {@link Throwable} type. // w  w w .jav a2s  .  c om
 * @return instructions to throw an exception
 * @throws NullPointerException if any argument is {@code null}
 */
public static InsnList throwThrowable() {
    InsnList ret = new InsnList();

    //        ret.add(new TypeInsnNode(Opcodes.CHECKCAST, "java/lang/Throwable")); // If required, do it outside this method
    ret.add(new InsnNode(Opcodes.ATHROW));

    return ret;
}

From source file:com.sun.fortress.compiler.OverloadSet.java

License:Open Source License

protected void generateBody(MethodVisitor mv, int one_if_method_closure) {
    mv.visitCode();/*from   w ww. ja va 2 s  .c o  m*/
    //   Label fail = new Label();

    generateCall(mv, firstArg(), one_if_method_closure); // Guts of overloaded method

    // Emit failure case
    //        mv.visitLabel(fail);
    //        // Boilerplate for throwing an error.
    //        // mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);

    mv.visitMethodInsn(Opcodes.INVOKESTATIC, NamingCzar.miscCodegen, NamingCzar.matchFailure,
            NamingCzar.errorReturn);
    mv.visitInsn(Opcodes.ATHROW);

    mv.visitMaxs(getParamCount(), getParamCount()); // autocomputed
    mv.visitEnd();
}

From source file:com.taobao.profile.instrument.ProfMethodAdapter.java

License:Open Source License

public void visitInsn(int inst) {
    switch (inst) {
    case Opcodes.ARETURN:
    case Opcodes.DRETURN:
    case Opcodes.FRETURN:
    case Opcodes.IRETURN:
    case Opcodes.LRETURN:
    case Opcodes.RETURN:
    case Opcodes.ATHROW:
        this.visitLdcInsn(mMethodId);
        this.visitMethodInsn(INVOKESTATIC, "com/taobao/profile/Profiler", "End", "(I)V");
        break;/*  w  w w. j av a2 s .c  o  m*/
    default:
        break;
    }

    super.visitInsn(inst);
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.types.gambit.BytecodeCatchBuilder.java

@Override
public ScopedBuilder always() {
    CatchClause catchClause = new CatchClause(source, parent.child()) {
        @Override//  w  w w .j  ava 2  s .co m
        public void generate(CodeEmitter code) {
            super.generate(code);
            code.getMethodVisitor().visitInsn(Opcodes.ATHROW);
        }
    };
    catchClauses.add(catchClause);
    return catchClause;
}

From source file:com.yahoo.yqlplus.engine.internal.compiler.CodeEmitter.java

public void emitThrow(Class<? extends Throwable> exceptionType, BytecodeExpression... constructorArguments) {
    emitNew(Type.getInternalName(exceptionType), constructorArguments);
    methodVisitor.visitInsn(Opcodes.ATHROW);
}

From source file:com.yahoo.yqlplus.engine.internal.source.MissingRequiredFieldExpr.java

@Override
public void generate(CodeEmitter code) {
    MethodVisitor mv = code.getMethodVisitor();
    mv.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class));
    mv.visitInsn(Opcodes.DUP);//from   ww  w .ja v  a2 s .  c om
    mv.visitLdcInsn(String.format("%s::%s Missing required property '%s' (%s)", className, methodName,
            propertyName, type.getTypeName()));
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false);
    mv.visitInsn(Opcodes.ATHROW);
}

From source file:de.codesourcery.asm.controlflow.ControlFlowAnalyzer.java

License:Apache License

@SuppressWarnings("unchecked")
public ControlFlowGraph analyze(String owner, final MethodNode mn) throws AnalyzerException {
    // line numbers with associated block
    // initially we'll create one block per line and merge adjacent ones later if control flow permits it  
    final Map<Integer, IBlock> blocks = new HashMap<>();

    final ListIterator<AbstractInsnNode> it = mn.instructions.iterator();

    IBlock currentLine = null;/* www.java2s  .  c  o m*/
    Object previousMetadata = null;
    IBlock previous = null;
    final IBlock methodExit = new MethodExit();
    for (int instrCounter = 0; it.hasNext(); instrCounter++) {
        final AbstractInsnNode instruction = it.next();
        currentLine = getBlockForInstruction(instrCounter, blocks);

        if (previous != null) {
            previous.addSuccessor(currentLine, EdgeType.REGULAR, previousMetadata);
            currentLine.addRegularPredecessor(previous);
            previousMetadata = null;
        }

        IBlock nextPrevious = currentLine;
        switch (instruction.getType()) {

        case AbstractInsnNode.LOOKUPSWITCH_INSN:
            LookupSwitchInsnNode lookup = (LookupSwitchInsnNode) instruction;

            // add edge for default handler
            if (lookup.dflt != null) {
                final IBlock target = getBlockForInstruction(lookup.dflt, mn, blocks);
                target.addRegularPredecessor(currentLine);
                currentLine.addRegularSuccessor(target);
            }

            @SuppressWarnings("cast")
            final Iterator<Integer> keys = (Iterator<Integer>) lookup.keys.iterator();

            for (LabelNode ln : (List<LabelNode>) lookup.labels) {
                final IBlock target = getBlockForInstruction(ln, mn, blocks);
                final Integer key = keys.next();

                target.addPredecessor(currentLine, EdgeType.LOOKUP_SWITCH, key);
                currentLine.addSuccessor(target, EdgeType.LOOKUP_SWITCH, key);
            }
            nextPrevious = null;
            break;

        case AbstractInsnNode.TABLESWITCH_INSN:

            TableSwitchInsnNode tblSwitch = (TableSwitchInsnNode) instruction;

            // add edge for default handler
            if (tblSwitch.dflt != null) {
                final IBlock target = getBlockForInstruction(tblSwitch.dflt, mn, blocks);
                target.addRegularPredecessor(currentLine);
                currentLine.addRegularSuccessor(target);
            }
            int currentKey = tblSwitch.min;

            for (LabelNode ln : (List<LabelNode>) tblSwitch.labels) {
                final IBlock target = getBlockForInstruction(ln, mn, blocks);

                target.addPredecessor(currentLine, EdgeType.TABLE_SWITCH, currentKey);
                currentLine.addSuccessor(target, EdgeType.TABLE_SWITCH, currentKey);

                currentKey++;
            }
            nextPrevious = null;
            break;

        case AbstractInsnNode.INSN:

            if (instruction.getOpcode() == Opcodes.RETURN
                    || instruction.getOpcode() == Opcodes.IRETURN) /* method exit */
            {
                currentLine.addRegularSuccessor(methodExit);
                methodExit.addRegularPredecessor(currentLine);
                nextPrevious = null;
            } else if (instruction.getOpcode() == Opcodes.ATHROW || instruction.getOpcode() == Opcodes.RET) {
                nextPrevious = null;
            }
            break;

        case AbstractInsnNode.JUMP_INSN: /* jump */

            final JumpInsnNode jmp = (JumpInsnNode) instruction;
            final LabelNode label = jmp.label;
            final int target = mn.instructions.indexOf(label);

            final boolean isConditional = ASMUtil.isConditionalJump(instruction);

            if (isConditional) { // label edges of conditional jump instructions with "true" and "false
                previousMetadata = "false";
            }

            final IBlock targetBlock = getBlockForInstruction(target, blocks);
            targetBlock.addRegularPredecessor(currentLine);

            // create edge from current block to jump target 
            currentLine.addSuccessor(targetBlock, EdgeType.REGULAR, isConditional ? "true" : null);

            if (instruction.getOpcode() == Opcodes.GOTO) {
                nextPrevious = null;
            }
            break;
        }

        // link last instruction with method_exit block
        if (!it.hasNext()) {
            currentLine.addRegularSuccessor(methodExit);
            methodExit.addRegularPredecessor(currentLine);
        }
        previous = nextPrevious;
    }
    // try/catch blocks need special treatment because
    // they are not represented as opcodes
    for (TryCatchBlockNode node : (List<TryCatchBlockNode>) mn.tryCatchBlocks) {
        final LabelNode startLabel = node.start;
        final int startTarget = mn.instructions.indexOf(startLabel);

        final LabelNode endLabel = node.end;
        final int endTarget = mn.instructions.indexOf(endLabel);

        final int handlerTarget = mn.instructions.indexOf(node.handler);
        IBlock handler = getBlockForInstruction(node.handler, mn, blocks);

        for (int i = startTarget; i <= endTarget; i++) {
            if (i != handlerTarget) {
                getBlockForInstruction(i, blocks).addExceptionHandler(handler, node.type);
            }
        }
    }

    // merge adjacent instructions
    final Set<Integer> linesBeforeMerge = new HashSet<>();
    for (IBlock block : blocks.values()) {
        linesBeforeMerge.addAll(block.getInstructionNums());
    }

    final List<IBlock> result = mergeBlocks(blocks, mn);

    if (debug) {
        System.out.println("################ Control-blocks merged ################");
    }
    // sanity check
    final Set<Integer> linesAfterMerge = new HashSet<>();
    for (IBlock block : result) {
        linesAfterMerge.addAll(block.getInstructionNums());
        if (debug) {
            System.out.println("-----");
            System.out.println(block + " has " + block.getByteCodeInstructionCount(mn) + " instructions.");
            System.out.println(block.disassemble(mn, false, true));
        }
        for (Edge e : block.getEdges()) {
            if (!result.contains(e.src) && e.src != methodExit) {
                throw new RuntimeException(e + " has src that is not in result list?");
            }
            if (!result.contains(e.dst) && e.dst != methodExit) {
                throw new RuntimeException(e + " has destination that is not in result list?");
            }
        }
    }

    if (!linesBeforeMerge.equals(linesAfterMerge)) {
        throw new RuntimeException("Internal error, line count mismatch before/after control block merge: \n\n"
                + linesBeforeMerge + "\n\n" + linesAfterMerge);
    }

    // add starting block and link it with block that contains the lowest instruction number
    MethodEntry methodEntry = new MethodEntry();
    int lowest = Integer.MAX_VALUE;
    for (Integer i : blocks.keySet()) {
        if (i < lowest) {
            lowest = i;
        }
    }

    final IBlock firstBlock = blocks.get(lowest);
    if (firstBlock.hasRegularPredecessor()) {
        throw new IllegalStateException(firstBlock + " that constrains first instruction has a predecessor?");
    }

    methodEntry.addRegularSuccessor(firstBlock);
    firstBlock.addRegularPredecessor(methodEntry);
    result.add(0, methodEntry);

    // add end block to results
    result.add(methodExit);//owner+"#"+
    ControlFlowGraph cfg = new ControlFlowGraph(mn, result);
    System.out.println("CFGMAP:" + formatname(owner) + "#" + cfg.getMethod().name);
    graphmap.put(formatname(owner) + "#" + cfg.getMethod().name, cfg);
    return cfg;
}

From source file:de.dynamicfiles.projects.gradle.plugins.javafx.tasks.internal.MonkeyPatcher.java

License:Apache License

private static void doMonkeyPatchFileHandleLeak(ClassReader classReader, ClassWriter classWriter) {
    classReader.accept(new ClassVisitor(Opcodes.ASM5, classWriter) {
        @Override/* w w w  .  j  a  v  a 2  s  . c  om*/
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (!(name.equals(METHOD_TO_MONKEY_PATCH) && desc.equals(METHOD_SIGNATURE_TO_MONKEY_PATCH))) {
                return super.visitMethod(access, name, desc, signature, exceptions);
            }
            // helpful source: http://web.cs.ucla.edu/~msb/cs239-tutorial/
            // "We will do this using the Adapter Pattern. Adapters wrap an object, overriding some of its methods, and delegating to the others."
            // ugly adapter-pattern ... took me more time than I really can tell here <.<
            return getMonkeyPatchedFileHandleLeakMethodVisitor(access, name, desc, signature, exceptions);
        }

        private MethodVisitor getMonkeyPatchedFileHandleLeakMethodVisitor(int access, String name, String desc,
                String signature, String[] exceptions) {
            return new MethodVisitor(Opcodes.ASM5,
                    super.visitMethod(access, name, desc, signature, exceptions)) {

                /*
                 TODO improve detection of lambda-positions, numbers might vary on different compile-versions
                 */
                @Override
                public void visitCode() {
                    // This mostly got generated from ASM itself, except some adjustments for lambda-IDs and removed "visitMaxs()"-call
                    String javalangThrowable = "java/lang/Throwable";
                    String javaioFile = "java/io/File";
                    String javalangString = "java/lang/String";

                    Label l0 = new Label();
                    Label l1 = new Label();
                    Label l2 = new Label();
                    mv.visitTryCatchBlock(l0, l1, l2, javalangThrowable);
                    Label l3 = new Label();
                    Label l4 = new Label();
                    Label l5 = new Label();
                    mv.visitTryCatchBlock(l3, l4, l5, javalangThrowable);
                    Label l6 = new Label();
                    mv.visitTryCatchBlock(l3, l4, l6, null);
                    Label l7 = new Label();
                    Label l8 = new Label();
                    Label l9 = new Label();
                    mv.visitTryCatchBlock(l7, l8, l9, javalangThrowable);
                    Label l10 = new Label();
                    mv.visitTryCatchBlock(l5, l10, l6, null);
                    mv.visitInsn(Opcodes.ACONST_NULL);
                    mv.visitVarInsn(Opcodes.ASTORE, 3);
                    mv.visitVarInsn(Opcodes.ALOAD, 2);
                    Label l11 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l11);
                    mv.visitVarInsn(Opcodes.ALOAD, 2);
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, javaioFile, "isDirectory", "()Z", false);
                    Label l12 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNE, l12);
                    mv.visitLabel(l11);
                    mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] { javalangString }, 0, null);
                    mv.visitTypeInsn(Opcodes.NEW, javaioFile);
                    mv.visitInsn(Opcodes.DUP);
                    mv.visitLdcInsn("java.home");
                    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "getProperty",
                            "(Ljava/lang/String;)Ljava/lang/String;", false);
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, javaioFile, "<init>", "(Ljava/lang/String;)V",
                            false);
                    mv.visitVarInsn(Opcodes.ASTORE, 2);
                    mv.visitLabel(l12);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitFieldInsn(Opcodes.GETSTATIC, "com/oracle/tools/packager/windows/WinAppBundler",
                            "VS_VERS", "[Ljava/lang/String;");
                    mv.visitVarInsn(Opcodes.ASTORE, 4);
                    mv.visitVarInsn(Opcodes.ALOAD, 4);
                    mv.visitInsn(Opcodes.ARRAYLENGTH);
                    mv.visitVarInsn(Opcodes.ISTORE, 5);
                    mv.visitInsn(Opcodes.ICONST_0);
                    mv.visitVarInsn(Opcodes.ISTORE, 6);
                    Label l13 = new Label();
                    mv.visitLabel(l13);
                    mv.visitFrame(Opcodes.F_APPEND, 3,
                            new Object[] { "[Ljava/lang/String;", Opcodes.INTEGER, Opcodes.INTEGER }, 0, null);
                    mv.visitVarInsn(Opcodes.ILOAD, 6);
                    mv.visitVarInsn(Opcodes.ILOAD, 5);
                    Label l14 = new Label();
                    mv.visitJumpInsn(Opcodes.IF_ICMPGE, l14);
                    mv.visitVarInsn(Opcodes.ALOAD, 4);
                    mv.visitVarInsn(Opcodes.ILOAD, 6);
                    mv.visitInsn(Opcodes.AALOAD);
                    mv.visitVarInsn(Opcodes.ASTORE, 7);
                    mv.visitVarInsn(Opcodes.ALOAD, 0);
                    mv.visitVarInsn(Opcodes.ALOAD, 1);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/oracle/tools/packager/windows/WinAppBundler",
                            "copyMSVCDLLs", "(Ljava/io/File;Ljava/lang/String;)Z", false);
                    Label l15 = new Label();
                    mv.visitJumpInsn(Opcodes.IFEQ, l15);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    mv.visitVarInsn(Opcodes.ASTORE, 3);
                    mv.visitJumpInsn(Opcodes.GOTO, l14);
                    mv.visitLabel(l15);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitIincInsn(6, 1);
                    mv.visitJumpInsn(Opcodes.GOTO, l13);
                    mv.visitLabel(l14);
                    mv.visitFrame(Opcodes.F_CHOP, 3, null, 0, null);
                    mv.visitVarInsn(Opcodes.ALOAD, 3);
                    Label l16 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNONNULL, l16);
                    mv.visitTypeInsn(Opcodes.NEW, "java/lang/RuntimeException");
                    mv.visitInsn(Opcodes.DUP);
                    mv.visitLdcInsn("Not found MSVC dlls");
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>",
                            "(Ljava/lang/String;)V", false);
                    mv.visitInsn(Opcodes.ATHROW);
                    mv.visitLabel(l16);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitTypeInsn(Opcodes.NEW, "java/util/concurrent/atomic/AtomicReference");
                    mv.visitInsn(Opcodes.DUP);
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/concurrent/atomic/AtomicReference",
                            "<init>", "()V", false);
                    mv.visitVarInsn(Opcodes.ASTORE, 4);
                    mv.visitVarInsn(Opcodes.ALOAD, 3);
                    mv.visitVarInsn(Opcodes.ASTORE, 5);
                    mv.visitVarInsn(Opcodes.ALOAD, 2);
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, javaioFile, "toPath", "()Ljava/nio/file/Path;",
                            false);
                    mv.visitLdcInsn("bin");
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/nio/file/Path", "resolve",
                            "(Ljava/lang/String;)Ljava/nio/file/Path;", true);
                    mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/nio/file/Files", "list",
                            "(Ljava/nio/file/Path;)Ljava/util/stream/Stream;", false);
                    mv.visitVarInsn(Opcodes.ASTORE, 6);
                    mv.visitInsn(Opcodes.ACONST_NULL);
                    mv.visitVarInsn(Opcodes.ASTORE, 7);
                    mv.visitLabel(l3);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitInvokeDynamicInsn("test", "()Ljava/util/function/Predicate;", new Handle(
                            Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory",
                            "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                            new Object[] { Type.getType("(Ljava/lang/Object;)Z"),
                                    new Handle(Opcodes.H_INVOKESTATIC,
                                            "com/oracle/tools/packager/windows/WinAppBundler",
                                            "lambda$copyMSVCDLLs$261", "(Ljava/nio/file/Path;)Z"),
                                    Type.getType("(Ljava/nio/file/Path;)Z") }); // modified lambda-name
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "filter",
                            "(Ljava/util/function/Predicate;)Ljava/util/stream/Stream;", true);
                    mv.visitVarInsn(Opcodes.ALOAD, 5);
                    mv.visitInvokeDynamicInsn("test", "(Ljava/lang/String;)Ljava/util/function/Predicate;",
                            new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory",
                                    "metafactory",
                                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                            new Object[] { Type.getType("(Ljava/lang/Object;)Z"), new Handle(
                                    Opcodes.H_INVOKESTATIC, "com/oracle/tools/packager/windows/WinAppBundler",
                                    "lambda$copyMSVCDLLs$262", "(Ljava/lang/String;Ljava/nio/file/Path;)Z"),
                                    Type.getType("(Ljava/nio/file/Path;)Z") }); // modified lambda-name
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "filter",
                            "(Ljava/util/function/Predicate;)Ljava/util/stream/Stream;", true);
                    mv.visitVarInsn(Opcodes.ALOAD, 1);
                    mv.visitVarInsn(Opcodes.ALOAD, 4);
                    mv.visitInvokeDynamicInsn("accept",
                            "(Ljava/io/File;Ljava/util/concurrent/atomic/AtomicReference;)Ljava/util/function/Consumer;",
                            new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory",
                                    "metafactory",
                                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"),
                            new Object[] { Type.getType("(Ljava/lang/Object;)V"), new Handle(
                                    Opcodes.H_INVOKESTATIC, "com/oracle/tools/packager/windows/WinAppBundler",
                                    "lambda$copyMSVCDLLs$263",
                                    "(Ljava/io/File;Ljava/util/concurrent/atomic/AtomicReference;Ljava/nio/file/Path;)V"),
                                    Type.getType("(Ljava/nio/file/Path;)V") }); // modified lambda-name
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "forEach",
                            "(Ljava/util/function/Consumer;)V", true);
                    mv.visitLabel(l4);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    Label l17 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l17);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    Label l18 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l18);
                    mv.visitLabel(l0);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "close", "()V",
                            true);
                    mv.visitLabel(l1);
                    mv.visitJumpInsn(Opcodes.GOTO, l17);
                    mv.visitLabel(l2);
                    mv.visitFrame(Opcodes.F_FULL, 8,
                            new Object[] { "com/oracle/tools/packager/windows/WinAppBundler", javaioFile,
                                    javaioFile, javalangString, "java/util/concurrent/atomic/AtomicReference",
                                    javalangString, "java/util/stream/Stream", javalangThrowable },
                            1, new Object[] { javalangThrowable });
                    mv.visitVarInsn(Opcodes.ASTORE, 8);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    mv.visitVarInsn(Opcodes.ALOAD, 8);
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, javalangThrowable, "addSuppressed",
                            "(Ljava/lang/Throwable;)V", false);
                    mv.visitJumpInsn(Opcodes.GOTO, l17);
                    mv.visitLabel(l18);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "close", "()V",
                            true);
                    mv.visitJumpInsn(Opcodes.GOTO, l17);
                    mv.visitLabel(l5);
                    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { javalangThrowable });
                    mv.visitVarInsn(Opcodes.ASTORE, 8);
                    mv.visitVarInsn(Opcodes.ALOAD, 8);
                    mv.visitVarInsn(Opcodes.ASTORE, 7);
                    mv.visitVarInsn(Opcodes.ALOAD, 8);
                    mv.visitInsn(Opcodes.ATHROW);
                    mv.visitLabel(l6);
                    mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { javalangThrowable });
                    mv.visitVarInsn(Opcodes.ASTORE, 9);
                    mv.visitLabel(l10);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    Label l19 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l19);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    Label l20 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l20);
                    mv.visitLabel(l7);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "close", "()V",
                            true);
                    mv.visitLabel(l8);
                    mv.visitJumpInsn(Opcodes.GOTO, l19);
                    mv.visitLabel(l9);
                    mv.visitFrame(Opcodes.F_FULL, 10,
                            new Object[] { "com/oracle/tools/packager/windows/WinAppBundler", javaioFile,
                                    javaioFile, javalangString, "java/util/concurrent/atomic/AtomicReference",
                                    javalangString, "java/util/stream/Stream", javalangThrowable, Opcodes.TOP,
                                    javalangThrowable },
                            1, new Object[] { javalangThrowable });
                    mv.visitVarInsn(Opcodes.ASTORE, 10);
                    mv.visitVarInsn(Opcodes.ALOAD, 7);
                    mv.visitVarInsn(Opcodes.ALOAD, 10);
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, javalangThrowable, "addSuppressed",
                            "(Ljava/lang/Throwable;)V", false);
                    mv.visitJumpInsn(Opcodes.GOTO, l19);
                    mv.visitLabel(l20);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/stream/Stream", "close", "()V",
                            true);
                    mv.visitLabel(l19);
                    mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
                    mv.visitVarInsn(Opcodes.ALOAD, 9);
                    mv.visitInsn(Opcodes.ATHROW);
                    mv.visitLabel(l17);
                    mv.visitFrame(Opcodes.F_FULL, 6,
                            new Object[] { "com/oracle/tools/packager/windows/WinAppBundler", javaioFile,
                                    javaioFile, javalangString, "java/util/concurrent/atomic/AtomicReference",
                                    javalangString },
                            0, new Object[] {});
                    mv.visitVarInsn(Opcodes.ALOAD, 4);
                    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicReference",
                            "get", "()Ljava/lang/Object;", false);
                    mv.visitTypeInsn(Opcodes.CHECKCAST, "java/io/IOException");
                    mv.visitVarInsn(Opcodes.ASTORE, 6);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    Label l21 = new Label();
                    mv.visitJumpInsn(Opcodes.IFNULL, l21);
                    mv.visitVarInsn(Opcodes.ALOAD, 6);
                    mv.visitInsn(Opcodes.ATHROW);
                    mv.visitLabel(l21);
                    mv.visitFrame(Opcodes.F_APPEND, 1, new Object[] { "java/io/IOException" }, 0, null);
                    mv.visitInsn(Opcodes.RETURN);
                }

            };
        }

    }, ClassReader.EXPAND_FRAMES); // ClassReader.EXPAND_FRAMES required for Java 8
}

From source file:de.scoopgmbh.copper.instrument.TryCatchBlockHandler.java

License:Apache License

@SuppressWarnings("unchecked")
public void instrument(ClassNode cn) {
    //if (1 == 1) return;

    for (MethodNode m : (List<MethodNode>) cn.methods) {
        if (!m.exceptions.contains(INTERRUPT_EXCEPTION_NAME) || m.tryCatchBlocks.isEmpty()) {
            continue;
        }/*from w ww .j  a va 2s  .c  om*/
        logger.info("Instrument " + cn.name + "." + m.name);
        HashSet<Label> labels = new HashSet<Label>();
        for (TryCatchBlockNode catchNode : (List<TryCatchBlockNode>) m.tryCatchBlocks) {
            if (labels.contains(catchNode.handler.getLabel())) {
                // some handlers share their handling code - check it out to prevent double instrumentation
                logger.info("skipping node");
                continue;
            }
            labels.add(catchNode.handler.getLabel());

            LabelNode labelNode = catchNode.handler;
            AbstractInsnNode lineNumberNode = labelNode.getNext() instanceof LineNumberNode
                    ? labelNode.getNext()
                    : labelNode;
            FrameNode frameNode = (FrameNode) lineNumberNode.getNext();
            VarInsnNode varInsnNode = (VarInsnNode) frameNode.getNext();
            AbstractInsnNode insertPoint = varInsnNode;

            if (catchNode.type == null) {
                // this is probably a finally block;
                if (insertPoint.getNext() != null && insertPoint.getNext() instanceof LabelNode) {
                    insertPoint = insertPoint.getNext();
                }
            }

            LabelNode labelNode4ifeg = new LabelNode();
            InsnList newCode = new InsnList();
            newCode.add(new VarInsnNode(Opcodes.ALOAD, varInsnNode.var));
            newCode.add(new TypeInsnNode(Opcodes.INSTANCEOF, INTERRUPT_EXCEPTION_NAME));
            newCode.add(new JumpInsnNode(Opcodes.IFEQ, labelNode4ifeg));
            newCode.add(new VarInsnNode(Opcodes.ALOAD, varInsnNode.var));
            newCode.add(new TypeInsnNode(Opcodes.CHECKCAST, INTERRUPT_EXCEPTION_NAME));
            newCode.add(new InsnNode(Opcodes.ATHROW));
            newCode.add(labelNode4ifeg);
            m.instructions.insert(insertPoint, newCode);
        }
    }
}