org.apache.bcel.generic.ReferenceType Java Examples

The following examples show how to use org.apache.bcel.generic.ReferenceType. 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 6 votes vote down vote up
@Override
protected ReferenceType mergeReferenceTypes(ReferenceType aRef, ReferenceType bRef) throws DataflowAnalysisException {
    byte aType = aRef.getType();
    byte bType = bRef.getType();

    if (isExtendedStringType(aType) || isExtendedStringType(bType)) {
        // If both types are the same extended String type,
        // then the same type is returned. Otherwise, extended
        // types are downgraded to plain java.lang.String,
        // and a standard merge is applied.
        if (aType == bType) {
            return aRef;
        }

        if (isExtendedStringType(aType)) {
            aRef = Type.STRING;
        }
        if (isExtendedStringType(bType)) {
            bRef = Type.STRING;
        }
    }

    return super.mergeReferenceTypes(aRef, bRef);
}
 
Example #2
Source File: GenericUtilities.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parse a bytecode signature that has 1 or more (possibly generic) types
 * and return a list of the Types.
 *
 * @param signature
 *            bytecode signature e.g. e.g.
 *            <code>Ljava/util/ArrayList&lt;Ljava/lang/String;&gt;;Ljava/util/ArrayList&lt;TT;&gt;;Ljava/util/ArrayList&lt;*&gt;;</code>
 */
public static final @CheckForNull List<ReferenceType> getTypeParameters(String signature) {
    GenericSignatureParser parser = new GenericSignatureParser("(" + signature + ")V");
    List<ReferenceType> types = new ArrayList<>();

    Iterator<String> iter = parser.parameterSignatureIterator();
    while (iter.hasNext()) {
        String parameterString = iter.next();
        ReferenceType t = (ReferenceType) getType(parameterString);
        if (t == null) {
            return null;
        }
        types.add(t);
    }
    return types;
}
 
Example #3
Source File: ObligationPolicyDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void getActions(ReferenceType receiverType, String methodName, String signature, boolean isStatic,
        Collection<ObligationPolicyDatabaseAction> actionList) {
    if (DEBUG) {
        System.out.println("Lookup for " + receiverType + "," + methodName + "," + signature + "," + isStatic + ": ");
    }
    for (ObligationPolicyDatabaseEntry entry : entryList) {

        boolean matched = entry.getActions(receiverType, methodName, signature, isStatic, actionList);

        if (DEBUG) {
            if (matched) {
                System.out.println(" Entry " + entry + "  ==> MATCH");
                //                else
                //                    System.out.println("  ==> no match");
            }
        }
    }
    if (DEBUG) {
        System.out.println("  ** Resulting action list: " + actionList);
    }
}
 
Example #4
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ReferenceType computeFirstCommonSuperclassOfReferenceTypes(ReferenceType a, ReferenceType b)
        throws ClassNotFoundException {
    boolean aIsArrayType = (a instanceof ArrayType);
    boolean bIsArrayType = (b instanceof ArrayType);

    if (aIsArrayType && bIsArrayType) {
        // Merging array types - kind of a pain.

        ArrayType aArrType = (ArrayType) a;
        ArrayType bArrType = (ArrayType) b;

        if (aArrType.getDimensions() == bArrType.getDimensions()) {
            return computeFirstCommonSuperclassOfSameDimensionArrays(aArrType, bArrType);
        } else {
            return computeFirstCommonSuperclassOfDifferentDimensionArrays(aArrType, bArrType);
        }
    }

    if (aIsArrayType || bIsArrayType) {
        // One of a and b is an array type, but not both.
        // Common supertype is Object.
        return Type.OBJECT;
    }

    // Neither a nor b is an array type.
    // Find first common supertypes of ObjectTypes.
    return getFirstCommonSuperclass((ObjectType) a, (ObjectType) b);
}
 
Example #5
Source File: BuildNonnullReturnDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void considerMethod(ClassContext classContext, Method method) {
    if ((method.getReturnType() instanceof ReferenceType) && classContext.getMethodGen(method) != null) {
        if (VERBOSE_DEBUG) {
            System.out.println("Check " + method);
        }
        analyzeMethod(classContext, method);
    }
}
 
Example #6
Source File: SubtypeTypeMatcher.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean matches(Type t) {
    if (!(t instanceof ReferenceType)) {
        return false;
    }
    IAnalysisCache analysisCache = Global.getAnalysisCache();
    Subtypes2 subtypes2 = analysisCache.getDatabase(Subtypes2.class);

    try {
        return subtypes2.isSubtype((ReferenceType) t, supertype);
    } catch (ClassNotFoundException e) {
        analysisCache.getErrorLogger().reportMissingClass(e);
        return false;
    }
}
 
Example #7
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private ObjectType getObjectType(final FieldInstruction o) {
    final ReferenceType rt = o.getReferenceType(constantPoolGen);
    if(rt instanceof ObjectType) {
        return (ObjectType)rt;
    }
    constraintViolated(o, "expecting ObjectType but got "+rt);
    return null;
}
 
Example #8
Source File: MatchMethodEntry.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean getActions(ReferenceType receiverType, String methodName, String signature, boolean isStatic,
        Collection<ObligationPolicyDatabaseAction> actionList) {
    if (this.methodName.matches(methodName) && this.signature.matches(signature) && this.isStatic == isStatic
            && this.receiverType.matches(receiverType)) {
        for (Obligation o : obligations) {
            actionList.add(new ObligationPolicyDatabaseAction(action, o));
        }
        return true;
    }
    return false;
}
 
Example #9
Source File: TestGenericObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void initTest(String bytecodeSignature, String javaSignature, String underlyingClass,
        GenericUtilities.TypeCategory typeCategory,
        @Nullable String variable, @Nullable Type extension, @Nullable List<ReferenceType> parameters) {
    this.obj = (GenericObjectType) GenericUtilities.getType(bytecodeSignature);
    this.javaSignature = javaSignature;
    this.underlyingClass = underlyingClass;
    this.typeCategory = typeCategory;
    this.variable = variable;
    this.extension = extension;
    this.parameters = parameters;
}
 
Example #10
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleSuspiciousRefComparison(JavaClass jclass, Method method, MethodGen methodGen,
        List<WarningWithProperties> refComparisonList, Location location, String lhs, ReferenceType lhsType,
        ReferenceType rhsType) {
    XField xf = null;
    if (lhsType instanceof FinalConstant) {
        xf = ((FinalConstant) lhsType).getXField();
    } else if (rhsType instanceof FinalConstant) {
        xf = ((FinalConstant) rhsType).getXField();
    }
    String sourceFile = jclass.getSourceFileName();
    String bugPattern = "RC_REF_COMPARISON";
    int priority = Priorities.HIGH_PRIORITY;
    if ("java.lang.Boolean".equals(lhs)) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN";
        priority = Priorities.NORMAL_PRIORITY;
    } else if (xf != null && xf.isStatic() && xf.isFinal()) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE";
        if (xf.isPublic() || !methodGen.isPublic()) {
            priority = Priorities.NORMAL_PRIORITY;
        }
    }
    BugInstance instance = new BugInstance(this, bugPattern, priority).addClassAndMethod(methodGen, sourceFile)
            .addType("L" + lhs.replace('.', '/') + ";").describe(TypeAnnotation.FOUND_ROLE);
    if (xf != null) {
        instance.addField(xf).describe(FieldAnnotation.LOADED_FROM_ROLE);
    } else {
        instance.addSomeSourceForTopTwoStackValues(classContext, method, location);
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
            sourceFile, location.getHandle());

    refComparisonList.add(new WarningWithProperties(instance, new WarningPropertySet<>(),
            sourceLineAnnotation, location));
}
 
Example #11
Source File: BuildUnconditionalParamDerefDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void considerMethod(ClassContext classContext, Method method) {
    boolean hasReferenceParameters = false;
    for (Type argument : method.getArgumentTypes()) {
        if (argument instanceof ReferenceType) {
            hasReferenceParameters = true;
        }
    }

    if (hasReferenceParameters && classContext.getMethodGen(method) != null) {
        if (VERBOSE_DEBUG) {
            System.out.println("Check " + method);
        }
        analyzeMethod(classContext, method);
    }
}
 
Example #12
Source File: TestGenericObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void notestCreateTypes() {
    initTest("LDummyClass<Ljava/lang/Comparable;TE;>;", "DummyClass<java.lang.Comparable,E>", "DummyClass",
            GenericUtilities.TypeCategory.PARAMETERIZED, null, null, Arrays.asList(
                    (ReferenceType) GenericUtilities.getType("Ljava/lang/Comparable;"),
                    (ReferenceType) GenericUtilities.getType("TE;")));
    processTest();
}
 
Example #13
Source File: GenericUtilitiesTest.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void notestNestedSignature2() {
    List<ReferenceType> parameters = GenericUtilities
            .getTypeParameters("Lcom/google/common/util/WeakIdentityHashMap<TK;TV;>.IdentityWeakReference;TV;");

    System.out.println(parameters);
    assertEquals(2, parameters.size());
    ReferenceType t = parameters.get(0);
    assertEquals("com.google.common.util.WeakIdentityHashMap$IdentityWeakReference", t.toString());
}
 
Example #14
Source File: ExceptionSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the least (lowest in the lattice) common supertype of the exceptions
 * in the set. Returns the special TOP type if the set is empty.
 */
public Type getCommonSupertype() throws ClassNotFoundException {
    if (commonSupertype != null) {
        return commonSupertype;
    }

    if (isEmpty()) {
        // This probably means that we're looking at an
        // infeasible exception path.
        return TypeFrame.getTopType();
    }

    // Compute first common superclass
    ThrownExceptionIterator i = iterator();
    ReferenceType result = i.next();
    while (i.hasNext()) {
        if (Subtypes2.ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES) {
            result = AnalysisContext.currentAnalysisContext().getSubtypes2().getFirstCommonSuperclass(result, i.next());
        } else {
            result = result.getFirstCommonSuperclass(i.next());
        }
        if (result == null) {
            // This should only happen if the class hierarchy
            // is incomplete. We'll just be conservative.
            result = Type.THROWABLE;
            break;
        }
    }

    // Cache and return the result
    commonSupertype = result;
    return result;
}
 
Example #15
Source File: StandardTypeMerger.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isThrowable(ReferenceType ref) /*
                                               * throws
                                               * ClassNotFoundException
                                               */ {
    try {

        Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
        return subtypes2.isSubtype(ref, Type.THROWABLE);

    } catch (ClassNotFoundException e) {
        // We'll just assume that it's not an exception type.
        lookupFailureCallback.reportMissingClass(e);
        return false;
    }
}
 
Example #16
Source File: GenericUtilities.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static ObjectType merge(@CheckForNull GenericObjectType t1, ObjectType t2) {
    if (t1 == null || t2 instanceof GenericObjectType) {
        return t2;
    }
    List<? extends ReferenceType> parameters = t1.getParameters();
    if (parameters == null) {
        return t2;
    }
    return new GenericObjectType(t2.getClassName(), parameters);
}
 
Example #17
Source File: GenericObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param index
 *            should be less than getNumParameters()
 * @return the type parameter at index
 */
public ReferenceType getParameterAt(int index) {
    if (index < getNumParameters()) {
        return parameters.get(index);
    } else {
        throw new IndexOutOfBoundsException("The index " + index + " is too large for " + this);
    }
}
 
Example #18
Source File: FieldStoreTypeDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void purgeBoringEntries() {
    Collection<FieldDescriptor> keys = new ArrayList<>(getKeys());
    for (FieldDescriptor f : keys) {
        FieldStoreType type = getProperty(f);
        Type fieldType = Type.getType(f.getSignature());
        if (!(fieldType instanceof ReferenceType)) {
            removeProperty(f);
            continue;
        }
        ReferenceType storeType = type.getLoadType((ReferenceType) fieldType);
        if (storeType.equals(fieldType)) {
            removeProperty(f);
        }
    }
}
 
Example #19
Source File: GenericObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a GenericObjectType that represents a Wildcard with extensions
 *
 */
GenericObjectType(@Nonnull String wildcard, @CheckForNull ReferenceType extension) {
    super(Type.OBJECT.getClassName());
    this.variable = wildcard;
    this.extension = extension;
    parameters = null;
}
 
Example #20
Source File: GenericObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a GenericObjectType that represents a parameterized class
 *
 * @param class_name
 *            the class that is parameterized. e.g.
 *            <code>java.util.List</code>
 * @param parameters
 *            the parameters of this class, must be at least 1 parameter
 */
GenericObjectType(@DottedClassName String class_name, List<? extends ReferenceType> parameters) {
    super(class_name);
    variable = null;
    extension = null;
    if (parameters == null || parameters.size() == 0) {
        throw new IllegalStateException("argument 'parameters' must contain at least 1 parameter");
    }
    this.parameters = parameters;
}
 
Example #21
Source File: Hierarchy2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Resolve possible instance method call targets.
 *
 * @param receiverType
 *            type of the receiver object
 * @param invokeInstruction
 *            the InvokeInstruction
 * @param cpg
 *            the ConstantPoolGen
 * @param receiverTypeIsExact
 *            if true, the receiver type is known exactly, which should
 *            allow a precise result
 * @return Set of methods which might be called
 * @throws ClassNotFoundException
 */
public static Set<XMethod> resolveMethodCallTargets(ReferenceType receiverType, InvokeInstruction invokeInstruction,
        ConstantPoolGen cpg, boolean receiverTypeIsExact) throws ClassNotFoundException {

    if (invokeInstruction.getOpcode() == Const.INVOKESTATIC) {
        throw new IllegalArgumentException();
    }

    String methodName = invokeInstruction.getName(cpg);
    String methodSig = invokeInstruction.getSignature(cpg);

    // Array method calls aren't virtual.
    // They should just resolve to Object methods.
    if (receiverType instanceof ArrayType) {
        try {
            return Util.emptyOrNonnullSingleton(getXClass(objectDescriptor).findMethod(methodName, methodSig, false));
        } catch (CheckedAnalysisException e) {
            return Collections.<XMethod>emptySet();
        }
    }

    if (receiverType instanceof ObjectType) {
        // Get the receiver class.
        String receiverClassName = ((ObjectType) receiverType).getClassName();

        return resolveVirtualMethodCallTargets(receiverClassName, methodName, methodSig, receiverTypeIsExact,
                invokeInstruction instanceof INVOKESPECIAL);
    }
    assert receiverType instanceof NullType;
    return Collections.<XMethod>emptySet();

}
 
Example #22
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ReferenceType checkFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b) {
    if (a.getSignature().compareTo(b.getSignature()) > 0) {
        ReferenceType tmp = a;
        a = b;
        b = tmp;
    }
    return firstCommonSuperclassQueryCache.get(a, b);
}
 
Example #23
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void putFirstCommonSuperclassQueryCache(ReferenceType a, ReferenceType b, ReferenceType answer) {
    if (a.getSignature().compareTo(b.getSignature()) > 0) {
        ReferenceType tmp = a;
        a = b;
        b = tmp;
    }
    firstCommonSuperclassQueryCache.put(a, b, answer);
}
 
Example #24
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the first common superclass of arrays with different numbers of
 * dimensions.
 *
 * @param aArrType
 *            an ArrayType
 * @param bArrType
 *            another ArrayType
 * @return ReferenceType representing first common superclass
 */
private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays(ArrayType aArrType, ArrayType bArrType) {
    assert aArrType.getDimensions() != bArrType.getDimensions();

    boolean aBaseTypeIsPrimitive = (aArrType.getBasicType() instanceof BasicType);
    boolean bBaseTypeIsPrimitive = (bArrType.getBasicType() instanceof BasicType);

    if (aBaseTypeIsPrimitive || bBaseTypeIsPrimitive) {
        int minDimensions, maxDimensions;
        if (aArrType.getDimensions() < bArrType.getDimensions()) {
            minDimensions = aArrType.getDimensions();
            maxDimensions = bArrType.getDimensions();
        } else {
            minDimensions = bArrType.getDimensions();
            maxDimensions = aArrType.getDimensions();
        }

        if (minDimensions == 1) {
            // One of the types was something like int[].
            // The only possible common supertype is Object.
            return Type.OBJECT;
        } else {
            // Weird case: e.g.,
            // - first common supertype of int[][] and char[][][] is
            // Object[]
            // because f.c.s. of int[] and char[][] is Object
            // - first common supertype of int[][][] and char[][][][][] is
            // Object[][]
            // because f.c.s. of int[] and char[][][] is Object
            return new ArrayType(Type.OBJECT, maxDimensions - minDimensions);
        }
    } else {
        // Both a and b have base types which are ObjectTypes.
        // Since the arrays have different numbers of dimensions, the
        // f.c.s. will have Object as its base type.
        // E.g., f.c.s. of Cat[] and Dog[][] is Object[]
        return new ArrayType(Type.OBJECT, Math.min(aArrType.getDimensions(), bArrType.getDimensions()));
    }
}
 
Example #25
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get first common supertype of arrays with the same number of dimensions.
 *
 * @param aArrType
 *            an ArrayType
 * @param bArrType
 *            another ArrayType with the same number of dimensions
 * @return first common supertype
 * @throws ClassNotFoundException
 */
private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType)
        throws ClassNotFoundException {
    assert aArrType.getDimensions() == bArrType.getDimensions();

    Type aBaseType = aArrType.getBasicType();
    Type bBaseType = bArrType.getBasicType();
    boolean aBaseIsObjectType = (aBaseType instanceof ObjectType);
    boolean bBaseIsObjectType = (bBaseType instanceof ObjectType);

    if (!aBaseIsObjectType || !bBaseIsObjectType) {
        assert (aBaseType instanceof BasicType) || (bBaseType instanceof BasicType);

        if (aArrType.getDimensions() > 1) {
            // E.g.: first common supertype of int[][] and WHATEVER[][] is
            // Object[]
            return new ArrayType(Type.OBJECT, aArrType.getDimensions() - 1);
        } else {
            assert aArrType.getDimensions() == 1;
            // E.g.: first common supertype type of int[] and WHATEVER[] is
            // Object
            return Type.OBJECT;
        }
    } else {
        assert (aBaseType instanceof ObjectType);
        assert (bBaseType instanceof ObjectType);

        // Base types are both ObjectTypes, and number of dimensions is
        // same.
        // We just need to find the first common supertype of base types
        // and return a new ArrayType using that base type.
        ObjectType firstCommonBaseType = getFirstCommonSuperclass((ObjectType) aBaseType, (ObjectType) bBaseType);
        return new ArrayType(firstCommonBaseType, aArrType.getDimensions());
    }
}
 
Example #26
Source File: IncompatibleTypes.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
static public @Nonnull IncompatibleTypes getPriorityForAssumingCompatible(GenericObjectType genericType, Type plainType) {
    IncompatibleTypes result = IncompatibleTypes.getPriorityForAssumingCompatible(genericType.getObjectType(), plainType);
    List<? extends ReferenceType> parameters = genericType.getParameters();
    if (result.getPriority() == Priorities.NORMAL_PRIORITY && parameters != null && parameters.contains(plainType)) {
        result = UNRELATED_TYPES_BUT_MATCHES_TYPE_PARAMETER;
    }
    return result;

}
 
Example #27
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 #28
Source File: OperandStack.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Merges another stack state into this instance's stack state.
 * See the Java Virtual Machine Specification, Second Edition, page 146: 4.9.2
 * for details.
 */
public void merge(final OperandStack s) {
    try {
    if ( (slotsUsed() != s.slotsUsed()) || (size() != s.size()) ) {
        throw new StructuralCodeConstraintException(
            "Cannot merge stacks of different size:\nOperandStack A:\n"+this+"\nOperandStack B:\n"+s);
    }

    for (int i=0; i<size(); i++) {
        // If the object _was_ initialized and we're supposed to merge
        // in some uninitialized object, we reject the code (see vmspec2, 4.9.4, last paragraph).
        if ( (! (stack.get(i) instanceof UninitializedObjectType)) && (s.stack.get(i) instanceof UninitializedObjectType) ) {
            throw new StructuralCodeConstraintException("Backwards branch with an uninitialized object on the stack detected.");
        }
        // Even harder, we're not initialized but are supposed to broaden
        // the known object type
        if ( (!(stack.get(i).equals(s.stack.get(i)))) &&
                (stack.get(i) instanceof UninitializedObjectType) && (!(s.stack.get(i) instanceof UninitializedObjectType))) {
            throw new StructuralCodeConstraintException("Backwards branch with an uninitialized object on the stack detected.");
        }
        // on the other hand...
        if (stack.get(i) instanceof UninitializedObjectType) { //if we have an uninitialized object here
            if (! (s.stack.get(i) instanceof UninitializedObjectType)) { //that has been initialized by now
                stack.set(i, ((UninitializedObjectType) (stack.get(i))).getInitialized() ); //note that.
            }
        }
        if (! stack.get(i).equals(s.stack.get(i))) {
            if (    (stack.get(i) instanceof ReferenceType) &&
                        (s.stack.get(i) instanceof ReferenceType)  ) {
                stack.set(i, ((ReferenceType) stack.get(i)).getFirstCommonSuperclass((ReferenceType) (s.stack.get(i))));
            }
            else{
                throw new StructuralCodeConstraintException(
                    "Cannot merge stacks of different types:\nStack A:\n"+this+"\nStack B:\n"+s);
            }
        }
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example #29
Source File: LocalVariables.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
     * Merges a single local variable.
     *
     * @see #merge(LocalVariables)
     */
    private void merge(final LocalVariables lv, final int i) {
        try {

        // We won't accept an unitialized object if we know it was initialized;
        // compare vmspec2, 4.9.4, last paragraph.
        if ( (!(locals[i] instanceof UninitializedObjectType)) && (lv.locals[i] instanceof UninitializedObjectType) ) {
            throw new StructuralCodeConstraintException(
                "Backwards branch with an uninitialized object in the local variables detected.");
        }
        // Even harder, what about _different_ uninitialized object types?!
        if ( (!(locals[i].equals(lv.locals[i]))) && (locals[i] instanceof UninitializedObjectType) &&
                (lv.locals[i] instanceof UninitializedObjectType) ) {
            throw new StructuralCodeConstraintException(
                "Backwards branch with an uninitialized object in the local variables detected.");
        }
        // If we just didn't know that it was initialized, we have now learned.
        if (locals[i] instanceof UninitializedObjectType) {
            if (! (lv.locals[i] instanceof UninitializedObjectType)) {
                locals[i] = ((UninitializedObjectType) locals[i]).getInitialized();
            }
        }
        if ((locals[i] instanceof ReferenceType) && (lv.locals[i] instanceof ReferenceType)) {
            if (! locals[i].equals(lv.locals[i])) { // needed in case of two UninitializedObjectType instances
                final Type sup = ((ReferenceType) locals[i]).getFirstCommonSuperclass((ReferenceType) (lv.locals[i]));

                if (sup != null) {
                    locals[i] = sup;
                }
                else{
                    // We should have checked this in Pass2!
                    throw new AssertionViolatedException(
                        "Could not load all the super classes of '"+locals[i]+"' and '"+lv.locals[i]+"'.");
                }
            }
        }
        else{
            if (! (locals[i].equals(lv.locals[i])) ) {
/*TODO
                if ((locals[i] instanceof org.apache.bcel.generic.ReturnaddressType) &&
                    (lv.locals[i] instanceof org.apache.bcel.generic.ReturnaddressType)) {
                    //System.err.println("merging "+locals[i]+" and "+lv.locals[i]);
                    throw new AssertionViolatedException("Merging different ReturnAddresses: '"+locals[i]+"' and '"+lv.locals[i]+"'.");
                }
*/
                locals[i] = Type.UNKNOWN;
            }
        }
        } catch (final ClassNotFoundException e) {
        // FIXME: maybe not the best way to handle this
        throw new AssertionViolatedException("Missing class: " + e, e);
        }
    }
 
Example #30
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;
}