org.apache.bcel.generic.ObjectType Java Examples

The following examples show how to use org.apache.bcel.generic.ObjectType. 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: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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
Source File: BlockTypeAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #3
Source File: ExceptionHandlerMap.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #4
Source File: Hierarchy2.java    From spotbugs with 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 #5
Source File: ObligationFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #6
Source File: StaticFieldLoadStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #7
Source File: UnconditionalValueDerefAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #8
Source File: AnyMethodReturnValueStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #9
Source File: GenericUtilities.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #10
Source File: Subtypes2.java    From spotbugs with 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 #11
Source File: ObjectTypeFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #12
Source File: GenericSignatureParser.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #13
Source File: BCELFactory.java    From commons-bcel with 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 File: ElementValueGenTestCase.java    From commons-bcel with 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
Source File: ExceptionSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Return whether or not the set contains any checked exceptions.
 */
public boolean containsCheckedExceptions() throws ClassNotFoundException {
    for (ThrownExceptionIterator i = iterator(); i.hasNext();) {
        ObjectType type = i.next();
        if (!Hierarchy.isUncheckedException(type)) {
            return true;
        }
    }
    return false;
}
 
Example #16
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 #17
Source File: ExceptionSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add an exception.
 *
 * @param type
 *            the exception type
 * @param explicit
 *            true if the exception is explicitly declared or thrown, false
 *            if implicit
 */
public void add(ObjectType type, boolean explicit) {
    int index = factory.getIndexOfType(type);
    if (!exceptionSet.get(index)) {
        ++size;
    }
    exceptionSet.set(index);
    if (explicit) {
        explicitSet.set(index);
    }

    commonSupertype = null;
}
 
Example #18
Source File: ExceptionSetFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #19
Source File: ExceptionSet.java    From spotbugs with 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;
}
 
Example #20
Source File: ExceptionObjectType.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #21
Source File: ExceptionSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks to see if the exception set is a singleton set containing just the
 * named exception
 *
 * @param exceptionName
 *            (in dotted format)
 * @return true if it is
 */
public boolean isSingleton(String exceptionName) {
    if (size != 1) {
        return false;
    }
    ObjectType e = iterator().next();
    return e.toString().equals(exceptionName);

}
 
Example #22
Source File: TransitiveHull.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void checkType(Type type) {
    if (type instanceof ArrayType) {
        type = ((ArrayType) type).getBasicType();
    }

    if (type instanceof ObjectType) {
        add(((ObjectType) type).getClassName());
    }
}
 
Example #23
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Assures the generic preconditions of a LoadClass instance.
 * The referenced class is loaded and pass2-verified.
 */
@Override
public void visitLoadClass(final LoadClass loadClass) {
    final ObjectType t = loadClass.getLoadClassType(constantPoolGen);
    if (t != null) {// null means "no class is loaded"
        final Verifier v = VerifierFactory.getVerifier(t.getClassName());
        final VerificationResult vr = v.doPass1();
        if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
            constraintViolated((Instruction) loadClass,
                "Class '"+loadClass.getLoadClassType(constantPoolGen).getClassName()+"' is referenced, but cannot be loaded: '"+vr+"'.");
        }
    }
}
 
Example #24
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 #25
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitAllocationInstruction( final AllocationInstruction i ) {
    Type type;
    if (i instanceof CPInstruction) {
        type = ((CPInstruction) i).getType(_cp);
    } else {
        type = ((NEWARRAY) i).getType();
    }
    final short opcode = ((Instruction) i).getOpcode();
    int dim = 1;
    switch (opcode) {
        case Const.NEW:
            _out.println("il.append(_factory.createNew(\"" + ((ObjectType) type).getClassName()
                    + "\"));");
            break;
        case Const.MULTIANEWARRAY:
            dim = ((MULTIANEWARRAY) i).getDimensions();
            //$FALL-THROUGH$
        case Const.ANEWARRAY:
        case Const.NEWARRAY:
            if (type instanceof ArrayType) {
                type = ((ArrayType) type).getBasicType();
            }
            _out.println("il.append(_factory.createNewArray(" + BCELifier.printType(type)
                    + ", (short) " + dim + "));");
            break;
        default:
            throw new IllegalArgumentException("Unhandled opcode: " + opcode);
    }
}
 
Example #26
Source File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #27
Source File: TestArrayAccess02Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void createMethod_1() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] {  },
          "test", TEST_PACKAGE+".TestArrayAccess02", il, _cp);

  final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE+".TestArrayAccess02"), (short) 1));
  il.append(InstructionFactory.createStore(Type.OBJECT, 0));
  final InstructionHandle ih_5 = il.append(new PUSH(_cp, 1));
  Assert.assertNotNull(ih_5); // TODO why is this not used
  il.append(_factory.createNewArray(Type.STRING, (short) 1));
  il.append(InstructionFactory.createStore(Type.OBJECT, 1));
  final InstructionHandle ih_10 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1));
  Assert.assertNotNull(ih_10); // TODO why is this not used
  il.append(new PUSH(_cp, 0));
  il.append(_factory.createNew(TEST_PACKAGE+".TestArrayAccess02"));
  il.append(InstructionConst.DUP);
  il.append(_factory.createInvoke(TEST_PACKAGE+".TestArrayAccess02", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  il.append(InstructionConst.AASTORE);
  final InstructionHandle ih_20 = il.append(InstructionFactory.createReturn(Type.VOID));
  Assert.assertNotNull(ih_20); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #28
Source File: StandardTypeMerger.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void updateExceptionSet(ExceptionSet exceptionSet, ObjectType type) {
    if (type instanceof ExceptionObjectType) {
        exceptionSet.addAll(((ExceptionObjectType) type).getExceptionSet());
    } else {
        exceptionSet.addExplicit(type);
    }
}
 
Example #29
Source File: Hierarchy.java    From spotbugs with 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 #30
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testCreateClassElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final ObjectType classType = new ObjectType("java.lang.Integer");
    final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);
    assertTrue("Unexpected value for contained class: '"
            + evg.getClassString() + "'", evg.getClassString().contains("Integer"));
    checkSerialize(evg, cp);
}