Search in sources :

Example 11 with AbstractInsnNode

use of org.objectweb.asm.tree.AbstractInsnNode in project jacoco by jacoco.

the class FinallyTest method gotos.

/**
 * This test studies placement of GOTO instructions.
 */
@Test
public void gotos() throws IOException {
    final Source source = Source.getSourceFor("src", Finally.class);
    byte[] b = TargetLoader.getClassDataAsBytes(Finally.class);
    b = BytecodeVersion.downgradeIfNeeded(BytecodeVersion.get(b), b);
    final ClassNode classNode = new ClassNode();
    new ClassReader(b).accept(classNode, 0);
    final Set<String> tags = new HashSet<String>();
    for (final MethodNode m : classNode.methods) {
        if ("main".equals(m.name)) {
            // skip it
            continue;
        }
        int lineNumber = -1;
        for (AbstractInsnNode i = m.instructions.getFirst(); i != null; i = i.getNext()) {
            if (AbstractInsnNode.LINE == i.getType()) {
                lineNumber = ((LineNumberNode) i).line;
            }
            if (Opcodes.GOTO == i.getOpcode()) {
                final String line = source.getLine(lineNumber);
                if (line.indexOf('$') < 0) {
                    throw new AssertionError("No tag at line " + lineNumber);
                }
                final String tag = line.substring(line.indexOf('$') + "$line-".length(), line.lastIndexOf('$'));
                tags.add(tag);
            }
        }
    }
    final Set<String> expected = new HashSet<String>();
    if (isJDKCompiler) {
        expected.add("example.2");
    } else {
        expected.add("example.0");
    }
    expected.add("breakStatement.for");
    if (isJDKCompiler) {
        if (JAVA_VERSION.isBefore("10")) {
            // https://bugs.openjdk.java.net/browse/JDK-8180141
            expected.add("breakStatement.1");
        } else {
            expected.add("breakStatement");
        }
        expected.add("breakStatement.2");
    } else {
        expected.add("breakStatement");
    }
    if (isJDKCompiler) {
        expected.add("emptyCatch.2");
    } else {
        expected.add("emptyCatch");
        expected.add("emptyCatch.1");
    }
    if (isJDKCompiler) {
        expected.add("catchNotExecuted.2");
    } else {
        expected.add("catchNotExecuted");
        expected.add("catchNotExecuted.1");
    }
    if (isJDKCompiler) {
        expected.add("nested.5");
        expected.add("nested.6");
    } else {
        expected.add("nested.0");
        expected.add("nested.3");
    }
    if (isJDKCompiler && JAVA_VERSION.isBefore("1.8")) {
        expected.add("emptyTry.2");
    }
    if (!isJDKCompiler) {
        expected.add("alwaysCompletesAbruptly.0");
    }
    assertEquals(expected, tags);
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) MethodNode(org.objectweb.asm.tree.MethodNode) ClassReader(org.objectweb.asm.ClassReader) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) Source(org.jacoco.core.test.validation.Source) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 12 with AbstractInsnNode

use of org.objectweb.asm.tree.AbstractInsnNode in project jacoco by jacoco.

the class StructuredLockingTest method assertStructuredLocking.

private void assertStructuredLocking(String owner, MethodNode mn) throws Exception {
    Analyzer<BasicValue> analyzer = new Analyzer<BasicValue>(new BasicInterpreter()) {

        @Override
        protected Frame<BasicValue> newFrame(int nLocals, int nStack) {
            return new LockFrame(nLocals, nStack);
        }

        @Override
        protected Frame<BasicValue> newFrame(Frame<? extends BasicValue> src) {
            return new LockFrame(src);
        }
    };
    Frame<BasicValue>[] frames = analyzer.analyze(owner, mn);
    // Make sure no locks are left when method exits:
    for (int i = 0; i < frames.length; i++) {
        AbstractInsnNode insn = mn.instructions.get(i);
        switch(insn.getOpcode()) {
            case Opcodes.IRETURN:
            case Opcodes.LRETURN:
            case Opcodes.FRETURN:
            case Opcodes.DRETURN:
            case Opcodes.ARETURN:
            case Opcodes.RETURN:
                ((LockFrame) frames[i]).assertNoLock("Exit with lock");
                break;
            case Opcodes.ATHROW:
                List<TryCatchBlockNode> handlers = analyzer.getHandlers(i);
                if (handlers == null || handlers.isEmpty()) {
                    ((LockFrame) frames[i]).assertNoLock("Exit with lock");
                }
                break;
        }
    }
    // Only instructions protected by a catch-all handler can hold locks:
    for (int i = 0; i < frames.length; i++) {
        AbstractInsnNode insn = mn.instructions.get(i);
        if (insn.getOpcode() > 0) {
            boolean catchAll = false;
            List<TryCatchBlockNode> handlers = analyzer.getHandlers(i);
            if (handlers != null) {
                for (TryCatchBlockNode node : handlers) {
                    catchAll |= node.type == null;
                }
            }
            if (!catchAll) {
                ((LockFrame) frames[i]).assertNoLock("No handlers for insn with lock");
            }
        }
    }
}
Also used : TryCatchBlockNode(org.objectweb.asm.tree.TryCatchBlockNode) Frame(org.objectweb.asm.tree.analysis.Frame) BasicInterpreter(org.objectweb.asm.tree.analysis.BasicInterpreter) Analyzer(org.objectweb.asm.tree.analysis.Analyzer) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) BasicValue(org.objectweb.asm.tree.analysis.BasicValue)

Example 13 with AbstractInsnNode

use of org.objectweb.asm.tree.AbstractInsnNode in project sonar-java by SonarSource.

the class BytecodeCFGBuilderTest method test_all_instructions_are_part_of_CFG.

@Test
public void test_all_instructions_are_part_of_CFG() throws Exception {
    SquidClassLoader squidClassLoader = new SquidClassLoader(Lists.newArrayList(new File("target/test-classes"), new File("target/classes")));
    File file = new File("src/test/java/org/sonar/java/bytecode/cfg/testdata/CFGTestData.java");
    CompilationUnitTree tree = (CompilationUnitTree) JavaParser.createParser().parse(file);
    SemanticModel.createFor(tree, squidClassLoader);
    Symbol.TypeSymbol testClazz = ((ClassTree) tree.types().get(0)).symbol();
    ClassReader cr = new ClassReader(squidClassLoader.getResourceAsStream(Convert.bytecodeName(CFGTestData.class.getCanonicalName()) + ".class"));
    ClassNode classNode = new ClassNode(Opcodes.ASM5);
    cr.accept(classNode, 0);
    for (MethodNode method : classNode.methods) {
        Multiset<String> opcodes = Arrays.stream(method.instructions.toArray()).map(AbstractInsnNode::getOpcode).filter(opcode -> opcode != -1).map(opcode -> Printer.OPCODES[opcode]).collect(Collectors.toCollection(HashMultiset::create));
        Symbol methodSymbol = Iterables.getOnlyElement(testClazz.lookupSymbols(method.name));
        BytecodeCFG bytecodeCFG = SETestUtils.bytecodeCFG(((JavaSymbol.MethodJavaSymbol) methodSymbol).completeSignature(), squidClassLoader);
        Multiset<String> cfgOpcodes = cfgOpcodes(bytecodeCFG);
        assertThat(cfgOpcodes).isEqualTo(opcodes);
    }
}
Also used : Iterables(com.google.common.collect.Iterables) Arrays(java.util.Arrays) JavaSymbol(org.sonar.java.resolve.JavaSymbol) H_INVOKESTATIC(org.objectweb.asm.Opcodes.H_INVOKESTATIC) Multiset(com.google.common.collect.Multiset) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SETestUtils(org.sonar.java.se.SETestUtils) NO_OPERAND_INSN(org.sonar.java.bytecode.cfg.Instructions.NO_OPERAND_INSN) Label(org.objectweb.asm.Label) CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) VAR_INSN(org.sonar.java.bytecode.cfg.Instructions.VAR_INSN) MethodNode(org.objectweb.asm.tree.MethodNode) INVOKEINTERFACE(org.objectweb.asm.Opcodes.INVOKEINTERFACE) Lists(com.google.common.collect.Lists) CFGTestData(org.sonar.java.bytecode.cfg.testdata.CFGTestData) HashMultiset(com.google.common.collect.HashMultiset) FIELD_INSN(org.sonar.java.bytecode.cfg.Instructions.FIELD_INSN) JUMP_INSN(org.sonar.java.bytecode.cfg.Instructions.JUMP_INSN) METHOD_INSN(org.sonar.java.bytecode.cfg.Instructions.METHOD_INSN) JavaParser(org.sonar.java.ast.parser.JavaParser) NOP(org.objectweb.asm.Opcodes.NOP) Opcodes(org.objectweb.asm.Opcodes) Predicate(java.util.function.Predicate) SquidClassLoader(org.sonar.java.bytecode.loader.SquidClassLoader) IOException(java.io.IOException) Test(org.junit.Test) TYPE_INSN(org.sonar.java.bytecode.cfg.Instructions.TYPE_INSN) Tree(org.sonar.plugins.java.api.tree.Tree) Collectors(java.util.stream.Collectors) File(java.io.File) Objects(java.util.Objects) Handle(org.objectweb.asm.Handle) List(java.util.List) Stream(java.util.stream.Stream) Rule(org.junit.Rule) LogTester(org.sonar.api.utils.log.LogTester) ClassReader(org.objectweb.asm.ClassReader) Printer(org.objectweb.asm.util.Printer) SemanticModel(org.sonar.java.resolve.SemanticModel) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) ClassTree(org.sonar.plugins.java.api.tree.ClassTree) JSR(org.objectweb.asm.Opcodes.JSR) ClassNode(org.objectweb.asm.tree.ClassNode) Convert(org.sonar.java.resolve.Convert) INT_INSN(org.sonar.java.bytecode.cfg.Instructions.INT_INSN) Symbol(org.sonar.plugins.java.api.semantic.Symbol) LoggerLevel(org.sonar.api.utils.log.LoggerLevel) MethodTree(org.sonar.plugins.java.api.tree.MethodTree) ClassNode(org.objectweb.asm.tree.ClassNode) CompilationUnitTree(org.sonar.plugins.java.api.tree.CompilationUnitTree) JavaSymbol(org.sonar.java.resolve.JavaSymbol) Symbol(org.sonar.plugins.java.api.semantic.Symbol) ClassTree(org.sonar.plugins.java.api.tree.ClassTree) SquidClassLoader(org.sonar.java.bytecode.loader.SquidClassLoader) MethodNode(org.objectweb.asm.tree.MethodNode) JavaSymbol(org.sonar.java.resolve.JavaSymbol) ClassReader(org.objectweb.asm.ClassReader) File(java.io.File) Test(org.junit.Test)

Example 14 with AbstractInsnNode

use of org.objectweb.asm.tree.AbstractInsnNode in project MineCamera by PorPit.

the class CamTransformer method initTransformers.

protected void initTransformers() {
    addTransformer(new Transformer("net.minecraft.client.entity.EntityPlayerSP") {

        @Override
        public void transform(ClassNode node) {
            MethodNode m = findMethod(node, "isCurrentViewEntity", "()Z");
            m.instructions.clear();
            m.instructions.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/porpit/minecamera/transform/CamEventHandler", "shouldPlayerTakeInput", "()Z", false));
            m.instructions.add(new InsnNode(Opcodes.IRETURN));
        }
    });
    addTransformer(new Transformer("net.minecraft.client.renderer.EntityRenderer") {

        @Override
        public void transform(ClassNode node) {
            MethodNode m = findMethod(node, "getMouseOver", "(F)V");
            m.instructions.insert(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/porpit/minecamera/transform/CamEventHandler", "setupMouseHandlerBefore", "()V", false));
            AbstractInsnNode currentNode = null;
            @SuppressWarnings("unchecked") Iterator<AbstractInsnNode> iter = m.instructions.iterator();
            while (iter.hasNext()) {
                currentNode = iter.next();
                if (currentNode instanceof InsnNode && ((InsnNode) currentNode).getOpcode() == RETURN) {
                    m.instructions.insertBefore(currentNode, new MethodInsnNode(Opcodes.INVOKESTATIC, "com/porpit/minecamera/transform/CamEventHandler", "setupMouseHandlerAfter", "()V", false));
                }
            }
        }
    });
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) MethodInsnNode(org.objectweb.asm.tree.MethodInsnNode) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) InsnNode(org.objectweb.asm.tree.InsnNode) IClassTransformer(net.minecraft.launchwrapper.IClassTransformer) MethodNode(org.objectweb.asm.tree.MethodNode) MethodInsnNode(org.objectweb.asm.tree.MethodInsnNode) Iterator(java.util.Iterator) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode)

Example 15 with AbstractInsnNode

use of org.objectweb.asm.tree.AbstractInsnNode in project MineCamera by PorPit.

the class Transformer method replaceLabelBefore.

public void replaceLabelBefore(InsnList instructions, AbstractInsnNode node, @Nullable ArrayList<AbstractInsnNode> replaceInstructions, int labels, int labelsBefore, boolean keepFirstLabel, boolean deleteFrame) {
    ListIterator<AbstractInsnNode> iterator = instructions.iterator();
    LabelNode searchedLabel = null;
    ArrayList<LabelNode> foundLabels = new ArrayList<LabelNode>();
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof LabelNode)
            foundLabels.add((LabelNode) insn);
        if (areNodesEqual(insn, node)) {
            int index = foundLabels.size() - 1;
            index -= labelsBefore;
            if (index >= 0)
                searchedLabel = foundLabels.get(index);
            labels += labelsBefore;
            break;
        }
    }
    if (searchedLabel != null) {
        boolean found = false;
        int labelCounter = 0;
        iterator = instructions.iterator();
        while (iterator.hasNext()) {
            AbstractInsnNode insn = iterator.next();
            if (found && insn instanceof LabelNode) {
                labelCounter++;
                if (labelCounter >= labels) {
                    if (replaceInstructions != null)
                        for (int i = 0; i < replaceInstructions.size(); i++) instructions.insertBefore(insn, replaceInstructions.get(i));
                    break;
                }
            }
            if (insn == searchedLabel) {
                found = true;
                if (keepFirstLabel)
                    continue;
            }
            if (found)
                if (deleteFrame || !(insn instanceof FrameNode))
                    instructions.remove(insn);
        }
    } else if (node instanceof LineNumberNode)
        System.out.println("COULD NOT FIND NODE line=" + ((LineNumberNode) node).line);
}
Also used : LabelNode(org.objectweb.asm.tree.LabelNode) FrameNode(org.objectweb.asm.tree.FrameNode) ArrayList(java.util.ArrayList) LineNumberNode(org.objectweb.asm.tree.LineNumberNode) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode)

Aggregations

AbstractInsnNode (org.objectweb.asm.tree.AbstractInsnNode)185 MethodInsnNode (org.objectweb.asm.tree.MethodInsnNode)68 MethodNode (org.objectweb.asm.tree.MethodNode)54 InsnList (org.objectweb.asm.tree.InsnList)53 InsnNode (org.objectweb.asm.tree.InsnNode)41 VarInsnNode (org.objectweb.asm.tree.VarInsnNode)38 LdcInsnNode (org.objectweb.asm.tree.LdcInsnNode)37 FieldInsnNode (org.objectweb.asm.tree.FieldInsnNode)35 ClassNode (org.objectweb.asm.tree.ClassNode)33 LabelNode (org.objectweb.asm.tree.LabelNode)27 JumpInsnNode (org.objectweb.asm.tree.JumpInsnNode)26 Test (org.junit.Test)25 Label (org.objectweb.asm.Label)25 ClassReader (org.objectweb.asm.ClassReader)23 TypeInsnNode (org.objectweb.asm.tree.TypeInsnNode)23 HashSet (java.util.HashSet)16 Type (org.objectweb.asm.Type)15 Frame (org.objectweb.asm.tree.analysis.Frame)13 ArrayList (java.util.ArrayList)12 TryCatchBlockNode (org.objectweb.asm.tree.TryCatchBlockNode)11