Example usage for org.objectweb.asm.tree InsnList getFirst

List of usage examples for org.objectweb.asm.tree InsnList getFirst

Introduction

In this page you can find the example usage for org.objectweb.asm.tree InsnList getFirst.

Prototype

public AbstractInsnNode getFirst() 

Source Link

Document

Returns the first instruction in this list.

Usage

From source file:analysis.ReferenceGenerator.java

License:Open Source License

private void refInstructions(InsnList insnList) {
    AbstractInsnNode insn;/*from w  ww .  j  a  v  a  2  s .c o  m*/

    insn = insnList.getFirst();

    Object cst;

    while (insn != null) {
        switch (insn.getType()) {
        case AbstractInsnNode.FIELD_INSN:
            //addTypeClassRef(Type.getType(((FieldInsnNode)insn).desc));
            addFieldRef(((FieldInsnNode) insn).owner, ((FieldInsnNode) insn).name);
            break;
        /*case AbstractInsnNode.INVOKE_DYNAMIC_INSN:
                   
           break;*/
        /*case AbstractInsnNode.LDC_INSN:
           cst = ((LdcInsnNode)insn).cst;
           if(cst instanceof Type) {
              addTypeClassRef((Type)cst);
           }
           break;*/
        case AbstractInsnNode.METHOD_INSN:
            addMethodRef(((MethodInsnNode) insn).owner, ((MethodInsnNode) insn).name,
                    ((MethodInsnNode) insn).desc);
            break;
        case AbstractInsnNode.MULTIANEWARRAY_INSN:
            addTypeClassRef(Type.getType(((MultiANewArrayInsnNode) insn).desc));
            break;
        case AbstractInsnNode.TYPE_INSN:
            addTypeClassRef(Type.getType(((TypeInsnNode) insn).desc));
            break;
        }
        insn = insn.getNext();
    }
}

From source file:cl.inria.stiq.instrumenter.BCIUtils.java

License:Open Source License

private static InsnList cloneInstructions(ClonerMap aMap, InsnList aList) {
    InsnList theInsnListClone = new InsnList();
    AbstractInsnNode theNode = aList.getFirst();
    while (theNode != null) {
        AbstractInsnNode theClone = theNode.clone(aMap);
        if (theClone instanceof LabelNode) {
            LabelNode theLabelNode = (LabelNode) theClone;
        }/*ww w.  j  ava2  s.c om*/
        theInsnListClone.add(theClone);
        theNode = theNode.getNext();
    }

    return theInsnListClone;
}

From source file:com.android.ide.eclipse.apt.internal.analysis.InternalGetSetAnalyzer.java

License:Apache License

/**
 * Checks if a method is a getter//from   ww w  .j  a v  a 2s .  c om
 * @param methodTest The method to test
 * @return True if the method is a getter, false otherwise
 */
private boolean isGetter(final MethodNode methodTest) {
    boolean getter = false;
    final String desc = methodTest.desc;
    final Type[] arguments = Type.getArgumentTypes(desc);
    final Type returnType = Type.getReturnType(desc);
    if (arguments.length == 0 && returnType.getSort() != Type.VOID) {
        final InsnList instructions = methodTest.instructions;
        //three next to skip label and line number instructions
        final AbstractInsnNode first = instructions.getFirst().getNext().getNext();
        final int returnOp = returnType.getOpcode(Opcodes.IRETURN);
        final int firstOp = first.getOpcode();
        //check for static getter
        if ((Opcodes.ACC_STATIC & methodTest.access) == 0) {
            if (firstOp == Opcodes.ALOAD) {
                final AbstractInsnNode second = first.getNext();
                if (second.getOpcode() == Opcodes.GETFIELD) {
                    final AbstractInsnNode third = second.getNext();
                    if (third.getOpcode() == returnOp) {
                        getter = true;
                    }
                }
            }
        } else {
            if (firstOp == Opcodes.GETSTATIC) {
                final AbstractInsnNode second = first.getNext();
                if (second.getOpcode() == returnOp) {
                    getter = true;
                }
            }
        }
    }
    return getter;
}

From source file:com.android.ide.eclipse.apt.internal.analysis.InternalGetSetAnalyzer.java

License:Apache License

/**
 * Checks if a method is a setter// w  w w  . j  a v a 2 s .  co  m
 * @param methodTest The method to be checked
 * @return True if the method is a setter, false otherwise
 */
private boolean isSetter(final MethodNode methodTest) {
    boolean setter = false;
    final String desc = methodTest.desc;
    final Type[] arguments = Type.getArgumentTypes(desc);
    final Type returnType = Type.getReturnType(desc);
    if (arguments.length == 1 && returnType.getSort() == Type.VOID) {
        final InsnList instructions = methodTest.instructions;
        //skip label and line number instructions
        final AbstractInsnNode first = instructions.getFirst().getNext().getNext();
        final int loadOp = arguments[0].getOpcode(Opcodes.ILOAD);
        final int firstOp = first.getOpcode();
        //check for static setter
        if ((Opcodes.ACC_STATIC & methodTest.access) == 0) {
            if (firstOp == Opcodes.ALOAD) {
                final AbstractInsnNode second = first.getNext();
                if (second.getOpcode() == loadOp) {
                    final AbstractInsnNode third = second.getNext();
                    if (third.getOpcode() == Opcodes.PUTFIELD) {
                        //three next to skip label and line number instructions
                        final AbstractInsnNode fourth = third.getNext().getNext().getNext();
                        if (fourth.getOpcode() == Opcodes.RETURN) {
                            setter = true;
                        }
                    }
                }
            }
        } else {
            if (firstOp == loadOp) {
                final AbstractInsnNode second = first.getNext();
                if (second.getOpcode() == Opcodes.PUTSTATIC) {
                    final AbstractInsnNode third = second.getNext().getNext().getNext();
                    if (third.getOpcode() == Opcodes.RETURN) {
                        setter = true;
                    }
                }
            }
        }
    }
    return setter;
}

From source file:com.android.tools.lint.checks.FieldGetterDetector.java

License:Apache License

private static Map<String, String> checkMethods(ClassNode classNode, Set<String> names) {
    Map<String, String> validGetters = Maps.newHashMap();
    @SuppressWarnings("rawtypes")
    List methods = classNode.methods;
    String fieldName = null;//  w  w  w .j  av  a 2s .  c  o m
    checkMethod: for (Object methodObject : methods) {
        MethodNode method = (MethodNode) methodObject;
        if (names.contains(method.name) && method.desc.startsWith("()")) { //$NON-NLS-1$ // (): No arguments
            InsnList instructions = method.instructions;
            int mState = 1;
            for (AbstractInsnNode curr = instructions.getFirst(); curr != null; curr = curr.getNext()) {
                switch (curr.getOpcode()) {
                case -1:
                    // Skip label and line number nodes
                    continue;
                case Opcodes.ALOAD:
                    if (mState == 1) {
                        fieldName = null;
                        mState = 2;
                    } else {
                        continue checkMethod;
                    }
                    break;
                case Opcodes.GETFIELD:
                    if (mState == 2) {
                        FieldInsnNode field = (FieldInsnNode) curr;
                        fieldName = field.name;
                        mState = 3;
                    } else {
                        continue checkMethod;
                    }
                    break;
                case Opcodes.ARETURN:
                case Opcodes.FRETURN:
                case Opcodes.IRETURN:
                case Opcodes.DRETURN:
                case Opcodes.LRETURN:
                case Opcodes.RETURN:
                    if (mState == 3) {
                        validGetters.put(method.name, fieldName);
                    }
                    continue checkMethod;
                default:
                    continue checkMethod;
                }
            }
        }
    }

    return validGetters;
}

From source file:com.github.antag99.retinazer.weaver.SystemProcessor.java

License:Open Source License

private void processMethod(MethodNode methodNode) {
    InsnList insns = methodNode.instructions;

    // Filter out debugging nodes/labels
    int count = 0;
    int maxCount = insns.size();
    AbstractInsnNode[] nodes = new AbstractInsnNode[maxCount];
    for (AbstractInsnNode node = insns.getFirst(); node != null; node = node.getNext())
        if (node.getOpcode() > 0)
            nodes[count++] = node;//from   w  w  w.  j  av a 2s  .co  m

    // Find mapper get() calls and create an own flyweight instance for each
    for (int i = 0; i <= count - 4; i++) {
        if (!(nodes[i + 0] instanceof VarInsnNode))
            continue;
        if (!(nodes[i + 1] instanceof FieldInsnNode))
            continue;
        if (!(nodes[i + 2] instanceof VarInsnNode))
            continue;
        if (!(nodes[i + 3] instanceof MethodInsnNode))
            continue;

        VarInsnNode loadThis = (VarInsnNode) nodes[i + 0];
        FieldInsnNode getField = (FieldInsnNode) nodes[i + 1];
        VarInsnNode loadEntity = (VarInsnNode) nodes[i + 2];
        MethodInsnNode getMethod = (MethodInsnNode) nodes[i + 3];

        if (loadThis.var != 0 || loadThis.getOpcode() != ALOAD)
            continue;

        if (!getField.owner.equals(metadata.internalName)
                || !getField.desc.equals("L" + WeaverConstants.MAPPER_NAME + ";")
                || !metadata.mappersByName.containsKey(getField.name))
            continue;
        if (loadEntity.getOpcode() != ILOAD)
            continue;
        if (!getMethod.owner.equals(WeaverConstants.MAPPER_NAME)
                || !getMethod.desc.equals("(I)L" + WeaverConstants.COMPONENT_NAME + ";")
                || !getMethod.name.equals("get"))
            continue;

        SystemMapper mapper = metadata.mappersByName.get(getField.name);

        // Add field to hold the flyweight
        String fieldName = "flyweight$" + flyweightFields.size();
        String fieldDesc = mapper.componentType.getDescriptor();
        FieldNode fieldNode = new FieldNode(ACC_PRIVATE, fieldName, fieldDesc, null, null);
        fieldNode.visitAnnotation("Lcom/github/antag99/retinazer/SkipWire;", true);
        FlyweightField flyweightField = new FlyweightField();
        flyweightField.fieldNode = fieldNode;
        flyweightField.mapper = mapper;
        flyweightFields.add(flyweightField);

        // Rewrite access to use the flyweight
        getField.owner = metadata.internalName;
        getField.name = fieldName;
        getField.desc = fieldDesc;
        insns.insert(getField, new InsnNode(DUP));
        insns.insert(loadEntity, new FieldInsnNode(PUTFIELD, mapper.componentType.getInternalName(),
                WeaverConstants.INDEX_FIELD_NAME, WeaverConstants.INDEX_FIELD_DESC));
        insns.remove(getMethod);
    }
}

From source file:com.github.fge.grappa.transform.process.SuperCallRewriter.java

License:Apache License

@Override
public void process(@Nonnull ParserClassNode classNode, @Nonnull RuleMethod method) throws Exception {
    Objects.requireNonNull(classNode, "classNode");
    Objects.requireNonNull(method, "method");
    InsnList instructions = method.instructions;
    AbstractInsnNode insn = instructions.getFirst();
    while (insn.getOpcode() != ARETURN) {
        if (insn.getOpcode() == INVOKESPECIAL)
            process(classNode, method, (MethodInsnNode) insn);
        insn = insn.getNext();//from  w w  w  . j a  va 2  s. co m
    }
}

From source file:com.liferay.portal.nio.intraband.proxy.IntrabandProxyUtilTest.java

License:Open Source License

private void _doTestToClass(boolean proxyClassesDumpEnabled, boolean logEnabled) throws FileNotFoundException {

    class TestClass {
    }//from   w  w w.j  a  va  2 s.c om

    ClassNode classNode = _loadClass(TestClass.class);

    MethodNode methodNode = new MethodNode(Opcodes.ACC_PUBLIC, "<clinit>", "()V", null, null);

    methodNode.visitCode();
    methodNode.visitInsn(Opcodes.RETURN);
    methodNode.visitEnd();

    List<MethodNode> methodNodes = classNode.methods;

    methodNodes.add(methodNode);

    ClassLoader classLoader = new URLClassLoader(new URL[0], null);

    Level level = Level.WARNING;

    if (logEnabled) {
        level = Level.INFO;
    }

    try (CaptureHandler captureHandler = JDKLoggerTestUtil
            .configureJDKLogger(IntrabandProxyUtil.class.getName(), level)) {

        List<LogRecord> logRecords = captureHandler.getLogRecords();

        IntrabandProxyUtil.toClass(classNode, classLoader);

        if (proxyClassesDumpEnabled) {
            StringBundler sb = new StringBundler(6);

            sb.append(SystemProperties.get(SystemProperties.TMP_DIR));
            sb.append(StringPool.SLASH);
            sb.append(PropsValues.INTRABAND_PROXY_DUMP_CLASSES_DIR);
            sb.append(StringPool.SLASH);
            sb.append(classNode.name);
            sb.append(".class");

            String filePath = sb.toString();

            File classFile = new File(filePath);

            Assert.assertTrue(classFile.exists());

            ClassNode reloadedClassNode = _loadClass(new FileInputStream(classFile));

            MethodNode clinitMethodNode = ASMUtil.findMethodNode(reloadedClassNode.methods, "<clinit>",
                    Type.VOID_TYPE);

            InsnList insnList = clinitMethodNode.instructions;

            Assert.assertEquals(1, insnList.size());

            _assertInsnNode(insnList.getFirst(), Opcodes.RETURN);

            if (logEnabled) {
                Assert.assertEquals(1, logRecords.size());

                LogRecord logRecord = logRecords.get(0);

                Assert.assertEquals(logRecord.getMessage(), "Dumpped class ".concat(filePath));
            }
        }

        if (!proxyClassesDumpEnabled || !logEnabled) {
            Assert.assertTrue(logRecords.isEmpty());
        }
    }

    try {
        IntrabandProxyUtil.toClass(classNode, classLoader);

        Assert.fail();
    } catch (RuntimeException re) {
        Throwable throwable = re.getCause();

        Assert.assertSame(InvocationTargetException.class, throwable.getClass());

        throwable = throwable.getCause();

        Assert.assertSame(LinkageError.class, throwable.getClass());

        String message = throwable.getMessage();

        Assert.assertTrue(message.contains(
                "duplicate class definition for name: \"" + Type.getInternalName(TestClass.class) + "\""));
    }
}

From source file:com.lodgon.parboiled.transform.SuperCallRewriter.java

License:Apache License

public void process(ParserClassNode classNode, RuleMethod method) throws Exception {
    checkArgNotNull(classNode, "classNode");
    checkArgNotNull(method, "method");
    InsnList instructions = method.instructions;
    AbstractInsnNode insn = instructions.getFirst();
    while (insn.getOpcode() != ARETURN) {
        if (insn.getOpcode() == INVOKESPECIAL) {
            process(classNode, method, (MethodInsnNode) insn);
        }//  w  ww. j  a  v  a  2s  .  c om
        insn = insn.getNext();
    }
}

From source file:com.triage.bytecodemaster.TestObjectReferenceSwitches.java

public void testReplacingThisWithOtherVariable() throws Exception {

    final String FIELDPROXYWORKED = "FIELDPROXYWORKED";

    //set up the proxy object. this is the object that will receive
    //the proxied calls
    TestSubClass tcc = new TestSubClass();
    tcc.setBaseString(FIELDPROXYWORKED);

    TestBaseClassHolder.setTestBase(tcc);

    //get the dynamic source that has the donor body in it
    ClassNode donorSource = loadGroovyTestClassAsBytecode(GROOVY_CLASS_FIELDREF);
    MethodNode donorMethod = findMethod(donorSource, "before_whatDoIThinkAbout");

    System.out.println("Donor");
    printMethodNode(donorMethod);//from  ww  w  .ja  v  a 2  s. co  m

    //alright here's the strategy:  (1) inject a new local variable that points 
    //   to our remote instance,
    //  (2) inject code that sets this local to the value of a method call,
    //  (3) change references to 'this' ( ALOAD0 or ALOAD 0 ) to ALOAD1

    InsnList instructionsToInject = donorMethod.instructions;

    //make a new local variable
    LabelNode begin = new LabelNode();
    LabelNode end = new LabelNode();
    instructionsToInject.insertBefore(instructionsToInject.getFirst(), begin);
    instructionsToInject.add(end);

    Type type = Type.getObjectType("com/triage/bytecodemaster/fortesting/TestBaseClass");
    int variableIndex = donorMethod.maxLocals;
    donorMethod.maxLocals += type.getSize();
    donorMethod.visitLocalVariable("proxy", type.getDescriptor(), null, begin.getLabel(), end.getLabel(),
            variableIndex);

    //set the value of the local variable with a new instruction at the top
    //fetch a reference to our proxy object
    MethodInsnNode getTestBase = new MethodInsnNode(Opcodes.INVOKESTATIC,
            "com/triage/bytecodemaster/fortesting/TestBaseClassHolder", "getTestBase",
            "()Lcom/triage/bytecodemaster/fortesting/TestBaseClass;");

    //insert after begin label
    instructionsToInject.insert(begin, getTestBase);

    //store reference
    VarInsnNode setRef = new VarInsnNode(Opcodes.ASTORE, variableIndex);

    //insert store after fetch
    instructionsToInject.insert(getTestBase, setRef);

    //replace all references to 'this'  with the new variable

    for (int currentIndex = 0; currentIndex < instructionsToInject.size(); currentIndex++) {
        AbstractInsnNode node = instructionsToInject.get(currentIndex);
        if (node.getOpcode() == Opcodes.ALOAD) {
            VarInsnNode vin = (VarInsnNode) node;

            //'this' is var index 0. ours is var index varindex
            if (vin.var == 0) {
                vin.var = variableIndex;
            }
        }
    }

    System.out.println(">>>>>>>>>Finished Modifying<<<<<<<<");
    printMethodNode(donorMethod);
    String NEWCLASSNAME = "ScriptTestClass";

    //write a class 
    Class c = createClassFromClassNode(donorSource, NEWCLASSNAME);

    Object o = c.newInstance();
    Method m = o.getClass().getDeclaredMethod("before_whatDoIThinkAbout", String.class);

    //should return HAHAHA not baseStringValue 
    String result = (String) m.invoke(o, new Object[] { "AAAA" });
    System.out.println("TestDonorClass.whatDoIThinkAbout Result: " + result);
    assertTrue(result.equals(FIELDPROXYWORKED + "AAAA"));
}