Java Code Examples for org.apache.bcel.classfile.Field

The following examples show how to use org.apache.bcel.classfile.Field. 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 visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();
    if (OBJECT_MAPPER_CLASSES.contains(javaClass.getClassName())) {
        return;
    }
    for (Field field : javaClass.getFields()) {
        analyzeField(field, javaClass);
    }
    for (Method m : javaClass.getMethods()) {
        try {
            analyzeMethod(m, classContext);
        }
        catch (CFGBuilderException | DataflowAnalysisException e) {
        }
    }
}
 
Example 2
private void analyzeField(Field field, JavaClass javaClass) {
    for (AnnotationEntry annotation : field.getAnnotationEntries())  {
        if (ANNOTATION_TYPES.contains(annotation.getAnnotationType()) ||
                annotation.getAnnotationType().contains("JsonTypeInfo")) {
            for (ElementValuePair elementValuePair : annotation.getElementValuePairs()) {
                if ("use".equals((elementValuePair.getNameString())) &&
                        VULNERABLE_USE_NAMES.contains(elementValuePair.getValue().stringifyValue())) {
                    bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY)
                            .addClass(javaClass)
                            .addString(javaClass.getClassName() + " on field " +
                                    field.getName() + " of type " + field.getType() +
                                    " annotated with " + annotation.toShortString())
                            .addField(FieldAnnotation.fromBCELField(javaClass, field))
                            .addString("")
                    );
                }
            }
        }
    }
}
 
Example 3
private void doVisitField(Field field) {
    if (visitingField) {
        throw new IllegalStateException("visitField called when already visiting a field");
    }
    visitingField = true;
    this.field = field;
    try {
        fieldName = fieldSig = dottedFieldSig = fullyQualifiedFieldName = null;
        thisFieldInfo = (FieldInfo) thisClassInfo.findField(getFieldName(), getFieldSig(), field.isStatic());
        assert thisFieldInfo != null : "Can't get field info for " + getFullyQualifiedFieldName();
        fieldIsStatic = field.isStatic();
        field.accept(this);
        Attribute[] attributes = field.getAttributes();
        for (Attribute attribute : attributes) {
            attribute.accept(this);
        }
    } finally {
        visitingField = false;
        this.field = null;
        this.thisFieldInfo = null;
    }
}
 
Example 4
Source Project: commons-bcel   Source File: MethodHTML.java    License: Apache License 2.0 6 votes vote down vote up
MethodHTML(final String dir, final String class_name, final Method[] methods, final Field[] fields,
        final ConstantHTML constant_html, final AttributeHTML attribute_html) throws IOException {
    this.className = class_name;
    this.attribute_html = attribute_html;
    this.constantHtml = constant_html;
    file = new PrintWriter(new FileOutputStream(dir + class_name + "_methods.html"));
    file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\"><TABLE BORDER=0>");
    file.println("<TR><TH ALIGN=LEFT>Access&nbsp;flags</TH><TH ALIGN=LEFT>Type</TH>"
            + "<TH ALIGN=LEFT>Field&nbsp;name</TH></TR>");
    for (final Field field : fields) {
        writeField(field);
    }
    file.println("</TABLE>");
    file.println("<TABLE BORDER=0><TR><TH ALIGN=LEFT>Access&nbsp;flags</TH>"
            + "<TH ALIGN=LEFT>Return&nbsp;type</TH><TH ALIGN=LEFT>Method&nbsp;name</TH>"
            + "<TH ALIGN=LEFT>Arguments</TH></TR>");
    for (int i = 0; i < methods.length; i++) {
        writeMethod(methods[i], i);
    }
    file.println("</TABLE></BODY></HTML>");
    file.close();
}
 
Example 5
Source Project: spotbugs   Source File: Naming.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field obj) {
    if (getFieldName().length() == 1) {
        return;
    }

    if (isEclipseNLS) {
        int flags = obj.getAccessFlags();
        if ((flags & Const.ACC_STATIC) != 0 && ((flags & Const.ACC_PUBLIC) != 0) && "Ljava/lang/String;".equals(getFieldSig())) {
            // ignore "public statis String InstallIUCommandTooltip;"
            // messages from Eclipse NLS bundles
            return;
        }
    }
    if (badFieldName(obj)) {
        bugReporter.reportBug(new BugInstance(this, "NM_FIELD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadFieldNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClass(this).addVisitedField(this));
    }
}
 
Example 6
@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 7
Source Project: spotbugs   Source File: Hierarchy.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Find a field with given name defined in given class.
 *
 * @param className
 *            the name of the class
 * @param fieldName
 *            the name of the field
 * @return the Field, or null if no such field could be found
 */
public static Field findField(String className, String fieldName) throws ClassNotFoundException {
    JavaClass jclass = Repository.lookupClass(className);

    while (jclass != null) {
        Field[] fieldList = jclass.getFields();
        for (Field field : fieldList) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }

        jclass = jclass.getSuperClass();
    }

    return null;
}
 
Example 8
Source Project: spotbugs   Source File: Subtypes2.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isJSP(JavaClass javaClass) {
    @DottedClassName
    String className = javaClass.getClassName();
    if (className.endsWith("_jsp") || className.endsWith("_tag")) {
        return true;
    }
    for (Method m : javaClass.getMethods()) {
        if (m.getName().startsWith("_jsp")) {
            return true;
        }
    }

    for (Field f : javaClass.getFields()) {
        if (f.getName().startsWith("_jsp")) {
            return true;
        }
    }
    return Subtypes2.instanceOf(className, "javax.servlet.jsp.JspPage")
            || Subtypes2.instanceOf(className, "org.apache.jasper.runtime.HttpJspBase")
            || Subtypes2.instanceOf(className, "javax.servlet.jsp.tagext.SimpleTagSupport")
            || Subtypes2.instanceOf(className, " org.apache.jasper.runtime.JspSourceDependent");
}
 
Example 9
Source Project: commons-bcel   Source File: MethodHTML.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Print field of class.
 *
 * @param field field to print
 * @throws java.io.IOException
 */
private void writeField( final Field field ) throws IOException {
    final String type = Utility.signatureToString(field.getSignature());
    final String name = field.getName();
    String access = Utility.accessToString(field.getAccessFlags());
    Attribute[] attributes;
    access = Utility.replace(access, " ", "&nbsp;");
    file.print("<TR><TD><FONT COLOR=\"#FF0000\">" + access + "</FONT></TD>\n<TD>"
            + Class2HTML.referenceType(type) + "</TD><TD><A NAME=\"field" + name + "\">" + name
            + "</A></TD>");
    attributes = field.getAttributes();
    // Write them to the Attributes.html file with anchor "<name>[<i>]"
    for (int i = 0; i < attributes.length; i++) {
        attribute_html.writeAttribute(attributes[i], name + "@" + i);
    }
    for (int i = 0; i < attributes.length; i++) {
        if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // Default value
            final String str = ((ConstantValue) attributes[i]).toString();
            // Reference attribute in _attributes.html
            file.print("<TD>= <A HREF=\"" + className + "_attributes.html#" + name + "@" + i
                    + "\" TARGET=\"Attributes\">" + str + "</TD>\n");
            break;
        }
    }
    file.println("</TR>");
}
 
Example 10
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClasses)
{
    final Iterator it = aJavaClasses.iterator();
    while (it.hasNext()) {
        final JavaClass javaClass = (JavaClass) it.next();
        final String className = javaClass.getClassName();
        final JavaClassDefinition classDef = findJavaClassDef(javaClass);
        final FieldDefinition[] fieldDefs = classDef.getFieldDefs();
        for (int i = 0; i < fieldDefs.length; i++) {
            if (fieldDefs[i].getReadReferenceCount() == 0) {
                final Field field = fieldDefs[i].getField();
                if (!field.isFinal()
                    && (!ignore(className, field))
                    )
                {
                    log(
                        javaClass,
                        0,
                        "unread.field",
                        new Object[] {fieldDefs[i]});
                }
            }
        }
    }
}
 
Example 11
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClasses)
{
    final Iterator it = aJavaClasses.iterator();
    while (it.hasNext()) {
        final JavaClass javaClass = (JavaClass) it.next();
        final String className = javaClass.getClassName();
        final JavaClassDefinition classDef = findJavaClassDef(javaClass);
        final FieldDefinition[] fieldDefs = classDef.getFieldDefs();
        for (int i = 0; i < fieldDefs.length; i++) {
            if (fieldDefs[i].getReadReferenceCount() == 0) {
                final Field field = fieldDefs[i].getField();
                if (!field.isFinal()
                    && (!ignore(className, field))
                    )
                {
                    log(
                        javaClass,
                        0,
                        "unread.field",
                        new Object[] {fieldDefs[i]});
                }
            }
        }
    }
}
 
Example 12
Source Project: google-http-java-client   Source File: BetaDetector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reports bug in case the field defined by the given name is {@link Beta}.
 *
 * <p>The field is searched in current class and all super classses as well.
 */
private void checkField(String fieldName) {
  JavaClass javaClass = checkClass();
  if (javaClass == null) {
    return;
  }

  for (JavaClass current = javaClass; current != null; current = getSuperclass(current)) {
    for (Field field : current.getFields()) {
      if (fieldName.equals(field.getName())) {
        // field has been found - check if it's beta
        if (isBeta(field.getAnnotationEntries())) {
          bugReporter.reportBug(createBugInstance(BETA_FIELD_USAGE).addReferencedField(this));
        }
        return;
      }
    }
  }
  bugReporter.logError("Can't locate field " + javaClass.getClassName() + "." + fieldName);
}
 
Example 13
Source Project: j-j-jvm   Source File: GenerateStubDialog.java    License: 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 14
Source Project: j-j-jvm   Source File: GenerateStubDialog.java    License: 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 15
Source Project: commons-bcel   Source File: id.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example 16
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Processes information about the fields of the class, i.e., its variables.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processFields () throws IOException, ClassFormatException {
    int fields_count;
    fields_count = file.readUnsignedShort();
    fields = new Field[fields_count];

    // sometimes fields[0] is magic used for serialization
    System.out.printf("%nFields(%d):%n", fields_count);

    for (int i = 0; i < fields_count; i++) {
        processFieldOrMethod();
        if (i < fields_count - 1) {
            System.out.println();
        }
    }
}
 
Example 17
Source Project: commons-bcel   Source File: FieldGen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate from existing field.
 *
 * @param field Field object
 * @param cp constant pool (must contain the same entries as the field's constant pool)
 */
public FieldGen(final Field field, final ConstantPoolGen cp) {
    this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
    final Attribute[] attrs = field.getAttributes();
    for (final Attribute attr : attrs) {
        if (attr instanceof ConstantValue) {
            setValue(((ConstantValue) attr).getConstantValueIndex());
        } else if (attr instanceof Annotations) {
            final Annotations runtimeAnnotations = (Annotations)attr;
            final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();
            for (final AnnotationEntry element : annotationEntries) {
                addAnnotationEntry(new AnnotationEntryGen(element,cp,false));
            }
        } else {
            addAttribute(attr);
        }
    }
}
 
Example 18
Source Project: commons-bcel   Source File: ClassGen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return the (finally) built up Java class object.
 */
public JavaClass getJavaClass() {
    final int[] interfaces = getInterfaces();
    final Field[] fields = getFields();
    final Method[] methods = getMethods();
    Attribute[] attributes = null;
    if (annotationList.isEmpty()) {
        attributes = getAttributes();
    } else {
        // TODO: Sometime later, trash any attributes called 'RuntimeVisibleAnnotations' or 'RuntimeInvisibleAnnotations'
        final Attribute[] annAttributes  = AnnotationEntryGen.getAnnotationAttributes(cp, getAnnotationEntries());
        attributes = new Attribute[attributeList.size()+annAttributes.length];
        attributeList.toArray(attributes);
        System.arraycopy(annAttributes,0,attributes,attributeList.size(),annAttributes.length);
    }
    // Must be last since the above calls may still add something to it
    final ConstantPool _cp = this.cp.getFinalConstantPool();
    return new JavaClass(classNameIndex, superclass_name_index, fileName, major, minor,
            super.getAccessFlags(), _cp, interfaces, fields, methods, attributes);
}
 
Example 19
Source Project: JQF   Source File: JavaClassGenerator.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Field generateField(SourceOfRandomness r) {
    int flags = r.nextInt(0, Short.MAX_VALUE);
    Type type = generateType(r, true);
    String name = generateMemberName(r);
    FieldGen fieldGen = new FieldGen(flags, type, name, constants);
    return fieldGen.getField();
}
 
Example 20
/** If currently visiting a field, get the field's Field object */
public Field getField() {
    if (!visitingField) {
        throw new IllegalStateException("getField called while not visiting field");
    }
    return field;
}
 
Example 21
@Override
public void visit(Field obj) {
    super.visit(obj);
    FieldAnnotation f = FieldAnnotation.fromVisitedField(this);
    declaredFields.add(f);

}
 
Example 22
@Override
public void visit(JavaClass obj) {

    if (Subtypes2.instanceOf(obj, "java.util.Comparator") && !ClassName.isLocalOrAnonymous(getClassName())
            && !Subtypes2.instanceOf(obj, "java.io.Serializable")) {
        int priority = NORMAL_PRIORITY;
        if (obj.isInterface() || obj.isAbstract()) {
            return;
        }

        double easilySerializable = 1.0;
        for (Field f : obj.getFields()) {
            try {
                if (f.getName().startsWith("this$")) {
                    return;
                }
                String signature = f.getSignature();
                char firstChar = signature.charAt(0);
                if (firstChar == 'L' || firstChar == '[') {
                    easilySerializable *= DeepSubtypeAnalysis.isDeepSerializable(signature);
                }
            } catch (ClassNotFoundException e) {
                easilySerializable = 0.0;
                break;
            }
        }

        if (easilySerializable < 0.9) {
            priority = LOW_PRIORITY;
        }

        bugReporter.reportBug(new BugInstance(this, "SE_COMPARATOR_SHOULD_BE_SERIALIZABLE", priority).addClass(this));

    }

}
 
Example 23
Source Project: spotbugs   Source File: Naming.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static @CheckForNull String getSignatureOfOuterClass(JavaClass obj) {
    for (Field f : obj.getFields()) {
        if (f.getName().startsWith("this$")) {
            return f.getSignature();
        }
    }
    return null;
}
 
Example 24
@Override
public void visit(Field obj) {
    super.visit(obj);
    XField f = XFactory.createXField(this);
    if (checkForInitialization(f) && !f.isSynthetic()) {
        if (f.isStatic()) {
            nonnullStaticFields.add(f);
        } else {
            nonnullFields.add(f);
        }
    }
}
 
Example 25
@Override
public void visit(LocalVariableTable obj) {
    if (ENABLE_LOCALS) {
        if (staticMethod) {
            return;
        }

        LocalVariable[] vars = obj.getLocalVariableTable();
        // System.out.println("Num params = " + numParms);
        for (LocalVariable var : vars) {
            if (var.getIndex() < numParms) {
                continue;
            }
            String varName = var.getName();
            if ("serialVersionUID".equals(varName)) {
                continue;
            }
            Field f = classFields.get(varName);
            // System.out.println("Checking " + varName);
            // System.out.println(" got " + f);
            // TODO: we could distinguish between obscuring a field in the
            // same class
            // vs. obscuring a field in a superclass. Not sure how important
            // that is.
            if (f != null) {
                FieldAnnotation fa = FieldAnnotation.fromBCELField(getDottedClassName(), f);
                if (true || var.getStartPC() > 0) {
                    bugReporter.reportBug(new BugInstance(this, "MF_METHOD_MASKS_FIELD", LOW_PRIORITY)
                            .addClassAndMethod(this).addField(fa).addSourceLine(this, var.getStartPC() - 1));
                }
            }
        }
    }
    super.visit(obj);
}
 
Example 26
Source Project: spotbugs   Source File: MutableLock.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Field obj) {
    super.visit(obj);
    if (obj.isFinal()) {
        finalFields.add(obj.getName());
    }
}
 
Example 27
@Override
public void visit(Field obj) {
    int accessFlags = obj.getAccessFlags();
    if ((accessFlags & Const.ACC_STATIC) != 0) {
        return;
    }
    if (!obj.getName().startsWith("this$") && !BCELUtil.isSynthetic(obj) && !obj.isTransient()) {
        hasFields = true;
    }
}
 
Example 28
@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 29
@Override
public void visit(Field obj) {
    if (!obj.isFinal() && !obj.isTransient() && !obj.isVolatile()) {
        bugReporter.reportBug(new BugInstance(this, "JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS", NORMAL_PRIORITY).addClass(
                this).addVisitedField(this));
    }
}
 
Example 30
@Override
public void visitField(Field obj) {
    if (obj.isProtected()) {
        bugReporter.reportBug(new BugInstance(this, "CI_CONFUSED_INHERITANCE", LOW_PRIORITY).addClass(cls).addField(
                new FieldAnnotation(cls.getClassName(), obj.getName(), obj.getSignature(), obj.isStatic())));
    }
}