Java Code Examples for org.apache.bcel.generic.ObjectType

The following examples show how to use org.apache.bcel.generic.ObjectType. These examples are extracted from open source projects. 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
@Override
public void visitCHECKCAST(CHECKCAST obj) {
    // cast to a safe object type
    ObjectType objectType = obj.getLoadClassType(cpg);
    if (objectType == null) {
        return;
    }

    String objectTypeSignature = objectType.getSignature();

    if(!taintConfig.isClassTaintSafe(objectTypeSignature)) {
        return;
    }

    try {
        getFrame().popValue();
        pushSafe();
    }
    catch (DataflowAnalysisException ex) {
        throw new InvalidBytecodeException("empty stack for checkcast", ex);
    }
}
 
Example 2
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();

    try {
        if (ins instanceof InvokeInstruction) {
            if (!Hierarchy.isSubtype(type, baseClassType)) {
                return null;
            }

            Stream stream = new Stream(location, type.getClassName(), baseClassType.getClassName()).setIsOpenOnCreation(true)
                    .setIgnoreImplicitExceptions(true);
            if (bugType != null) {
                stream.setInteresting(bugType);
            }

            return stream;
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 3
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();
    if (ins.getOpcode() != Const.GETSTATIC) {
        return null;
    }

    GETSTATIC getstatic = (GETSTATIC) ins;
    if (!className.equals(getstatic.getClassName(cpg)) || !fieldName.equals(getstatic.getName(cpg))
            || !fieldSig.equals(getstatic.getSignature(cpg))) {
        return null;
    }

    return new Stream(location, type.getClassName(), streamBaseClass).setIgnoreImplicitExceptions(true).setIsOpenOnCreation(
            true);
}
 
Example 4
/**
 * Get array of Obligation types corresponding to the parameters of the
 * given method.
 *
 * @param xmethod
 *            a method
 * @return array of Obligation types for each of the method's parameters; a
 *         null element means the corresponding parameter is not an
 *         Obligation type
 */
public Obligation[] getParameterObligationTypes(XMethod xmethod) {
    Type[] paramTypes = Type.getArgumentTypes(xmethod.getSignature());
    Obligation[] result = new Obligation[paramTypes.length];
    for (int i = 0; i < paramTypes.length; i++) {
        if (!(paramTypes[i] instanceof ObjectType)) {
            continue;
        }
        try {
            result[i] = getObligationByType((ObjectType) paramTypes[i]);
        } catch (ClassNotFoundException e) {
            Global.getAnalysisCache().getErrorLogger().reportMissingClass(e);
        }
    }
    return result;
}
 
Example 5
public static boolean isNullCheck(InstructionHandle h, ConstantPoolGen cpg) {
    if (!(h.getInstruction() instanceof IFNONNULL)) {
        return false;
    }
    h = h.getNext();
    final Instruction newInstruction = h.getInstruction();
    if (!(newInstruction instanceof NEW)) {
        return false;
    }
    final ObjectType loadClassType = ((NEW) newInstruction).getLoadClassType(cpg);
    if (!"java.lang.NullPointerException".equals(loadClassType.getClassName())) {
        return false;
    }
    h = h.getNext();
    return check(h, NULLCHECK1) || check(h, NULLCHECK2);

}
 
Example 6
/**
 * Get the TypeCategory that represents this Object
 *
 * @see GenericUtilities.TypeCategory
 */
public static final TypeCategory getTypeCategory(Type type) {
    if (type instanceof GenericObjectType) {
        return ((GenericObjectType) type).getTypeCategory();
    }

    if (type instanceof ObjectType || type instanceof NullType) {
        return TypeCategory.PLAIN_OBJECT_TYPE;
    }

    if (type instanceof ArrayType) {
        return TypeCategory.ARRAY_TYPE;
    }

    throw new IllegalArgumentException("Not a reference type: " + type);
}
 
Example 7
public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("Usage: " + GenericSignatureParser.class.getName() + " '<method signature>'");
        System.exit(1);
    }
    GenericSignatureParser parser = new GenericSignatureParser(args[0]);
    for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
        String s = i.next();
        System.out.println(s);
        Type t = GenericUtilities.getType(s);
        System.out.println("-~- " + t);
        if (t instanceof ObjectType) {
            System.out.println("-~- " + ((ObjectType) t).toString());
        }
        if (t != null) {
            System.out.println("-~- " + t.getClass());
        }
    }
    System.out.println(parser.getNumParameters() + " parameter(s)");

}
 
Example 8
public static ObjectType getInstance(@DottedClassName String s) {
    if (FindBugs.DEBUG && s.startsWith("[")) {
        throw new IllegalArgumentException("Cannot create an ObjectType to represent an array type: " + s);
    }
    if (s.endsWith(";")) {
        throw new IllegalArgumentException(s);
    }
    if (s.indexOf('/') >= 0) {
        s = s.replace('/', '.');
    }

    Map<String, ObjectType> map = instance.get();
    ObjectType result = map.get(s);
    if (result != null) {
        return result;
    }
    result = ObjectType.getInstance(s);
    map.put(s, result);
    return result;
}
 
Example 9
Source Project: spotbugs   Source File: Subtypes2.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Determine whether or not a given ObjectType is a subtype of another.
 * Throws ClassNotFoundException if the question cannot be answered
 * definitively due to a missing class.
 *
 * @param type
 *            a ReferenceType
 * @param possibleSupertype
 *            another Reference type
 * @return true if <code>type</code> is a subtype of
 *         <code>possibleSupertype</code>, false if not
 * @throws ClassNotFoundException
 *             if a missing class prevents a definitive answer
 */
public boolean isSubtype(ObjectType type, ObjectType possibleSupertype) throws ClassNotFoundException {
    if (DEBUG_QUERIES) {
        System.out.println("isSubtype: check " + type + " subtype of " + possibleSupertype);
    }

    if (type.equals(possibleSupertype)) {
        if (DEBUG_QUERIES) {
            System.out.println("  ==> yes, types are same");
        }
        return true;
    }
    ClassDescriptor typeClassDescriptor = DescriptorFactory.getClassDescriptor(type);
    ClassDescriptor possibleSuperclassClassDescriptor = DescriptorFactory.getClassDescriptor(possibleSupertype);

    return isSubtype(typeClassDescriptor, possibleSuperclassClassDescriptor);
}
 
Example 10
Source Project: spotbugs   Source File: Hierarchy2.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Find the declared exceptions for the method called by given instruction.
 *
 * @param inv
 *            the InvokeInstruction
 * @param cpg
 *            the ConstantPoolGen used by the class the InvokeInstruction
 *            belongs to
 * @return array of ObjectTypes of thrown exceptions, or null if we can't
 *         find the method implementation
 */
public static @CheckForNull ObjectType[] findDeclaredExceptions(InvokeInstruction inv, ConstantPoolGen cpg) {
    XMethod method = findInvocationLeastUpperBound(inv, cpg, inv instanceof INVOKESTATIC ? STATIC_METHOD : INSTANCE_METHOD);

    if (method == null) {
        return null;
    }
    String[] exceptions = method.getThrownExceptions();

    if (exceptions == null) {
        return new ObjectType[0];
    }

    ObjectType[] result = new ObjectType[exceptions.length];
    for (int i = 0; i < exceptions.length; ++i) {
        result[i] = ObjectTypeFactory.getInstance(ClassName.toDottedClassName(exceptions[i]));
    }
    return result;
}
 
Example 11
public static CodeExceptionGen merge(@CheckForNull TypeMerger m, CodeExceptionGen e1, CodeExceptionGen e2) {
    if (e1 == null) {
        return e2;
    }
    if (e2 == null) {
        return e1;
    }
    if (m == null) {
        return e1;
    }
    if (!e1.getHandlerPC().equals(e2.getHandlerPC())) {
        // log error
        return e1;
    }
    try {
        Type t = m.mergeTypes(e1.getCatchType(), e2.getCatchType());
        return new CodeExceptionGen(e1.getStartPC(), e1.getEndPC(), e1.getHandlerPC(), (ObjectType) t);
    } catch (DataflowAnalysisException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e1;
    }
}
 
Example 12
@Override
public void transfer(BasicBlock basicBlock, @CheckForNull InstructionHandle end, BlockType start, BlockType result)
        throws DataflowAnalysisException {
    result.copyFrom(start);

    if (start.isValid() && basicBlock.isExceptionHandler()) {
        CodeExceptionGen exceptionGen = basicBlock.getExceptionGen();
        ObjectType catchType = exceptionGen.getCatchType();
        if (catchType == null) {
            // Probably a finally block, or a synchronized block
            // exception-compensation catch block.
            result.pushFinally();
        } else {
            // Catch type was explicitly specified:
            // this is probably a programmer-written catch block
            result.pushCatch();
        }
    }
}
 
Example 13
Source Project: commons-bcel   Source File: BCELFactory.java    License: Apache License 2.0 6 votes vote down vote up
private void createConstant( final Object value ) {
    String embed = value.toString();
    if (value instanceof String) {
        embed = '"' + Utility.convertString(embed) + '"';
    } else if (value instanceof Character) {
        embed = "(char)0x" + Integer.toHexString(((Character) value).charValue());
    } else if (value instanceof Float) {
        embed += "f";
    } else if (value instanceof Long) {
        embed += "L";
    } else if (value instanceof ObjectType) {
        final ObjectType ot = (ObjectType) value;
        embed = "new ObjectType(\""+ot.getClassName()+"\")";
    }

    _out.println("il.append(new PUSH(_cp, " + embed + "));");
}
 
Example 14
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void testCreateEnumElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow
                                                        // :)
    final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp);
    // Creation of an element like that should leave a new entry in the
    // cpool
    assertTrue(
            "The new ElementValue value index should match the contents of the constantpool but "
                    + evg.getValueIndex() + "!=" + cp.lookupUtf8("Red"),
            evg.getValueIndex() == cp.lookupUtf8("Red"));
    // BCELBUG: Should the class signature or class name be in the constant
    // pool? (see note in ConstantPool)
    // assertTrue("The new ElementValue type index should match the contents
    // of the constantpool but "+
    // evg.getTypeIndex()+"!="+cp.lookupClass(enumType.getSignature()),
    // evg.getTypeIndex()==cp.lookupClass(enumType.getSignature()));
    checkSerialize(evg, cp);
}
 
Example 15
@Override
public void visitNEW(NEW obj) {
    Taint taint = new Taint(Taint.State.SAFE);
    ObjectType type = obj.getLoadClassType(cpg);
    taint.setRealInstanceClass(type);
    if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) {
        taint.setDebugInfo("new " + type.getClassName() + "()");
    }
    getFrame().pushValue(taint);
}
 
Example 16
public IOStreamFactory(String baseClass, String[] uninterestingSubclassList, String bugType) {
    this.baseClassType = ObjectTypeFactory.getInstance(baseClass);
    this.uninterestingSubclassTypeList = new ObjectType[uninterestingSubclassList.length];
    for (int i = 0; i < uninterestingSubclassList.length; ++i) {
        this.uninterestingSubclassTypeList[i] = ObjectTypeFactory.getInstance(uninterestingSubclassList[i]);
    }
    this.bugType = bugType;
}
 
Example 17
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    try {
        Instruction ins = location.getHandle().getInstruction();

        if (ins.getOpcode() != Const.NEW) {
            return null;
        }

        if (Hierarchy.isSubtype(type, baseClassType)) {
            boolean isUninteresting = false;
            for (ObjectType aUninterestingSubclassTypeList : uninterestingSubclassTypeList) {
                if (Hierarchy.isSubtype(type, aUninterestingSubclassTypeList)) {
                    isUninteresting = true;
                    break;
                }
            }
            Stream result = new Stream(location, type.getClassName(), baseClassType.getClassName())
                    .setIgnoreImplicitExceptions(true);
            if (!isUninteresting) {
                result.setInteresting(bugType);
            }
            return result;
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 18
private boolean isPossibleInstanceOfObligationType(Subtypes2 subtypes2, ObjectType type, ObjectType obligationType)
        throws ClassNotFoundException {
    //
    // If we're tracking, e.g., InputStream obligations,
    // and we see a FileInputStream reference being assigned
    // to a field (or returned from a method),
    // then the false-positive supressions heuristic should apply.
    //

    return subtypes2.isSubtype(type, obligationType);
}
 
Example 19
Source Project: commons-bcel   Source File: AbstractTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,
        final String aFruit, final boolean visibility)
{
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.STRING, cp, aFruit);
    final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);
    final ObjectType t = new ObjectType("SimpleStringAnnotation");
    final List<ElementValuePairGen> elements = new ArrayList<>();
    elements.add(nvGen);
    return new AnnotationEntryGen(t, elements, visibility, cp);
}
 
Example 20
@Override
public Stream isResourceCreation(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg) {

    // Use precomputed map of Locations to Stream creations,
    // if present. Note that we don't care about preexisting
    // resources here.
    if (resourceCollection != null) {
        return resourceCollection.getCreatedResource(new Location(handle, basicBlock));
    }

    Instruction ins = handle.getInstruction();
    if (!(ins instanceof TypedInstruction)) {
        return null;
    }

    Type type = ((TypedInstruction) ins).getType(cpg);
    if (!(type instanceof ObjectType)) {
        return null;
    }

    Location location = new Location(handle, basicBlock);

    // All StreamFactories are given an opportunity to
    // look at the location and possibly identify a created stream.
    for (StreamFactory aStreamFactoryList : streamFactoryList) {
        Stream stream = aStreamFactoryList.createStream(location, (ObjectType) type, cpg, lookupFailureCallback);
        if (stream != null) {
            return stream;
        }
    }

    return null;
}
 
Example 21
private Obligation comparesObligationTypeToNull(Edge edge) throws DataflowAnalysisException {
    BasicBlock sourceBlock = edge.getSource();
    InstructionHandle last = sourceBlock.getLastInstruction();
    if (last == null) {
        if (DEBUG_NULL_CHECK) {
            System.out.println("no last instruction in source block of " + edge + " ???");
        }
        return null;
    }
    Type type = null;

    short opcode = last.getInstruction().getOpcode();
    switch (opcode) {
    case Const.IFNULL:
    case Const.IFNONNULL:
        type = nullCheck(opcode, edge, last, sourceBlock);
        break;

    case Const.IF_ACMPEQ:
    case Const.IF_ACMPNE:
        type = acmpNullCheck(opcode, edge, last, sourceBlock);
        break;
    default:
        break;
    }

    if (!(type instanceof ObjectType)) {
        return null;
    }

    try {
        // See if the type of value compared to null is an obligation type.
        return database.getFactory().getObligationByType((ObjectType) type);
    } catch (ClassNotFoundException e) {
        errorLogger.reportMissingClass(e);
        throw new MissingClassException(e);
    }

}
 
Example 22
public static Type merge(@CheckForNull GenericObjectType t1, Type t2) {
    if (t1 == null) {
        return t2;
    }
    if (t2 instanceof ObjectType) {
        return merge(t1, (ObjectType) t2);
    }
    if (t2 instanceof NullType) {
        return t1;
    }
    return t2;
}
 
Example 23
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 24
/**
 * @return the underlying ObjectType for this Generic Object
 */
public ObjectType getObjectType() {
    String cName = ClassName.fromFieldSignature(getSignature());
    if (cName == null) {
        throw new IllegalStateException("Can't provide ObjectType for " + this);
    }
    @DottedClassName
    String c = ClassName.toDottedClassName(cName);
    return ObjectTypeFactory.getInstance(c);
}
 
Example 25
Source Project: spotbugs   Source File: Hierarchy.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine if the given ObjectType refers to an unchecked exception
 * (RuntimeException or Error).
 */
public static boolean isUncheckedException(ObjectType type) throws ClassNotFoundException {
    if (type.equals(Type.THROWABLE) || type.equals(RUNTIME_EXCEPTION_TYPE) || type.equals(ERROR_TYPE)) {
        return true;
    }
    ClassDescriptor c = DescriptorFactory.getClassDescriptor(type);
    Subtypes2 subtypes2 = Global.getAnalysisCache().getDatabase(Subtypes2.class);
    return subtypes2.isSubtype(c, RUNTIME_EXCEPTION, ERROR);

}
 
Example 26
Source Project: spotbugs   Source File: Subtypes2.java    License: 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 27
private static void updateExceptionSet(ExceptionSet exceptionSet, ObjectType type) {
    if (type instanceof ExceptionObjectType) {
        exceptionSet.addAll(((ExceptionObjectType) type).getExceptionSet());
    } else {
        exceptionSet.addExplicit(type);
    }
}
 
Example 28
int getIndexOfType(ObjectType type) {
    Integer index = typeIndexMap.get(type);
    if (index == null) {
        index = getNumTypes();
        typeList.add(type);
        typeIndexMap.put(type, index);
    }
    return index.intValue();
}
 
Example 29
/**
 * Initialize object from an exception set.
 *
 * @param exceptionSet
 *            the exception set
 * @return a Type that is a supertype of all of the exceptions in the
 *         exception set
 */
public static Type fromExceptionSet(ExceptionSet exceptionSet) throws ClassNotFoundException {
    Type commonSupertype = exceptionSet.getCommonSupertype();
    if (commonSupertype.getType() != Const.T_OBJECT) {
        return commonSupertype;
    }

    ObjectType exceptionSupertype = (ObjectType) commonSupertype;

    String className = exceptionSupertype.getClassName();
    if ("java.lang.Throwable".equals(className)) {
        return exceptionSupertype;
    }
    return new ExceptionObjectType(className, exceptionSet);
}
 
Example 30
Source Project: spotbugs   Source File: ExceptionSet.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ObjectType next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    ObjectType result = factory.getType(next);
    last = next;
    return result;
}