Java Code Examples for org.apache.bcel.generic.Type#equals()

The following examples show how to use org.apache.bcel.generic.Type#equals() . 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: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void initEntryFact(TypeFrame result) {
    super.initEntryFact(result);
    for (int i = 0; i < methodGen.getMaxLocals(); i++) {
        Type t = result.getValue(i);
        if (t.equals(Type.STRING)) {
            result.setValue(i, parameterStringTypeInstance);
        }
    }
}
 
Example 2
Source File: IncompatibleTypes.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static IncompatibleTypes getPriorityForAssumingCompatibleWithArray(Type rhsType) {
    if (rhsType.equals(Type.OBJECT)) {
        return ARRAY_AND_OBJECT;
    }
    String sig = rhsType.getSignature();
    if ("Ljava/io/Serializable;".equals(sig) || "Ljava/lang/Cloneable;".equals(sig)) {
        return SEEMS_OK;
    }
    return ARRAY_AND_NON_ARRAY;
}
 
Example 3
Source File: FindUseOfNonSerializableValue.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

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

        Use use = getUse(cpg, ins);
        if (use == null) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable < 0.9) {
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                        methodGen, sourceFile, handle);
                ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

                String pattern;
                switch (use) {
                case PASSED_TO_WRITE_OBJECT:
                    pattern = "DMI_NONSERIALIZABLE_OBJECT_WRITTEN";
                    double isRemote = DeepSubtypeAnalysis.isDeepRemote(refType);
                    if (isRemote >= 0.9) {
                        continue;
                    }
                    if (isSerializable < isRemote) {
                        isSerializable = isRemote;
                    }
                    break;
                case STORE_INTO_HTTP_SESSION:
                    pattern = "J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION";
                    break;
                default:
                    throw new IllegalStateException();
                }

                bugAccumulator.accumulateBug(new BugInstance(this, pattern,
                        isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                                .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE),
                        sourceLineAnnotation);

            }
        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 4
Source File: FindNonSerializableStoreIntoSession.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

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

        if (!(ins instanceof INVOKEINTERFACE)) {
            continue;
        }

        INVOKEINTERFACE invoke = (INVOKEINTERFACE) ins;
        String mName = invoke.getMethodName(cpg);
        if (!"setAttribute".equals(mName)) {
            continue;
        }
        String cName = invoke.getClassName(cpg);
        if (!"javax.servlet.http.HttpSession".equals(cName)) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable < 0.9) {
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                        methodGen, sourceFile, handle);
                ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

                bugAccumulator.accumulateBug(new BugInstance(this, "J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION",
                        isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                                .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE),
                        sourceLineAnnotation);

            }
        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 5
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void checkRefComparison(Location location, JavaClass jclass, Method method, MethodGen methodGen,
        RefComparisonTypeFrameModelingVisitor visitor, TypeDataflow typeDataflow,
        List<WarningWithProperties> stringComparisonList, List<WarningWithProperties> refComparisonList)
        throws DataflowAnalysisException {

    InstructionHandle handle = location.getHandle();

    TypeFrame frame = typeDataflow.getFactAtLocation(location);
    if (frame.getStackDepth() < 2) {
        throw new DataflowAnalysisException("Stack underflow", methodGen, handle);
    }

    int numSlots = frame.getNumSlots();
    Type lhsType = frame.getValue(numSlots - 2);
    Type rhsType = frame.getValue(numSlots - 1);

    if (lhsType instanceof NullType || rhsType instanceof NullType) {
        return;
    }
    if (lhsType instanceof ReferenceType && rhsType instanceof ReferenceType) {
        IncompatibleTypes result = IncompatibleTypes.getPriorityForAssumingCompatible(lhsType, rhsType, true);
        if (result != IncompatibleTypes.SEEMS_OK && result != IncompatibleTypes.UNCHECKED) {
            String sourceFile = jclass.getSourceFileName();

            boolean isAssertSame = handle.getInstruction() instanceof INVOKESTATIC;
            if (isAssertSame) {
                if (testingEnabled) {
                    bugAccumulator.accumulateBug(
                            new BugInstance(this, "TESTING", result.getPriority())
                                    .addClassAndMethod(methodGen, sourceFile)
                                    .addString("Calling assertSame with two distinct objects")
                                    .addFoundAndExpectedType(rhsType, lhsType)
                                    .addSomeSourceForTopTwoStackValues(classContext, method, location),
                            SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
                }
            } else {
                bugAccumulator.accumulateBug(
                        new BugInstance(this, "EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", result.getPriority())
                                .addClassAndMethod(methodGen, sourceFile).addFoundAndExpectedType(rhsType, lhsType)
                                .addSomeSourceForTopTwoStackValues(classContext, method, location),
                        SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
            }
            return;
        }
        if (lhsType.equals(Type.OBJECT) && rhsType.equals(Type.OBJECT)) {
            return;
        }
        String lhs = SignatureConverter.convert(lhsType.getSignature());
        String rhs = SignatureConverter.convert(rhsType.getSignature());

        if (Values.DOTTED_JAVA_LANG_STRING.equals(lhs) || Values.DOTTED_JAVA_LANG_STRING.equals(rhs)) {
            handleStringComparison(jclass, method, methodGen, visitor, stringComparisonList, location, lhsType, rhsType);
        } else if (suspiciousSet.contains(lhs)) {
            handleSuspiciousRefComparison(jclass, method, methodGen, refComparisonList, location, lhs,
                    (ReferenceType) lhsType, (ReferenceType) rhsType);
        } else if (suspiciousSet.contains(rhs)) {
            handleSuspiciousRefComparison(jclass, method, methodGen, refComparisonList, location, rhs,
                    (ReferenceType) lhsType, (ReferenceType) rhsType);
        }
    }
}
 
Example 6
Source File: FindNonSerializableValuePassedToWriteObject.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

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

        if (!(ins instanceof InvokeInstruction)) {
            continue;
        }

        InvokeInstruction invoke = (InvokeInstruction) ins;
        String mName = invoke.getMethodName(cpg);
        if (!"writeObject".equals(mName)) {
            continue;
        }
        String cName = invoke.getClassName(cpg);
        if (!"java.io.ObjectOutput".equals(cName) && !"java.io.ObjectOutputStream".equals(cName)) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable >= 0.9) {
                continue;
            }

            ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

            double isRemote = DeepSubtypeAnalysis.isDeepRemote(refType);
            if (isRemote >= 0.9) {
                continue;
            }
            if (isSerializable < isRemote) {
                isSerializable = isRemote;
            }


            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                    methodGen, sourceFile, handle);

            bugReporter.reportBug(new BugInstance(this, "DMI_NONSERIALIZABLE_OBJECT_WRITTEN",
                    isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                            .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE)
                            .addSourceLine(sourceLineAnnotation));

        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 7
Source File: TypeAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected void mergeValues(TypeFrame otherFrame, TypeFrame resultFrame, int slot) throws DataflowAnalysisException {

    Type type2 = resultFrame.getValue(slot);
    Type type1 = otherFrame.getValue(slot);
    Type value = typeMerger.mergeTypes(type2, type1);
    resultFrame.setValue(slot, value);

    // Result type is exact IFF types are identical and both are exact

    boolean typesAreIdentical = type1.equals(type2);

    boolean bothExact = resultFrame.isExact(slot) && otherFrame.isExact(slot);

    resultFrame.setExact(slot, typesAreIdentical && bothExact);
}
 
Example 8
Source File: IncompatibleTypes.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
static public @Nonnull IncompatibleTypes getPriorityForAssumingCompatible(Type expectedType, Type actualType, boolean pointerEquality) {
    if (expectedType.equals(actualType)) {
        return SEEMS_OK;
    }

    if (!(expectedType instanceof ReferenceType)) {
        return SEEMS_OK;
    }
    if (!(actualType instanceof ReferenceType)) {
        return SEEMS_OK;
    }

    while (expectedType instanceof ArrayType && actualType instanceof ArrayType) {
        expectedType = ((ArrayType) expectedType).getElementType();
        actualType = ((ArrayType) actualType).getElementType();
    }

    if (expectedType instanceof BasicType ^ actualType instanceof BasicType) {
        return PRIMATIVE_ARRAY_AND_OTHER_ARRAY;
    }
    if (expectedType instanceof BasicType && actualType instanceof BasicType) {
        if (!expectedType.equals(actualType)) {
            return INCOMPATIBLE_PRIMATIVE_ARRAYS;
        } else {
            return SEEMS_OK;
        }
    }
    if (expectedType instanceof ArrayType) {
        return getPriorityForAssumingCompatibleWithArray(actualType);
    }
    if (actualType instanceof ArrayType) {
        return getPriorityForAssumingCompatibleWithArray(expectedType);
    }
    if (expectedType.equals(actualType)) {
        return SEEMS_OK;
    }

    // For now, ignore the case where either reference is not
    // of an object type. (It could be either an array or null.)
    if (!(expectedType instanceof ObjectType) || !(actualType instanceof ObjectType)) {
        return SEEMS_OK;
    }

    return getPriorityForAssumingCompatible((ObjectType) expectedType, (ObjectType) actualType, pointerEquality);
}
 
Example 9
Source File: Utils.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Tests whether one type is compatible with another for method
 * invocation conversion. This includes assignment conversion,
 * except the implicit narrowing of integer constants.
 * JLS Section 5.2
 * @param aSubType the type to be converted.
 * @param aSuperType the converted type.
 * @return true if aSubType can be converted to aSuperType.
 */
public static boolean isCompatible(Type aSubType, Type aSuperType)
{
    boolean result = false;

    if (aSubType.equals(aSuperType)) {
        // identity conversion
        result = true;
    }
    else if ((aSubType instanceof ReferenceType)
        && (aSuperType instanceof ReferenceType))
    {
        // widening reference conversion?
        final ReferenceType aSubRefType = (ReferenceType) aSubType;
        result = aSubRefType.isAssignmentCompatibleWith(aSuperType);
    }
    // widening primitive conversion?
    else if (aSubType.equals(Type.BYTE)) {
        result =
            aSuperType.equals(Type.SHORT)
                || aSuperType.equals(Type.INT)
                || aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.SHORT)) {
        result =
            aSuperType.equals(Type.INT)
                || aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.INT)) {
        result =
            aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.LONG)) {
        result =
            aSuperType.equals(Type.FLOAT) || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.DOUBLE)) {
        result = aSuperType.equals(Type.DOUBLE);
    }
    return result;
}
 
Example 10
Source File: Utils.java    From contribution with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Tests whether one type is compatible with another for method
 * invocation conversion. This includes assignment conversion,
 * except the implicit narrowing of integer constants.
 * JLS Section 5.2
 * @param aSubType the type to be converted.
 * @param aSuperType the converted type.
 * @return true if aSubType can be converted to aSuperType.
 */
public static boolean isCompatible(Type aSubType, Type aSuperType)
{
    boolean result = false;

    if (aSubType.equals(aSuperType)) {
        // identity conversion
        result = true;
    }
    else if ((aSubType instanceof ReferenceType)
        && (aSuperType instanceof ReferenceType))
    {
        // widening reference conversion?
        final ReferenceType aSubRefType = (ReferenceType) aSubType;
        result = aSubRefType.isAssignmentCompatibleWith(aSuperType);
    }
    // widening primitive conversion?
    else if (aSubType.equals(Type.BYTE)) {
        result =
            aSuperType.equals(Type.SHORT)
                || aSuperType.equals(Type.INT)
                || aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.SHORT)) {
        result =
            aSuperType.equals(Type.INT)
                || aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.INT)) {
        result =
            aSuperType.equals(Type.LONG)
                || aSuperType.equals(Type.FLOAT)
                || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.LONG)) {
        result =
            aSuperType.equals(Type.FLOAT) || aSuperType.equals(Type.DOUBLE);
    }
    else if (aSubType.equals(Type.DOUBLE)) {
        result = aSuperType.equals(Type.DOUBLE);
    }
    return result;
}
 
Example 11
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
@Override
public void visitConstantValue(final ConstantValue obj) {//vmspec2 4.7.2
    // Despite its name, this really is an Attribute,
    // not a constant!
    checkIndex(obj, obj.getNameIndex(), CONST_Utf8);

    final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes();
    if (! name.equals("ConstantValue")) {
        throw new ClassConstraintException(
            "The ConstantValue attribute '"+tostring(obj)+"' is not correctly named 'ConstantValue' but '"+name+"'.");
    }

    final Object pred = carrier.predecessor();
    if (pred instanceof Field) { //ConstantValue attributes are quite senseless if the predecessor is not a field.
        final Field f = (Field) pred;
        // Field constraints have been checked before -- so we are safe using their type information.
        final Type field_type = Type.getType(((ConstantUtf8) (cp.getConstant(f.getSignatureIndex()))).getBytes());

        final int index = obj.getConstantValueIndex();
        if ((index < 0) || (index >= cplen)) {
            throw new ClassConstraintException("Invalid index '"+index+"' used by '"+tostring(obj)+"'.");
        }
        final Constant c = cp.getConstant(index);

        if (CONST_Long.isInstance(c) && field_type.equals(Type.LONG)) {
            return;
        }
        if (CONST_Float.isInstance(c) && field_type.equals(Type.FLOAT)) {
            return;
        }
        if (CONST_Double.isInstance(c) && field_type.equals(Type.DOUBLE)) {
            return;
        }
        if (CONST_Integer.isInstance(c) && (field_type.equals(Type.INT) || field_type.equals(Type.SHORT) ||
           field_type.equals(Type.CHAR) || field_type.equals(Type.BYTE) || field_type.equals(Type.BOOLEAN))) {
            return;
        }
        if (CONST_String.isInstance(c) && field_type.equals(Type.STRING)) {
            return;
        }

        throw new ClassConstraintException("Illegal type of ConstantValue '"+obj+"' embedding Constant '"+c+
            "'. It is referenced by field '"+tostring(f)+"' expecting a different type: '"+field_type+"'.");
    }
}