Java Code Examples for org.apache.bcel.classfile.Code#getCode()

The following examples show how to use org.apache.bcel.classfile.Code#getCode() . 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: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void compare(final String name, final Method method) {
    // System.out.println("Method: " + m);
    final Code code = method.getCode();
    if (code == null) {
        return; // e.g. abstract method
    }
    final byte[] src = code.getCode();
    final InstructionList instructionList = new InstructionList(src);
    final byte[] out = instructionList.getByteCode();
    if (src.length == out.length) {
        assertArrayEquals(name + ": " + method.toString(), src, out);
    } else {
        System.out.println(name + ": " + method.toString() + " " + src.length + " " + out.length);
        System.out.println(bytesToHex(src));
        System.out.println(bytesToHex(out));
        for (final InstructionHandle instructionHandle : instructionList) {
            System.out.println(instructionHandle.toString(false));
        }
        fail("Array comparison failure");
    }
}
 
Example 2
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean markedAsNotUsable(Method obj) {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof Deprecated) {
            return true;
        }
    }
    Code code = obj.getCode();
    if (code == null) {
        return false;
    }
    byte[] codeBytes = code.getCode();
    if (codeBytes.length > 1 && codeBytes.length < 10) {
        int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff;
        if (lastOpcode != Const.ATHROW) {
            return false;
        }
        for (int b : codeBytes) {
            if ((b & 0xff) == Const.RETURN) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 3
Source File: InvalidJUnitTest.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    if (!directChildOfTestCase && (getMethodName().equals("setUp") || getMethodName().equals("tearDown"))
            && !getMethod().isPrivate() && getMethodSig().equals("()V")) {
        sawSuperCall = false;
        super.visit(obj);
        if (sawSuperCall) {
            return;
        }
        JavaClass we = Lookup.findSuperImplementor(getThisClass(), getMethodName(), "()V", bugReporter);
        if (we != null && !we.getClassName().equals("junit.framework.TestCase")) {
            // OK, got a bug
            int offset = 0;
            if (getMethodName().equals("tearDown")) {
                offset = obj.getCode().length - 1;
            }
            Method superMethod = Lookup.findImplementation(we, getMethodName(), "()V");
            Code superCode = superMethod.getCode();
            if (superCode != null && superCode.getCode().length > 3) {
                bugReporter.reportBug(new BugInstance(this, getMethodName().equals("setUp") ? "IJU_SETUP_NO_SUPER"
                        : "IJU_TEARDOWN_NO_SUPER", NORMAL_PRIORITY).addClassAndMethod(this).addMethod(we, superMethod)
                                .describe(MethodAnnotation.METHOD_OVERRIDDEN).addSourceLine(this, offset));
            }
        }
    }
}
 
Example 4
Source File: VisitorSet.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @see org.apache.bcel.classfile.Visitor#visitCode
 */
public void visitCode(Code aCode)
{   
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aCode.accept(v);
    }
    
    // perform a deep visit
    final byte[] code = aCode.getCode();
    final InstructionList list = new InstructionList(code);
    final Iterator it = list.iterator();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        InstructionHandle instruction = (InstructionHandle) iter.next();
        visitInstructionHandle(instruction);
    }
}
 
Example 5
Source File: VisitorSet.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @see org.apache.bcel.classfile.Visitor#visitCode
 */
public void visitCode(Code aCode)
{   
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aCode.accept(v);
    }
    
    // perform a deep visit
    final byte[] code = aCode.getCode();
    final InstructionList list = new InstructionList(code);
    final Iterator it = list.iterator();
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        InstructionHandle instruction = (InstructionHandle) iter.next();
        visitInstructionHandle(instruction);
    }
}
 
Example 6
Source File: UnpackedCodeFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public UnpackedCode analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = getMethod(analysisCache, descriptor);
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    byte[] instructionList = code.getCode();

    // Create callback
    UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);

    // Scan the method.
    BytecodeScanner scanner = new BytecodeScanner();
    scanner.scan(instructionList, callback);

    return callback.getUnpackedCode();

}
 
Example 7
Source File: MethodBytecodeSetFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public MethodBytecodeSet analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    byte[] instructionList = code.getCode();

    // Create callback
    UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);

    // Scan the method.
    BytecodeScanner scanner = new BytecodeScanner();
    scanner.scan(instructionList, callback);

    UnpackedCode unpackedCode = callback.getUnpackedCode();
    MethodBytecodeSet result = null;
    if (unpackedCode != null) {
        result = unpackedCode.getBytecodeSet();
    }

    return result;
}
 
Example 8
Source File: ClassFeatureSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Initialize from given JavaClass.
 *
 * @param javaClass
 *            the JavaClass
 * @return this object
 */
public ClassFeatureSet initialize(JavaClass javaClass) {
    this.className = javaClass.getClassName();
    this.isInterface = javaClass.isInterface();

    addFeature(CLASS_NAME_KEY + transformClassName(javaClass.getClassName()));

    for (Method method : javaClass.getMethods()) {
        if (!isSynthetic(method)) {
            String transformedMethodSignature = transformMethodSignature(method.getSignature());

            if (method.isStatic() || !overridesSuperclassMethod(javaClass, method)) {
                addFeature(METHOD_NAME_KEY + method.getName() + ":" + transformedMethodSignature);
            }

            Code code = method.getCode();
            if (code != null && code.getCode() != null && code.getCode().length >= MIN_CODE_LENGTH) {
                addFeature(CODE_LENGTH_KEY + method.getName() + ":" + transformedMethodSignature + ":"
                        + code.getCode().length);
            }
        }
    }

    for (Field field : javaClass.getFields()) {
        if (!isSynthetic(field)) {
            addFeature(FIELD_NAME_KEY + field.getName() + ":" + transformSignature(field.getSignature()));
        }
    }

    return this;
}
 
Example 9
Source File: MethodGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private static byte[] getByteCodes(final Method method) {
    final Code code = method.getCode();
    if (code == null) {
        throw new IllegalStateException(String.format("The method '%s' has no code.", method));
    }
    return code.getCode();
}
 
Example 10
Source File: ClassContext.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get a BitSet representing the bytecodes that are used in the given
 * method. This is useful for prescreening a method for the existence of
 * particular instructions. Because this step doesn't require building a
 * MethodGen, it is very fast and memory-efficient. It may allow a Detector
 * to avoid some very expensive analysis, which is a Big Win for the user.
 *
 * @param method
 *            the method
 * @return the BitSet containing the opcodes which appear in the method, or
 *         null if the method has no code
 */
@CheckForNull
static public BitSet getBytecodeSet(JavaClass clazz, Method method) {

    XMethod xmethod = XFactory.createXMethod(clazz, method);
    if (cachedBitsets().containsKey(xmethod)) {
        return cachedBitsets().get(xmethod);
    }
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    byte[] instructionList = code.getCode();

    // Create callback
    UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);

    // Scan the method.
    BytecodeScanner scanner = new BytecodeScanner();
    scanner.scan(instructionList, callback);

    UnpackedCode unpackedCode = callback.getUnpackedCode();
    BitSet result = null;
    if (unpackedCode != null) {
        result = unpackedCode.getBytecodeSet();
    }
    cachedBitsets().put(xmethod, result);
    return result;
}
 
Example 11
Source File: LazyInit.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean prescreen(Method method, ClassContext classContext) {
    if (Const.STATIC_INITIALIZER_NAME.equals(method.getName())) {
        return false;
    }

    Code code = method.getCode();
    if (code.getCode().length > 5000) {
        return false;
    }

    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return false;
    }

    // The pattern requires a get/put pair accessing the same field.
    boolean hasGetStatic = bytecodeSet.get(Const.GETSTATIC);
    boolean hasPutStatic = bytecodeSet.get(Const.PUTSTATIC);
    if (!hasGetStatic || !hasPutStatic) {
        return false;
    }

    // If the method is synchronized, then we'll assume that
    // things are properly synchronized
    if (method.isSynchronized()) {
        return false;
    }

    reported.clear();
    return true;
}
 
Example 12
Source File: FindFinalizeInvocations.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    sawSuperFinalize = false;
    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    if (!"finalize".equals(getMethodName()) || !"()V".equals(getMethodSig())) {
        return;
    }
    String overridesFinalizeIn = Lookup.findSuperImplementor(getDottedClassName(), "finalize", "()V", bugReporter);
    boolean superHasNoFinalizer = Values.DOTTED_JAVA_LANG_OBJECT.equals(overridesFinalizeIn);
    // System.out.println("superclass: " + superclassName);
    if (obj.getCode().length == 1) {
        if (superHasNoFinalizer) {
            if (!getMethod().isFinal()) {
                bugReporter.reportBug(new BugInstance(this, "FI_EMPTY", NORMAL_PRIORITY).addClassAndMethod(this));
            }
        } else {
            bugReporter.reportBug(new BugInstance(this, "FI_NULLIFY_SUPER", NORMAL_PRIORITY).addClassAndMethod(this)
                    .addClass(overridesFinalizeIn));
        }
    } else if (obj.getCode().length == 5 && sawSuperFinalize) {
        bugReporter.reportBug(new BugInstance(this, "FI_USELESS", NORMAL_PRIORITY).addClassAndMethod(this));
    } else if (!sawSuperFinalize && !superHasNoFinalizer) {
        bugReporter.reportBug(new BugInstance(this, "FI_MISSING_SUPER_CALL", NORMAL_PRIORITY).addClassAndMethod(this)
                .addClass(overridesFinalizeIn));
    }
}
 
Example 13
Source File: InnerClassAccessMap.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Return a map of inner-class member access method names to the fields that
 * they access for given class name.
 *
 * @param className
 *            the name of the class
 * @return map of access method names to the fields they access
 */
private Map<String, InnerClassAccess> getAccessMapForClass(String className) throws ClassNotFoundException {

    Map<String, InnerClassAccess> map = classToAccessMap.get(className);
    if (map == null) {
        map = new HashMap<>(3);

        if (!className.startsWith("[")) {
            JavaClass javaClass = Repository.lookupClass(className);

            Method[] methodList = javaClass.getMethods();
            for (Method method : methodList) {
                String methodName = method.getName();
                if (!methodName.startsWith("access$")) {
                    continue;
                }

                Code code = method.getCode();
                if (code == null) {
                    continue;
                }

                if (DEBUG) {
                    System.out.println("Analyzing " + className + "." + method.getName()
                            + " as an inner-class access method...");
                }

                byte[] instructionList = code.getCode();
                String methodSig = method.getSignature();
                InstructionCallback callback = new InstructionCallback(javaClass, methodName, methodSig, instructionList);
                //                    try {
                new BytecodeScanner().scan(instructionList, callback);
                //                    } catch (LookupFailure lf) {
                //                        throw lf.getException();
                //                    }
                InnerClassAccess access = callback.getAccess();
                if (DEBUG) {
                    System.out.println((access != null ? "IS" : "IS NOT") + " an inner-class access method");
                }
                if (access != null) {
                    map.put(methodName, access);
                }
            }
        }

        if (map.size() == 0) {
            map = Collections.emptyMap();
        } else {
            map = new HashMap<>(map);
        }

        classToAccessMap.put(className, map);
    }

    return map;
}
 
Example 14
Source File: FindNoSideEffectMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Code obj) {
    uselessVoidCandidate = !classInit && !constructor && !getXMethod().isSynthetic() && Type.getReturnType(getMethodSig()) == Type.VOID;
    byte[] code = obj.getCode();
    if (code.length == 4 && (code[0] & 0xFF) == Const.GETSTATIC && (code[3] & 0xFF) == Const.ARETURN) {
        getStaticMethods.add(getMethodDescriptor());
        handleStatus();
        return;
    }

    if (code.length <= 2 && !getXMethod().isStatic() && (getXMethod().isPublic() || getXMethod().isProtected())
            && !getXMethod().isFinal() && (getXClass().isPublic() || getXClass().isProtected())) {
        for (byte[] stubMethod : STUB_METHODS) {
            if (Arrays.equals(stubMethod, code)
                    && (getClassName().endsWith("Visitor") || getClassName().endsWith("Listener") || !hasOtherImplementations(getXMethod()))) {
                // stub method which can be extended: assume it can be extended with possible side-effect
                status = SideEffectStatus.SIDE_EFFECT;
                handleStatus();
                return;
            }
        }
    }
    if (statusMap.containsKey(getMethodDescriptor())) {
        return;
    }
    finallyTargets = new HashSet<>();
    for (CodeException ex : getCode().getExceptionTable()) {
        if (ex.getCatchType() == 0) {
            finallyTargets.add(ex.getHandlerPC());
        }
    }
    finallyExceptionRegisters = new HashSet<>();
    try {
        super.visit(obj);
    } catch (EarlyExitException e) {
        // Ignore
    }
    if (uselessVoidCandidate && code.length > 1
            && (status == SideEffectStatus.UNSURE || status == SideEffectStatus.NO_SIDE_EFFECT)) {
        uselessVoidCandidates.add(getMethodDescriptor());
    }
    handleStatus();
}
 
Example 15
Source File: UselessSubclassMethod.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visitCode(Code obj) {
    try {
        String methodName = getMethodName();

        if (!Const.CONSTRUCTOR_NAME.equals(methodName) && !"clone".equals(methodName)
                && ((getMethod().getAccessFlags() & (Const.ACC_STATIC | Const.ACC_SYNTHETIC)) == 0)) {

            /*
             * for some reason, access flags doesn't return Synthetic, so do
             * this hocus pocus
             */
            Attribute[] atts = getMethod().getAttributes();
            for (Attribute att : atts) {
                if (att.getClass().equals(Synthetic.class)) {
                    return;
                }
            }

            byte[] codeBytes = obj.getCode();
            if ((codeBytes.length == 0) || (codeBytes[0] != Const.ALOAD_0)) {
                return;
            }

            state = State.SEEN_NOTHING;
            invokePC = 0;
            super.visitCode(obj);
            if ((state == State.SEEN_RETURN) && (invokePC != 0)) {
                // Do this check late, as it is potentially expensive
                Method superMethod = findSuperclassMethod(superclassName, getMethod());
                if ((superMethod == null) || differentAttributes(getMethod(), superMethod)
                        || getMethod().isProtected()
                                && !samePackage(getDottedClassName(), superclassName)) {
                    return;
                }

                bugReporter.reportBug(new BugInstance(this, "USM_USELESS_SUBCLASS_METHOD", LOW_PRIORITY).addClassAndMethod(
                        this).addSourceLine(this, invokePC));
            }
        }
    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
}
 
Example 16
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean codeDoesSomething(Code code) {
    byte[] codeBytes = code.getCode();
    return codeBytes.length > 1;
}
 
Example 17
Source File: FindBugsSummaryStats.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Code obj) {
    classCodeSize += obj.getCode().length;
}