Java Code Examples for org.apache.bcel.classfile.Field#isStatic()

The following examples show how to use org.apache.bcel.classfile.Field#isStatic() . 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: CheckAnalysisContextContainedAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field field) {
    if (!field.isStatic()) {
        return;
    }
    String signature = field.getSignature();
    if (signature.startsWith("Ljava/util/") && !"Ljava/util/regex/Pattern;".equals(signature)
            && !"Ljava/util/logging/Logger;".equals(signature) && !"Ljava/util/BitSet;".equals(signature)
            && !"Ljava/util/ResourceBundle;".equals(signature)
            && !"Ljava/util/Comparator;".equals(signature)
            && getXField().getAnnotation(ConstantAnnotation) == null) {
        boolean flagged = analysisContextContained(getXClass());

        bugReporter.reportBug(new BugInstance(this, "TESTING", flagged ? NORMAL_PRIORITY : LOW_PRIORITY).addClass(this).addField(this).addType(
                signature));

    }
}
 
Example 2
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 6 votes vote down vote up
protected Field[] getFields(final ClassItem classItem, final boolean staticFields) {
  final Set<Field> fieldSet = new TreeSet<Field>(new Comparator<Field>() {

    @Override
    public int compare(final Field o1, final Field o2) {
      return o1.getName().compareTo(o2.getName());
    }
  });

  final Field[] fields = classItem.getJavaClass().getFields();
  for (final Field field : fields) {
    if (staticFields) {
      if (field.isStatic()) {
        fieldSet.add(field);
      }
    } else {
      if (!field.isStatic()) {
        fieldSet.add(field);
      }
    }
  }

  return fieldSet.toArray(new Field[fieldSet.size()]);
}
 
Example 3
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 6 votes vote down vote up
protected String field2str(final Field field) {
  String modifier = "";

  if (field.isPrivate()) {
    modifier = "private ";
  } else if (field.isProtected()) {
    modifier = "protected ";
  } else if (field.isPublic()) {
    modifier = "public ";
  }

  if (field.isStatic()) {
    modifier += "static ";
  }

  if (field.isFinal()) {
    modifier += "final ";
  }

  modifier += field.getType().toString();

  modifier += ' ' + field.getName();

  return modifier;
}
 
Example 4
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitGETSTATIC(final GETSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 5
Source File: FunctionsThatMightBeMistakenForProcedures.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Field obj) {
    if ("this$0".equals(obj.getName())) {
        isInnerClass = true;
    }
    if (!obj.isFinal() && !obj.isStatic() && !BCELUtil.isSynthetic(obj)) {
        hasNonFinalFields = true;
    }
}
 
Example 6
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 visitGETFIELD(GETFIELD o){
	Type objectref = stack().peek();
	if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ){
		constraintViolated(o, "Stack top should be an object reference that's not an array reference, but is '"+objectref+"'.");
	}
	
	String field_name = o.getFieldName(cpg);
	
	JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
	Field[] fields = jc.getFields();
	Field f = null;
	for (int i=0; i<fields.length; i++){
		if (fields[i].getName().equals(field_name)){
			f = fields[i];
			break;
		}
	}
	if (f == null){
		throw new AssertionViolatedException("Field not found?!?");
	}

	if (f.isProtected()){
		ObjectType classtype = o.getClassType(cpg);
		ObjectType curr = new ObjectType(mg.getClassName());

		if (	classtype.equals(curr) ||
					curr.subclassOf(classtype)	){
			Type t = stack().peek();
			if (t == Type.NULL){
				return;
			}
			if (! (t instanceof ObjectType) ){
				constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+t+"'.");
			}
			ObjectType objreftype = (ObjectType) t;
			if (! ( objreftype.equals(curr) ||
					    objreftype.subclassOf(curr) ) ){
				//TODO: One day move to Staerk-et-al's "Set of object types" instead of "wider" object types
				//      created during the verification.
				//      "Wider" object types don't allow us to check for things like that below.
				//constraintViolated(o, "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or a superclass of the current class. However, the referenced object type '"+stack().peek()+"' is not the current class or a subclass of the current class.");
			}
		} 
	}
	
	// TODO: Could go into Pass 3a.
	if (f.isStatic()){
		constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
	}
}
 
Example 7
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 visitPUTFIELD(PUTFIELD o){

	Type objectref = stack().peek(1);
	if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ){
		constraintViolated(o, "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'.");
	}
	
	String field_name = o.getFieldName(cpg);
	
	JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
	Field[] fields = jc.getFields();
	Field f = null;
	for (int i=0; i<fields.length; i++){
		if (fields[i].getName().equals(field_name)){
			f = fields[i];
			break;
		}
	}
	if (f == null){
		throw new AssertionViolatedException("Field not found?!?");
	}

	Type value = stack().peek();
	Type t = Type.getType(f.getSignature());
	Type shouldbe = t;
	if (shouldbe == Type.BOOLEAN ||
			shouldbe == Type.BYTE ||
			shouldbe == Type.CHAR ||
			shouldbe == Type.SHORT){
		shouldbe = Type.INT;
	}
	if (t instanceof ReferenceType){
		ReferenceType rvalue = null;
		if (value instanceof ReferenceType){
			rvalue = (ReferenceType) value;
			referenceTypeIsInitialized(o, rvalue);
		}
		else{
			constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
		}
		// TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
		// using "wider cast object types" created during verification.
		// Comment it out if you encounter problems. See also the analogon at visitPUTSTATIC.
		if (!(rvalue.isAssignmentCompatibleWith(shouldbe))){
			constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
		}
	}
	else{
		if (shouldbe != value){
			constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
		}
	}
	
	if (f.isProtected()){
		ObjectType classtype = o.getClassType(cpg);
		ObjectType curr = new ObjectType(mg.getClassName());

		if (	classtype.equals(curr) ||
					curr.subclassOf(classtype)	){
			Type tp = stack().peek(1);
			if (tp == Type.NULL){
				return;
			}
			if (! (tp instanceof ObjectType) ){
				constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+tp+"'.");
			}
			ObjectType objreftype = (ObjectType) tp;
			if (! ( objreftype.equals(curr) ||
					    objreftype.subclassOf(curr) ) ){
				constraintViolated(o, "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or a superclass of the current class. However, the referenced object type '"+stack().peek()+"' is not the current class or a subclass of the current class.");
			}
		} 
	}

	// TODO: Could go into Pass 3a.
	if (f.isStatic()){
		constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
	}
}
 
Example 8
Source File: StaticCalendarDetector.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Checks if the visited field is of type {@link java.util.Calendar} or
 * {@link java.text.DateFormat} or a subclass of either one. If so and the
 * field is static and non-private it is suspicious and will be reported.
 */
@Override
public void visit(Field aField) {
    if (aField.isPrivate()) {
        /*
         * private fields are harmless, as long as they are used correctly
         * inside their own class. This should be something the rest of this
         * detector can find out, so do not report them, they might be false
         * positives.
         */
        return;
    }
    String superclassName = getSuperclassName();
    if (!aField.isStatic() && !"java/lang/Enum".equals(superclassName)) {
        return;
    }
    if (!aField.isPublic() && !aField.isProtected()) {
        return;
    }
    ClassDescriptor classOfField = DescriptorFactory.createClassDescriptorFromFieldSignature(aField.getSignature());
    String tBugType = null;
    int priority = aField.isPublic() && aField.isFinal() && aField.getName().equals(aField.getName().toUpperCase())
            && getThisClass().isPublic() ? HIGH_PRIORITY : NORMAL_PRIORITY;
    if (classOfField != null) {
        try {
            if (subtypes2.isSubtype(classOfField, calendarType)) {
                tBugType = "STCAL_STATIC_CALENDAR_INSTANCE";
                priority++;
            } else if (subtypes2.isSubtype(classOfField, dateFormatType)) {
                tBugType = "STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE";
            }
            if (getClassContext().getXClass().usesConcurrency()) {
                priority--;
            }
            if (tBugType != null) {

                pendingBugs.put(getXField(), new BugInstance(this, tBugType, priority).addClass(currentClass).addField(this));
            }
        } catch (ClassNotFoundException e) {
            AnalysisContext.reportMissingClass(e);
        }
    }

}
 
Example 9
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {
    String mName = getMethodName();
    if (mName.length() == 1) {
        return;
    }
    if ("isRequestedSessionIdFromURL".equals(mName) || "isRequestedSessionIdFromUrl".equals(mName)) {
        return;
    }
    String sig = getMethodSig();
    if (mName.equals(baseClassName) && "()V".equals(sig)) {
        Code code = obj.getCode();
        Method realVoidConstructor = findVoidConstructor(getThisClass());
        if (code != null && !markedAsNotUsable(obj)) {
            int priority = NORMAL_PRIORITY;
            if (codeDoesSomething(code)) {
                priority--;
            } else if (!obj.isPublic() && getThisClass().isPublic()) {
                priority--;
            }
            boolean instanceMembers = false;
            for (Method m : this.getThisClass().getMethods()) {
                if (!m.isStatic() && m != obj && !isVoidConstructor(getThisClass(), m)) {
                    instanceMembers = true;
                }
            }
            for (Field f : this.getThisClass().getFields()) {
                if (!f.isStatic()) {
                    instanceMembers = true;
                }
            }
            if (!codeDoesSomething(code) && !instanceMembers && "java/lang/Object".equals(getSuperclassName())) {
                priority += 2;
            }
            if (hasBadMethodNames) {
                priority++;
            }
            if (!getXClass().getAnnotations().isEmpty()) {
                priority++;
            }
            if (realVoidConstructor != null) {
                priority = LOW_PRIORITY;
            }

            bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this)
                    .lowerPriorityIfDeprecated());
            return;
        }
    } else if (badMethodName(mName)) {
        bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadMethodNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClassAndMethod(this));
    }

    if (obj.isAbstract()) {
        return;
    }
    if (obj.isPrivate()) {
        return;
    }

    if ("equal".equals(mName) && "(Ljava/lang/Object;)Z".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("hashcode".equals(mName) && "()I".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("tostring".equals(mName) && "()Ljava/lang/String;".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }

    if (obj.isPrivate() || obj.isStatic() || Const.CONSTRUCTOR_NAME.equals(mName)) {
        return;
    }

    String sig2 = removePackageNamesFromSignature(sig);
    String allSmall = mName.toLowerCase() + sig2;

    XMethod xm = getXMethod();
    {
        TreeSet<XMethod> s = canonicalToXMethod.computeIfAbsent(allSmall, k -> new TreeSet<>());
        s.add(xm);
    }

}
 
Example 10
Source File: FindMaskedFields.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    classFields.clear();

    Field[] fields = obj.getFields();
    String fieldName;
    for (Field field : fields) {
        if (!field.isStatic() && !field.isPrivate()) {
            fieldName = field.getName();
            classFields.put(fieldName, field);
        }
    }

    // Walk up the super class chain, looking for name collisions

    XClass c = getXClass();
    while (true) {
        ClassDescriptor s = c.getSuperclassDescriptor();
        if (s == null || "java/lang/Object".equals(s.getClassName())) {
            break;
        }
        try {
            c = Global.getAnalysisCache().getClassAnalysis(XClass.class, s);
        } catch (CheckedAnalysisException e) {
            break;
        }

        for (XField fld : c.getXFields()) {
            if (!fld.isStatic() && (fld.isPublic() || fld.isProtected())) {
                fieldName = fld.getName();
                if (fieldName.length() == 1) {
                    continue;
                }
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                String superClassName = s.getClassName();
                if (superClassName.startsWith("java/io")
                        && (superClassName.endsWith("InputStream") && "in".equals(fieldName) || superClassName
                                .endsWith("OutputStream") && "out".equals(fieldName))) {
                    continue;
                }
                if (classFields.containsKey(fieldName)) {
                    Field maskingField = classFields.get(fieldName);
                    String mClassName = getDottedClassName();
                    FieldAnnotation fa = new FieldAnnotation(mClassName, maskingField.getName(), maskingField.getSignature(),
                            maskingField.isStatic());
                    int priority = NORMAL_PRIORITY;
                    if (maskingField.isStatic() || maskingField.isFinal()) {
                        priority++;
                    } else if (fld.getSignature().charAt(0) == 'L' && !fld.getSignature().startsWith("Ljava/lang/")
                            || fld.getSignature().charAt(0) == '[') {
                        priority--;
                    }
                    if (!fld.getSignature().equals(maskingField.getSignature())) {
                        priority += 2;
                    } else if (fld.getAccessFlags() != maskingField.getAccessFlags()) {
                        priority++;
                    }
                    if (fld.isSynthetic() || fld.getName().indexOf('$') >= 0) {
                        priority++;
                    }

                    FieldAnnotation maskedFieldAnnotation = FieldAnnotation.fromFieldDescriptor(fld.getFieldDescriptor());
                    BugInstance bug = new BugInstance(this, "MF_CLASS_MASKS_FIELD", priority).addClass(this).addField(fa)
                            .describe("FIELD_MASKING").addField(maskedFieldAnnotation).describe("FIELD_MASKED");
                    rememberedBugs.add(new RememberedBug(bug, fa, maskedFieldAnnotation));

                }
            }
        }
    }

    super.visit(obj);
}
 
Example 11
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 visitPUTSTATIC(final PUTSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (f.isFinal()) {
        if (!(myOwner.getClassName().equals(getObjectType(o).getClassName()))) {
            constraintViolated(o,
                "Referenced field '"+f+"' is final and must therefore be declared in the current class '"+
                    myOwner.getClassName()+"' which is not the case: it is declared in '"+o.getReferenceType(constantPoolGen)+"'.");
        }
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }

    final String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[methodNo].getName();

    // If it's an interface, it can be set only in <clinit>.
    if ((!(jc.isClass())) && (!(meth_name.equals(Const.STATIC_INITIALIZER_NAME)))) {
        constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Const.STATIC_INITIALIZER_NAME+"' method.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 12
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
@Override
public void visitField(final Field obj) {

    if (jc.isClass()) {
        int maxone=0;
        if (obj.isPrivate()) {
            maxone++;
        }
        if (obj.isProtected()) {
            maxone++;
        }
        if (obj.isPublic()) {
            maxone++;
        }
        if (maxone > 1) {
            throw new ClassConstraintException("Field '"+tostring(obj)+
                "' must only have at most one of its ACC_PRIVATE, ACC_PROTECTED, ACC_PUBLIC modifiers set.");
        }

        if (obj.isFinal() && obj.isVolatile()) {
            throw new ClassConstraintException("Field '"+tostring(obj)+
                "' must only have at most one of its ACC_FINAL, ACC_VOLATILE modifiers set.");
        }
    }
    else{ // isInterface!
        if (!obj.isPublic()) {
            throw new ClassConstraintException("Interface field '"+tostring(obj)+
                "' must have the ACC_PUBLIC modifier set but hasn't!");
        }
        if (!obj.isStatic()) {
            throw new ClassConstraintException("Interface field '"+tostring(obj)+
                "' must have the ACC_STATIC modifier set but hasn't!");
        }
        if (!obj.isFinal()) {
            throw new ClassConstraintException("Interface field '"+tostring(obj)+
                "' must have the ACC_FINAL modifier set but hasn't!");
        }
    }

    if ((obj.getAccessFlags() & ~(Const.ACC_PUBLIC|Const.ACC_PRIVATE|Const.ACC_PROTECTED|Const.ACC_STATIC|
                                  Const.ACC_FINAL|Const.ACC_VOLATILE|Const.ACC_TRANSIENT)) > 0) {
        addMessage("Field '"+tostring(obj)+
            "' has access flag(s) other than ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED,"+
                " ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT set (ignored).");
    }

    checkIndex(obj, obj.getNameIndex(), CONST_Utf8);

    final String name = obj.getName();
    if (! validFieldName(name)) {
        throw new ClassConstraintException("Field '"+tostring(obj)+"' has illegal name '"+obj.getName()+"'.");
    }

    // A descriptor is often named signature in BCEL
    checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8);

    final String sig  = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor)

    try{
        Type.getType(sig);  /* Don't need the return value */
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }

    final String nameanddesc = name+sig;
    if (field_names_and_desc.contains(nameanddesc)) {
        throw new ClassConstraintException("No two fields (like '"+tostring(obj)+
            "') are allowed have same names and descriptors!");
    }
    if (field_names.contains(name)) {
        addMessage("More than one field of name '"+name+
            "' detected (but with different type descriptors). This is very unusual.");
    }
    field_names_and_desc.add(nameanddesc);
    field_names.add(name);

    final Attribute[] atts = obj.getAttributes();
    for (final Attribute att : atts) {
        if ((!(att instanceof ConstantValue)) &&
                (!(att instanceof Synthetic)) &&
                (!(att instanceof Deprecated))) {
            addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" +
                tostring(obj) + "' is unknown and will therefore be ignored.");
        }
        if (!(att instanceof ConstantValue)) {
            addMessage("Attribute '" + tostring(att) + "' as an attribute of Field '" + tostring(obj) +
                "' is not a ConstantValue and is therefore only of use for debuggers and such.");
        }
    }
}
 
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 visitPUTFIELD(final PUTFIELD o) {
    try {

    final Type objectref = stack().peek(1);
    if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ) {
        constraintViolated(o,
            "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'.");
    }

    final String field_name = o.getFieldName(cpg);

    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
              final Type f_type = Type.getType(field.getSignature());
              final Type o_type = o.getType(cpg);
                /* TODO: Check if assignment compatibility is sufficient.
               * What does Sun do?
               */
              if (f_type.equals(o_type)) {
                    f = field;
                    break;
                }
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    final Type value = stack().peek();
    final Type t = Type.getType(f.getSignature());
    Type shouldbe = t;
    if (shouldbe == Type.BOOLEAN ||
            shouldbe == Type.BYTE ||
            shouldbe == Type.CHAR ||
            shouldbe == Type.SHORT) {
        shouldbe = Type.INT;
    }
    if (t instanceof ReferenceType) {
        ReferenceType rvalue = null;
        if (value instanceof ReferenceType) {
            rvalue = (ReferenceType) value;
            referenceTypeIsInitialized(o, rvalue);
        }
        else{
            constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
        }
        // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
        // using "wider cast object types" created during verification.
        // Comment it out if you encounter problems. See also the analogon at visitPUTSTATIC.
        if (!(rvalue.isAssignmentCompatibleWith(shouldbe))) {
            constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
        }
    }
    else{
        if (shouldbe != value) {
            constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
        }
    }

    if (f.isProtected()) {
        final ObjectType classtype = getObjectType(o);
        final ObjectType curr = ObjectType.getInstance(mg.getClassName());

        if (    classtype.equals(curr) ||
                    curr.subclassOf(classtype)    ) {
            final Type tp = stack().peek(1);
            if (tp == Type.NULL) {
                return;
            }
            if (! (tp instanceof ObjectType) ) {
                constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+tp+"'.");
            }
            final ObjectType objreftype = (ObjectType) tp;
            if (! ( objreftype.equals(curr) ||
                        objreftype.subclassOf(curr) ) ) {
                constraintViolated(o,
                    "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or"+
                    " a superclass of the current class. However, the referenced object type '"+stack().peek()+
                    "' is not the current class or a subclass of the current class.");
            }
        }
    }

    // TODO: Could go into Pass 3a.
    if (f.isStatic()) {
        constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 14
Source File: ClassParserUsingBCEL.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * @param obj
 *            the field to parse
 * @return a descriptor for the field
 */
protected FieldDescriptor parseField(Field obj) {
    return new FieldDescriptor(slashedClassName, obj.getName(), obj.getSignature(), obj.isStatic());
}
 
Example 15
Source File: FieldAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Factory method. Construct from class name and BCEL Field object.
 *
 * @param className
 *            the name of the class which defines the field
 * @param field
 *            the BCEL Field object
 * @return the FieldAnnotation
 */
public static FieldAnnotation fromBCELField(@DottedClassName String className, Field field) {
    return new FieldAnnotation(className, field.getName(), field.getSignature(), field.isStatic());
}
 
Example 16
Source File: FieldAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Factory method. Construct from class name and BCEL Field object.
 *
 * @param jClass
 *            the class which defines the field
 * @param field
 *            the BCEL Field object
 * @return the FieldAnnotation
 */
public static FieldAnnotation fromBCELField(JavaClass jClass, Field field) {
    return new FieldAnnotation(jClass.getClassName(), field.getName(), field.getSignature(), field.isStatic());
}