Java Code Examples for org.apache.bcel.Repository#instanceOf()

The following examples show how to use org.apache.bcel.Repository#instanceOf() . 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: JavaClassDefinition.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Finds the narrowest method that is compatible with a method.
 * An invocation of the given method can be resolved as an invocation
 * of the narrowest method.
 * @param aClassName the class for the method.
 * @param aMethodName the name of the method.
 * @param aArgTypes the types for the method.
 * @return the narrowest compatible method.
 */
public MethodDefinition findNarrowestMethod(
    String aClassName,
    String aMethodName,
    Type[] aArgTypes)
{
    MethodDefinition result = null;
    final String javaClassName = mJavaClass.getClassName();
    if (Repository.instanceOf(aClassName, javaClassName)) {
        // check all
        for (int i = 0; i < mMethodDefs.length; i++) {
            // TODO: check access privileges
            if (mMethodDefs[i].isCompatible(aMethodName, aArgTypes)) {
                if (result == null) {
                    result = mMethodDefs[i];
                }
                //else if (mMethodDefs[i].isAsNarrow(result)) {
                else if (result.isCompatible(mMethodDefs[i])) {
                    result = mMethodDefs[i];
                }
            }
        }
    }
    return result;
}
 
Example 2
Source File: JavaClassDefinition.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Finds the narrowest method that is compatible with a method.
 * An invocation of the given method can be resolved as an invocation
 * of the narrowest method.
 * @param aClassName the class for the method.
 * @param aMethodName the name of the method.
 * @param aArgTypes the types for the method.
 * @return the narrowest compatible method.
 */
public MethodDefinition findNarrowestMethod(
    String aClassName,
    String aMethodName,
    Type[] aArgTypes)
{
    MethodDefinition result = null;
    final String javaClassName = mJavaClass.getClassName();
    if (Repository.instanceOf(aClassName, javaClassName)) {
        // check all
        for (int i = 0; i < mMethodDefs.length; i++) {
            // TODO: check access privileges
            if (mMethodDefs[i].isCompatible(aMethodName, aArgTypes)) {
                if (result == null) {
                    result = mMethodDefs[i];
                }
                //else if (mMethodDefs[i].isAsNarrow(result)) {
                else if (result.isCompatible(mMethodDefs[i])) {
                    result = mMethodDefs[i];
                }
            }
        }
    }
    return result;
}
 
Example 3
Source File: ReadReturnShouldBeChecked.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isBufferedInputStream() {
    try {
        if (lastCallClass.startsWith("[")) {
            return false;
        }
        return Repository.instanceOf(lastCallClass, "java.io.BufferedInputStream");
    } catch (ClassNotFoundException e) {
        return false;
    }
}
 
Example 4
Source File: ReadReturnShouldBeChecked.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isImageIOInputStream() {
    try {
        if (lastCallClass.startsWith("[")) {
            return false;
        }
        return Repository.instanceOf(lastCallClass, "javax.imageio.stream.ImageInputStream");
    } catch (ClassNotFoundException e) {
        return false;
    }
}
 
Example 5
Source File: MethodDefinition.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine whether this method definition has a reference from a class or
 * a superclass.
 * @param aJavaClass the JavaClass to check against.
 * @return true if there is a reference to this method definition from a
 * aJavaClass or a superclass of aJavaClass.
 */
public boolean hasReference(JavaClass aJavaClass)
{
    final Iterator it = getReferences().iterator();
    while (it.hasNext()) {
        final InvokeReference invokeRef = (InvokeReference) it.next();
        final String invokeClassName = invokeRef.getClassName();
        if (Repository.instanceOf(aJavaClass, invokeClassName)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: MethodDefinition.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine whether this method definition has a reference from a class or
 * a superclass.
 * @param aJavaClass the JavaClass to check against.
 * @return true if there is a reference to this method definition from a
 * aJavaClass or a superclass of aJavaClass.
 */
public boolean hasReference(JavaClass aJavaClass)
{
    final Iterator it = getReferences().iterator();
    while (it.hasNext()) {
        final InvokeReference invokeRef = (InvokeReference) it.next();
        final String invokeClassName = invokeRef.getClassName();
        if (Repository.instanceOf(aJavaClass, invokeClassName)) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: ObjectType.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Return true if this type is a subclass of given ObjectType.
 * @throws ClassNotFoundException if any of this class's superclasses
 *  can't be found
 */
public boolean subclassOf( final ObjectType superclass ) throws ClassNotFoundException {
    if (this.referencesInterfaceExact() || superclass.referencesInterfaceExact()) {
        return false;
    }
    return Repository.instanceOf(this.className, superclass.className);
}
 
Example 8
Source File: ObjectType.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
public boolean subclassOf(ObjectType superclass){
  if (this.referencesInterface() || superclass.referencesInterface())
    return false;

  return Repository.instanceOf(this.class_name, superclass.class_name);
}
 
Example 9
Source File: InstConstraintVisitor.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitINVOKESPECIAL(INVOKESPECIAL o){
	// Don't init an object twice.
	if ( (o.getMethodName(cpg).equals(Constants.CONSTRUCTOR_NAME)) && (!(stack().peek(o.getArgumentTypes(cpg).length) instanceof UninitializedObjectType)) ){
		constraintViolated(o, "Possibly initializing object twice. A valid instruction sequence must not have an uninitialized object on the operand stack or in a local variable during a backwards branch, or in a local variable in code protected by an exception handler. Please see The Java Virtual Machine Specification, Second Edition, 4.9.4 (pages 147 and 148) for details.");
	}

	// the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).

	Type t = o.getType(cpg);
	if (t instanceof ObjectType){
		String name = ((ObjectType)t).getClassName();
		Verifier v = VerifierFactory.getVerifier( name );
		VerificationResult vr = v.doPass2();
		if (vr.getStatus() != VerificationResult.VERIFIED_OK){
			constraintViolated((Instruction) o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
		}
	}


	Type[] argtypes = o.getArgumentTypes(cpg);
	int nargs = argtypes.length;
	
	for (int i=nargs-1; i>=0; i--){
		Type fromStack = stack().peek( (nargs-1) - i );	// 0 to nargs-1
		Type fromDesc = argtypes[i];
		if (fromDesc == Type.BOOLEAN ||
				fromDesc == Type.BYTE ||
				fromDesc == Type.CHAR ||
				fromDesc == Type.SHORT){
			fromDesc = Type.INT;
		}
		if (! fromStack.equals(fromDesc)){
			if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType){
				ReferenceType rFromStack = (ReferenceType) fromStack;
				ReferenceType rFromDesc = (ReferenceType) fromDesc;
				// TODO: This can only be checked using Staerk-et-al's "set of object types", not
				// using a "wider cast object type".
				if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ){
					constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack (which is not assignment compatible).");
				}
			}
			else{
				constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack.");
			}
		}
	}
	
	Type objref = stack().peek(nargs);
	if (objref == Type.NULL){
		return;
	}
	if (! (objref instanceof ReferenceType) ){
		constraintViolated(o, "Expecting a reference type as 'objectref' on the stack, not a '"+objref+"'.");
	}
	String objref_classname = null;
	if ( !(o.getMethodName(cpg).equals(Constants.CONSTRUCTOR_NAME))){
		referenceTypeIsInitialized(o, (ReferenceType) objref);
		if (!(objref instanceof ObjectType)){
			if (!(objref instanceof ArrayType)){
				constraintViolated(o, "Expecting an ObjectType as 'objectref' on the stack, not a '"+objref+"'."); // could be a ReturnaddressType
			}
			else{
				objref = GENERIC_ARRAY;
			}
		}

		objref_classname = ((ObjectType) objref).getClassName();		
	}
	else{
		if (!(objref instanceof UninitializedObjectType)){
			constraintViolated(o, "Expecting an UninitializedObjectType as 'objectref' on the stack, not a '"+objref+"'. Otherwise, you couldn't invoke a method since an array has no methods (not to speak of a return address).");
		}
		objref_classname = ((UninitializedObjectType) objref).getInitialized().getClassName();
	}
	

	String theClass = o.getClassName(cpg);
	if ( ! Repository.instanceOf(objref_classname, theClass) ){
		constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected.");
	}	
	
}
 
Example 10
Source File: InstConstraintVisitor.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitINVOKEVIRTUAL(INVOKEVIRTUAL o){
	// the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).

	Type t = o.getType(cpg);
	if (t instanceof ObjectType){
		String name = ((ObjectType)t).getClassName();
		Verifier v = VerifierFactory.getVerifier( name );
		VerificationResult vr = v.doPass2();
		if (vr.getStatus() != VerificationResult.VERIFIED_OK){
			constraintViolated((Instruction) o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
		}
	}


	Type[] argtypes = o.getArgumentTypes(cpg);
	int nargs = argtypes.length;
	
	for (int i=nargs-1; i>=0; i--){
		Type fromStack = stack().peek( (nargs-1) - i );	// 0 to nargs-1
		Type fromDesc = argtypes[i];
		if (fromDesc == Type.BOOLEAN ||
				fromDesc == Type.BYTE ||
				fromDesc == Type.CHAR ||
				fromDesc == Type.SHORT){
			fromDesc = Type.INT;
		}
		if (! fromStack.equals(fromDesc)){
			if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType){
				ReferenceType rFromStack = (ReferenceType) fromStack;
				ReferenceType rFromDesc = (ReferenceType) fromDesc;
				// TODO: This can possibly only be checked when using Staerk-et-al's "set of object types" instead
				// of a single "wider cast object type" created during verification.
				if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ){
					constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack (which is not assignment compatible).");
				}
			}
			else{
				constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack.");
			}
		}
	}
	
	Type objref = stack().peek(nargs);
	if (objref == Type.NULL){
		return;
	}
	if (! (objref instanceof ReferenceType) ){
		constraintViolated(o, "Expecting a reference type as 'objectref' on the stack, not a '"+objref+"'.");
	}
	referenceTypeIsInitialized(o, (ReferenceType) objref);
	if (!(objref instanceof ObjectType)){
		if (!(objref instanceof ArrayType)){
			constraintViolated(o, "Expecting an ObjectType as 'objectref' on the stack, not a '"+objref+"'."); // could be a ReturnaddressType
		}
		else{
			objref = GENERIC_ARRAY;
		}
	}
	
	String objref_classname = ((ObjectType) objref).getClassName();

	String theClass = o.getClassName(cpg);

	if ( ! Repository.instanceOf(objref_classname, theClass) ){
		constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected.");
	}	
}
 
Example 11
Source File: FindUnrelatedTypesInGenericContainer.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean compareTypesOld(Type parmType, Type argType) {
    // XXX equality not implemented for GenericObjectType
    // if (parmType.equals(argType)) return true;
    // Compare type signatures instead
    if (GenericUtilities.getString(parmType).equals(GenericUtilities.getString(argType))) {
        return true;
    }

    if (parmType instanceof GenericObjectType) {
        GenericObjectType o = (GenericObjectType) parmType;
        if (o.getTypeCategory() == GenericUtilities.TypeCategory.WILDCARD_EXTENDS) {
            return compareTypesOld(o.getExtension(), argType);
        }
    }
    // ignore type variables for now
    if (parmType instanceof GenericObjectType && !((GenericObjectType) parmType).hasParameters()) {
        return true;
    }
    if (argType instanceof GenericObjectType && !((GenericObjectType) argType).hasParameters()) {
        return true;
    }

    // Case: Both are generic containers
    if (parmType instanceof GenericObjectType && argType instanceof GenericObjectType) {
        return true;
    } else {
        // Don't consider non reference types (should not be possible)
        if (!(parmType instanceof ReferenceType && argType instanceof ReferenceType)) {
            return true;
        }

        // Don't consider non object types (for now)
        if (!(parmType instanceof ObjectType && argType instanceof ObjectType)) {
            return true;
        }

        // Otherwise, compare base types ignoring generic information
        try {
            return Repository.instanceOf(((ObjectType) argType).getClassName(), ((ObjectType) parmType).getClassName());
        } catch (ClassNotFoundException e) {
        }
    }

    return true;
}
 
Example 12
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitINVOKESPECIAL(final INVOKESPECIAL o) {
    try {
    // INVOKESPECIAL is a LoadClass; the Class where the referenced method is declared in,
    // is therefore resolved/verified.
    // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified,
    // too. So are the allowed method names.
    final String classname = o.getClassName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(classname);
    final Method m = getMethodRecursive(jc, o);
    if (m == null) {
        constraintViolated(o, "Referenced method '"+o.getMethodName(constantPoolGen)+"' with expected signature '"+o.getSignature(constantPoolGen)
            +"' not found in class '"+jc.getClassName()+"'.");
    }

    JavaClass current = Repository.lookupClass(myOwner.getClassName());
    if (current.isSuper()) {

        if ((Repository.instanceOf( current, jc )) && (!current.equals(jc))) {

            if (! (o.getMethodName(constantPoolGen).equals(Const.CONSTRUCTOR_NAME) )) {
                // Special lookup procedure for ACC_SUPER classes.

                int supidx = -1;

                Method meth = null;
                while (supidx != 0) {
                    supidx = current.getSuperclassNameIndex();
                    current = Repository.lookupClass(current.getSuperclassName());

                    final Method[] meths = current.getMethods();
                    for (final Method meth2 : meths) {
                        if    ( (meth2.getName().equals(o.getMethodName(constantPoolGen))) &&
                             (Type.getReturnType(meth2.getSignature()).equals(o.getReturnType(constantPoolGen))) &&
                             (objarrayequals(Type.getArgumentTypes(meth2.getSignature()), o.getArgumentTypes(constantPoolGen))) ) {
                            meth = meth2;
                            break;
                        }
                    }
                    if (meth != null) {
                        break;
                    }
                }
                if (meth == null) {
                    constraintViolated(o, "ACC_SUPER special lookup procedure not successful: method '"+
                        o.getMethodName(constantPoolGen)+"' with proper signature not declared in superclass hierarchy.");
                }
            }
        }
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }

}
 
Example 13
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitINVOKESPECIAL(final INVOKESPECIAL o) {
    try {
    // Don't init an object twice.
    if ( (o.getMethodName(cpg).equals(Const.CONSTRUCTOR_NAME)) &&
         (!(stack().peek(o.getArgumentTypes(cpg).length) instanceof UninitializedObjectType)) ) {
        constraintViolated(o, "Possibly initializing object twice."+
             " A valid instruction sequence must not have an uninitialized object on the operand stack or in a local variable"+
             " during a backwards branch, or in a local variable in code protected by an exception handler."+
             " Please see The Java Virtual Machine Specification, Second Edition, 4.9.4 (pages 147 and 148) for details.");
    }

    // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).

    final Type t = o.getType(cpg);
    if (t instanceof ObjectType) {
        final String name = ((ObjectType)t).getClassName();
        final Verifier v = VerifierFactory.getVerifier( name );
        final VerificationResult vr = v.doPass2();
        if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
            constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
        }
    }


    final Type[] argtypes = o.getArgumentTypes(cpg);
    final int nargs = argtypes.length;

    for (int i=nargs-1; i>=0; i--) {
        final Type fromStack = stack().peek( (nargs-1) - i );    // 0 to nargs-1
        Type fromDesc = argtypes[i];
        if (fromDesc == Type.BOOLEAN ||
                fromDesc == Type.BYTE ||
                fromDesc == Type.CHAR ||
                fromDesc == Type.SHORT) {
            fromDesc = Type.INT;
        }
        if (! fromStack.equals(fromDesc)) {
            if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) {
                final ReferenceType rFromStack = (ReferenceType) fromStack;
                final ReferenceType rFromDesc = (ReferenceType) fromDesc;
                // TODO: This can only be checked using Staerk-et-al's "set of object types", not
                // using a "wider cast object type".
                if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ) {
                    constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+
                        "' on the stack (which is not assignment compatible).");
                }
                referenceTypeIsInitialized(o, rFromStack);
            }
            else{
                constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack.");
            }
        }
    }

    Type objref = stack().peek(nargs);
    if (objref == Type.NULL) {
        return;
    }
    if (! (objref instanceof ReferenceType) ) {
        constraintViolated(o, "Expecting a reference type as 'objectref' on the stack, not a '"+objref+"'.");
    }
    String objref_classname = null;
    if ( !(o.getMethodName(cpg).equals(Const.CONSTRUCTOR_NAME))) {
        referenceTypeIsInitialized(o, (ReferenceType) objref);
        if (!(objref instanceof ObjectType)) {
            if (!(objref instanceof ArrayType)) { // could be a ReturnaddressType
                constraintViolated(o, "Expecting an ObjectType as 'objectref' on the stack, not a '"+objref+"'.");
            }
            else{
                objref = GENERIC_ARRAY;
            }
        }

        objref_classname = ((ObjectType) objref).getClassName();
    }
    else{
        if (!(objref instanceof UninitializedObjectType)) {
            constraintViolated(o, "Expecting an UninitializedObjectType as 'objectref' on the stack, not a '"+objref+
                "'. Otherwise, you couldn't invoke a method since an array has no methods (not to speak of a return address).");
        }
        objref_classname = ((UninitializedObjectType) objref).getInitialized().getClassName();
    }


    final String theClass = o.getClassName(cpg);
    if ( ! Repository.instanceOf(objref_classname, theClass) ) {
        constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected.");
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 14
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitINVOKEVIRTUAL(final INVOKEVIRTUAL o) {
    try {
    // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).

    final Type t = o.getType(cpg);
    if (t instanceof ObjectType) {
        final String name = ((ObjectType)t).getClassName();
        final Verifier v = VerifierFactory.getVerifier( name );
        final VerificationResult vr = v.doPass2();
        if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
            constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
        }
    }


    final Type[] argtypes = o.getArgumentTypes(cpg);
    final int nargs = argtypes.length;

    for (int i=nargs-1; i>=0; i--) {
        final Type fromStack = stack().peek( (nargs-1) - i );    // 0 to nargs-1
        Type fromDesc = argtypes[i];
        if (fromDesc == Type.BOOLEAN ||
                fromDesc == Type.BYTE ||
                fromDesc == Type.CHAR ||
                fromDesc == Type.SHORT) {
            fromDesc = Type.INT;
        }
        if (! fromStack.equals(fromDesc)) {
            if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) {
                final ReferenceType rFromStack = (ReferenceType) fromStack;
                final ReferenceType rFromDesc = (ReferenceType) fromDesc;
                // TODO: This can possibly only be checked when using Staerk-et-al's "set of object types" instead
                // of a single "wider cast object type" created during verification.
                if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ) {
                    constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+
                        "' on the stack (which is not assignment compatible).");
                }
                referenceTypeIsInitialized(o, rFromStack);
            }
            else{
                constraintViolated(o, "Expecting a '"+fromDesc+"' but found a '"+fromStack+"' on the stack.");
            }
        }
    }

    Type objref = stack().peek(nargs);
    if (objref == Type.NULL) {
        return;
    }
    if (! (objref instanceof ReferenceType) ) {
        constraintViolated(o, "Expecting a reference type as 'objectref' on the stack, not a '"+objref+"'.");
    }
    referenceTypeIsInitialized(o, (ReferenceType) objref);
    if (!(objref instanceof ObjectType)) {
        if (!(objref instanceof ArrayType)) { // could be a ReturnaddressType
            constraintViolated(o, "Expecting an ObjectType as 'objectref' on the stack, not a '"+objref+"'.");
        }
        else{
            objref = GENERIC_ARRAY;
        }
    }

    final String objref_classname = ((ObjectType) objref).getClassName();

    final String theClass = o.getClassName(cpg);

    if ( ! Repository.instanceOf(objref_classname, theClass) ) {
        constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}