Java Code Examples for org.apache.bcel.generic.MethodGen#getInstructionList()

The following examples show how to use org.apache.bcel.generic.MethodGen#getInstructionList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnsafeJacksonDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(m);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);

    if (methodGen == null || methodGen.getInstructionList() == null) {
        return; //No instruction .. nothing to do
    }
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
        Location location = i.next();
        Instruction inst = location.getHandle().getInstruction();
        if (inst instanceof InvokeInstruction) {
            InvokeInstruction invoke = (InvokeInstruction) inst;
            String methodName = invoke.getMethodName(cpg);
            if ("enableDefaultTyping".equals(methodName)) {
                JavaClass clz = classContext.getJavaClass();
                bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY)
                        .addClass(clz)
                        .addMethod(clz, m)
                        .addCalledMethod(cpg, invoke)
                        .addSourceLine(classContext, m, location)
                );
            }
        }
    }
}
 
Example 2
Source File: PLSETestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-262:
 */
public void testB262() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    // get the values() method
    final Method m = gen.getMethodAt(0);
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final InstructionList il = mg.getInstructionList();
    // get the invokevirtual instruction
    final InstructionHandle ih = il.findHandle(3);
    final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());
    // without fix, the getClassName() will throw:
    //   java.lang.IllegalArgumentException: Cannot be used on an array type
    final String cn = ii.getClassName(pool);
    assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}
 
Example 3
Source File: ObjectDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException
    {

        MethodGen methodGen = classContext.getMethodGen(m);
        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = classContext.getCFG(m);

        if (methodGen == null || methodGen.getInstructionList() == null) {
            return; //No instruction .. nothing to do
        }

        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
            Location location = i.next();
            Instruction inst = location.getHandle().getInstruction();

            //
            if (inst instanceof InvokeInstruction) {
//                System.out.println(inst.getName());
                InvokeInstruction invoke = (InvokeInstruction) inst;

                String className = invoke.getClassName(cpg);
                if ("java.io.ObjectInputStream".equals(className) || className.contains("InputStream") || InterfaceUtils.isSubtype(className, "java.io.ObjectInputStream")) {

                    String methodName = invoke.getMethodName(cpg);
                    if (OBJECT_INPUTSTREAM_READ_METHODS.contains(methodName)) {

                        JavaClass clz = classContext.getJavaClass();
                        bugReporter.reportBug(new BugInstance(this, OBJECT_DESERIALIZATION_TYPE, HIGH_PRIORITY) //
                                .addClass(clz).addMethod(clz, m).addSourceLine(classContext,m,location));
                    }
                }

            }
        }
    }
 
Example 4
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 5
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 6
Source File: LocalVariableTypeTableTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public Method injection(final JavaClass clazz, Method method, final ConstantPoolGen cp, final int firstStringOffset) {
    final MethodGen methodGen = new MethodGen(method, clazz.getClassName(), cp);

    final InstructionList instructionList = methodGen.getInstructionList();
    instructionList.insert(instructionList.getStart(), makeWillBeAddedInstructionList(methodGen, firstStringOffset));

    methodGen.setMaxStack();
    methodGen.setMaxLocals();

    method = methodGen.getMethod();
    instructionList.dispose();

    return method;
}
 
Example 7
Source File: BCELBenchmark.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();

        ClassGen cg = new ClassGen(clazz);

        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();

            if (il != null) {
                mg.getInstructionList().setPositions();
                mg.setMaxLocals();
                mg.setMaxStack();
            }
            cg.replaceMethod(m, mg.getMethod());
        }

        bh.consume(cg.getJavaClass().getBytes());
    }

    jar.close();
}
 
Example 8
Source File: FindInconsistentSync2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Determine whether or not the the given method is a getter method. I.e.,
 * if it just returns the value of an instance field.
 *
 * @param classContext
 *            the ClassContext for the class containing the method
 * @param method
 *            the method
 */
public static boolean isGetterMethod(ClassContext classContext, Method method) {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return false;
    }
    InstructionList il = methodGen.getInstructionList();
    // System.out.println("Checking getter method: " + method.getName());
    if (il.getLength() > 60) {
        return false;
    }

    int count = 0;
    for (InstructionHandle ih : il) {
        switch (ih.getInstruction().getOpcode()) {
        case Const.GETFIELD:
            count++;
            if (count > 1) {
                return false;
            }
            break;
        case Const.PUTFIELD:
        case Const.BALOAD:
        case Const.CALOAD:
        case Const.DALOAD:
        case Const.FALOAD:
        case Const.IALOAD:
        case Const.LALOAD:
        case Const.SALOAD:
        case Const.AALOAD:
        case Const.BASTORE:
        case Const.CASTORE:
        case Const.DASTORE:
        case Const.FASTORE:
        case Const.IASTORE:
        case Const.LASTORE:
        case Const.SASTORE:
        case Const.AASTORE:
        case Const.PUTSTATIC:
            return false;
        case Const.INVOKESTATIC:
        case Const.INVOKEVIRTUAL:
        case Const.INVOKEINTERFACE:
        case Const.INVOKESPECIAL:
        case Const.GETSTATIC:
            // no-op

        }
    }
    // System.out.println("Found getter method: " + method.getName());
    return true;
}
 
Example 9
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example 10
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example 11
Source File: helloify.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Patch a method.
 */
private static Method helloifyMethod(Method m) {
    final Code code = m.getCode();
    final int flags = m.getAccessFlags();
    final String name = m.getName();

    // Sanity check
    if (m.isNative() || m.isAbstract() || (code == null)) {
        return m;
    }

    // Create instruction list to be inserted at method start.
    final String mesg = "Hello from " + Utility.methodSignatureToString(m.getSignature(),
            name,
            Utility.accessToString(flags));
    final InstructionList patch = new InstructionList();
    patch.append(new GETSTATIC(out));
    patch.append(new PUSH(cp, mesg));
    patch.append(new INVOKEVIRTUAL(println));

    final MethodGen mg = new MethodGen(m, class_name, cp);
    final InstructionList il = mg.getInstructionList();
    final InstructionHandle[] ihs = il.getInstructionHandles();

    if (name.equals("<init>")) { // First let the super or other constructor be called
        for (int j = 1; j < ihs.length; j++) {
            if (ihs[j].getInstruction() instanceof INVOKESPECIAL) {
                il.append(ihs[j], patch); // Should check: method name == "<init>"
                break;
            }
        }
    } else {
        il.insert(ihs[0], patch);
    }

    // Stack size must be at least 2, since the println method takes 2 argument.
    if (code.getMaxStack() < 2) {
        mg.setMaxStack(2);
    }

    m = mg.getMethod();

    il.dispose(); // Reuse instruction handles

    return m;
}
 
Example 12
Source File: Peephole.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private static Method removeNOPs(final MethodGen mg) {
    final InstructionList il = mg.getInstructionList();
    final InstructionFinder f = new InstructionFinder(il);
    final String pat = "NOP+"; // Find at least one NOP
    InstructionHandle next = null;
    int count = 0;

    for (final Iterator<InstructionHandle[]> e = f.search(pat); e.hasNext(); ) {
        final InstructionHandle[] match = e.next();
        final InstructionHandle first = match[0];
        final InstructionHandle last = match[match.length - 1];

        // Some nasty Java compilers may add NOP at end of method.
        if ((next = last.getNext()) == null) {
            break;
        }

        count += match.length;

        // Delete NOPs and redirect any references to them to the following (non-nop) instruction.
        try {
            il.delete(first, last);
        } catch (final TargetLostException e2) {
            for (final InstructionHandle target : e2.getTargets()) {
                for (final InstructionTargeter targeter : target.getTargeters()) {
                    targeter.updateTarget(target, next);
                }
            }
        }
    }

    Method m = null;

    if (count > 0) {
        System.out.println("Removed " + count + " NOP instructions from method " + mg.getName());
        m = mg.getMethod();
    }

    il.dispose(); // Reuse instruction handles
    return m;
}
 
Example 13
Source File: ConstantPoolTestCase.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private InstructionHandle[] getInstructionHandles(final JavaClass clazz, final ConstantPoolGen cp, final Method method) {
    final MethodGen methodGen = new MethodGen(method, clazz.getClassName(), cp);
    final InstructionList instructionList = methodGen.getInstructionList();
    return instructionList.getInstructionHandles();
}
 
Example 14
Source File: PerformanceTest.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private static void test(final File lib) throws IOException {
    final NanoTimer total = new NanoTimer();
    final NanoTimer parseTime = new NanoTimer();
    final NanoTimer cgenTime = new NanoTimer();
    final NanoTimer mgenTime = new NanoTimer();
    final NanoTimer mserTime = new NanoTimer();
    final NanoTimer serTime = new NanoTimer();

    System.out.println("parsing " + lib);

    total.start();
    try (JarFile jar = new JarFile(lib)) {
        final Enumeration<?> en = jar.entries();

        while (en.hasMoreElements()) {
            final JarEntry e = (JarEntry) en.nextElement();
            if (e.getName().endsWith(".class")) {
                byte[] bytes;
                try (InputStream in = jar.getInputStream(e)) {
                    bytes = read(in);
                }

                parseTime.start();
                final JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), e.getName()).parse();
                parseTime.stop();

                cgenTime.start();
                final ClassGen cg = new ClassGen(clazz);
                cgenTime.stop();

                final Method[] methods = cg.getMethods();
                for (final Method m : methods) {
                    mgenTime.start();
                    final MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
                    final InstructionList il = mg.getInstructionList();
                    mgenTime.stop();

                    mserTime.start();
                    if (il != null) {
                        mg.getInstructionList().setPositions();
                        mg.setMaxLocals();
                        mg.setMaxStack();
                    }
                    cg.replaceMethod(m, mg.getMethod());
                    mserTime.stop();
                }

                serTime.start();
                cg.getJavaClass().getBytes();
                serTime.stop();
            }
        }
    }
    total.stop();
    if (REPORT) {
        System.out.println("ClassParser.parse: " + parseTime);
        System.out.println("ClassGen.init: " + cgenTime);
        System.out.println("MethodGen.init: " + mgenTime);
        System.out.println("MethodGen.getMethod: " + mserTime);
        System.out.println("ClassGen.getJavaClass.getBytes: " + serTime);
        System.out.println("Total: " + total);
        System.out.println();
    }
}