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

The following examples show how to use org.apache.bcel.classfile.Attribute. 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
Source Project: spotbugs   Source File: Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Determine the outer class of obj.
 *
 * @param obj
 * @return JavaClass for outer class, or null if obj is not an outer class
 * @throws ClassNotFoundException
 */

@CheckForNull
public static JavaClass getOuterClass(JavaClass obj) throws ClassNotFoundException {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof InnerClasses) {
            for (InnerClass ic : ((InnerClasses) a).getInnerClasses()) {
                if (obj.getClassNameIndex() == ic.getInnerClassIndex()) {
                    // System.out.println("Outer class is " +
                    // ic.getOuterClassIndex());
                    ConstantClass oc = (ConstantClass) obj.getConstantPool().getConstant(ic.getOuterClassIndex());
                    String ocName = oc.getBytes(obj.getConstantPool());
                    return Repository.lookupClass(ocName);
                }
            }
        }
    }
    return null;
}
 
Example 2
Source Project: spotbugs   Source File: Naming.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean markedAsNotUsable(Method obj) {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof Deprecated) {
            return true;
        }
    }
    Code code = obj.getCode();
    if (code == null) {
        return false;
    }
    byte[] codeBytes = code.getCode();
    if (codeBytes.length > 1 && codeBytes.length < 10) {
        int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff;
        if (lastOpcode != Const.ATHROW) {
            return false;
        }
        for (int b : codeBytes) {
            if ((b & 0xff) == Const.RETURN) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 3
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Processes information about the attributes of the class.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processAttributes () throws IOException, ClassFormatException {
    int attributes_count;
    attributes_count = file.readUnsignedShort();
    attributes = new Attribute[attributes_count];

    System.out.printf("%nAttributes(%d):%n", attributes_count);

    for (int i = 0; i < attributes_count; i++) {
        attributes[i] = Attribute.readAttribute(file, constant_pool);
        // indent all lines by two spaces
        final String[] lines = attributes[i].toString().split("\\r?\\n");
        for (final String line : lines) {
            System.out.println("  " + line);
        }
    }
}
 
Example 4
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 5
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return string representation close to declaration format,
 * `public static void main(String[]) throws IOException', e.g.
 *
 * @return String representation of the method.
 */
@Override
public final String toString() {
    final String access = Utility.accessToString(super.getAccessFlags());
    String signature = Type.getMethodSignature(super.getType(), argTypes);
    signature = Utility.methodSignatureToString(signature, super.getName(), access, true,
            getLocalVariableTable(super.getConstantPool()));
    final StringBuilder buf = new StringBuilder(signature);
    for (final Attribute a : getAttributes()) {
        if (!((a instanceof Code) || (a instanceof ExceptionTable))) {
            buf.append(" [").append(a).append("]");
        }
    }

    if (throwsList.size() > 0) {
        for (final String throwsDescriptor : throwsList) {
            buf.append("\n\t\tthrows ").append(throwsDescriptor);
        }
    }
    return buf.toString();
}
 
Example 6
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 7
Source Project: commons-bcel   Source File: Class2HTML.java    License: Apache License 2.0 6 votes vote down vote up
private void writeMainHTML( final AttributeHTML attribute_html ) throws IOException {
    try (PrintWriter file = new PrintWriter(new FileOutputStream(dir + class_name + ".html"))) {
        file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + class_name + "</TITLE>" + "</HEAD>\n"
                + "<FRAMESET BORDER=1 cols=\"30%,*\">\n" + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
                + "<FRAME NAME=\"ConstantPool\" SRC=\"" + class_name + "_cp.html" + "\"\n MARGINWIDTH=\"0\" "
                + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Attributes\" SRC=\""
                + class_name + "_attributes.html" + "\"\n MARGINWIDTH=\"0\" "
                + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "</FRAMESET>\n"
                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"Code\" SRC=\"" + class_name
                + "_code.html\"\n MARGINWIDTH=0 " + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
                + "<FRAME NAME=\"Methods\" SRC=\"" + class_name + "_methods.html\"\n MARGINWIDTH=0 "
                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "</FRAMESET></FRAMESET></HTML>");
    }
    final Attribute[] attributes = java_class.getAttributes();
    for (int i = 0; i < attributes.length; i++) {
        attribute_html.writeAttribute(attributes[i], "class" + i);
    }
}
 
Example 8
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 9
/**
 * Verify for an inner class declared inside the 'main' method that the
 * enclosing method attribute is set correctly.
 */
public void testCheckMethodLevelNamedInnerClass()
        throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");
    final ConstantPool pool = clazz.getConstantPool();
    final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
    assertTrue("Expected 1 EnclosingMethod attribute but found "
            + encMethodAttrs.length, encMethodAttrs.length == 1);
    final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
    final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
    final String enclosingMethodName = em.getEnclosingMethod().getName(pool);
    assertTrue(
            "Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "
                    + enclosingClassName, enclosingClassName
                    .equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));
    assertTrue("Expected method name to be 'main' but was "
            + enclosingMethodName, enclosingMethodName.equals("main"));
}
 
Example 10
/**
 * Verify for an inner class declared at the type level that the
 * EnclosingMethod attribute is set correctly (i.e. to a null value)
 */
public void testCheckClassLevelNamedInnerClass()
        throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1");
    final ConstantPool pool = clazz.getConstantPool();
    final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
    assertTrue("Expected 1 EnclosingMethod attribute but found "
            + encMethodAttrs.length, encMethodAttrs.length == 1);
    final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
    final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
    assertTrue(
            "The class is not within a method, so method_index should be null, but it is "
                    + em.getEnclosingMethodIndex(), em
                    .getEnclosingMethodIndex() == 0);
    assertTrue(
            "Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM02' but was "
                    + enclosingClassName, enclosingClassName
                    .equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM02"));
}
 
Example 11
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
static ImmutableSet<String> listInnerClassNames(JavaClass javaClass) {
  ImmutableSet.Builder<String> innerClassNames = ImmutableSet.builder();
  String topLevelClassName = javaClass.getClassName();
  ConstantPool constantPool = javaClass.getConstantPool();
  for (Attribute attribute : javaClass.getAttributes()) {
    if (attribute.getTag() == Const.ATTR_INNER_CLASSES) {
      // This innerClasses variable does not include double-nested inner classes
      InnerClasses innerClasses = (InnerClasses) attribute;
      for (InnerClass innerClass : innerClasses.getInnerClasses()) {
        int classIndex = innerClass.getInnerClassIndex();
        String innerClassName = constantPool.getConstantString(classIndex, Const.CONSTANT_Class);
        int outerClassIndex = innerClass.getOuterClassIndex();
        if (outerClassIndex > 0) {
          String outerClassName =
              constantPool.getConstantString(outerClassIndex, Const.CONSTANT_Class);
          String normalOuterClassName = outerClassName.replace('/', '.');
          if (!normalOuterClassName.equals(topLevelClassName)) {
            continue;
          }
        }

        // Class names stored in constant pool have '/' as separator. We want '.' (as binary name)
        String normalInnerClassName = innerClassName.replace('/', '.');
        innerClassNames.add(normalInnerClassName);
      }
    }
  }
  return innerClassNames.build();
}
 
Example 12
@Override
public void visitCode(Code obj) {
    code = obj;
    super.visitCode(obj);
    CodeException[] exceptions = obj.getExceptionTable();
    for (CodeException exception : exceptions) {
        exception.accept(this);
    }
    Attribute[] attributes = obj.getAttributes();
    for (Attribute attribute : attributes) {
        attribute.accept(this);
    }
    visitAfter(obj);
    code = null;
}
 
Example 13
Source Project: spotbugs   Source File: DumbMethods.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    String superclassName = obj.getSuperclassName();
    isSynthetic = "java.rmi.server.RemoteStub".equals(superclassName);
    Attribute[] attributes = obj.getAttributes();
    if (attributes != null) {
        for (Attribute a : attributes) {
            if (a instanceof Synthetic) {
                isSynthetic = true;
            }
        }
    }

}
 
Example 14
boolean isSynthetic(FieldOrMethod obj) {
    Attribute[] a = obj.getAttributes();
    for (Attribute aA : a) {
        if (aA instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source Project: spotbugs   Source File: UnreadFields.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean classHasParameter(JavaClass obj) {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof Signature) {
            String sig = ((Signature) a).getSignature();
            return sig.charAt(0) == '<';
        }
    }
    return false;
}
 
Example 16
/**
 * Methods marked with the "Synthetic" attribute do not appear in the source
 * code
 */
private boolean isSynthetic(Method m) {
    if ((m.getAccessFlags() & Const.ACC_SYNTHETIC) != 0) {
        return true;
    }
    Attribute[] attrs = m.getAttributes();
    for (Attribute attr : attrs) {
        if (attr instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 17
Source Project: spotbugs   Source File: BCELUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks if the given member is synthetic
 *
 * @param m The member to be checked
 * @return True if the member is synthetic, false otherwise
 * @deprecated You probably don't care for synthetic members, but want to
 *             know if the developer added it (think of lambdas), use
 *             {@link MemberUtils#isUserGenerated(FieldOrMethod)} instead
 */
@Deprecated
public static boolean isSynthetic(FieldOrMethod m) {
    if (m.isSynthetic()) {
        return true;
    }

    for (Attribute a : m.getAttributes()) {
        if (a instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 18
Source Project: spotbugs   Source File: BCELUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean isSynthetic(JavaClass j) {
    if (j.isSynthetic()) {
        return true;
    }

    for (Attribute a : j.getAttributes()) {
        if (a instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 19
Source Project: spotbugs   Source File: BCELUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean isSynthetic(FieldGenOrMethodGen m) {
    if (m.isSynthetic()) {
        return true;
    }
    for (Attribute a : m.getAttributes()) {
        if (a instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 20
/**
 * @param target
 *            the method whose signature is to be parsed
 * @return an iterator over the parameters of the generic signature of
 *         method. Returns null if the generic signature cannot be parsed
 */
public static @CheckForNull Iterator<String> getGenericSignatureIterator(Method target) {
    try {
        GenericSignatureParser parser = null;
        String genericSignature = null;
        for (Attribute a : target.getAttributes()) {
            if (a instanceof Signature) {

                Signature sig = (Signature) a;
                if (genericSignature != null) {
                    if (!genericSignature.equals(sig.getSignature())) {
                        // we've seen two inconsistent signatures
                        return null;
                    }
                    continue;
                }

                genericSignature = sig.getSignature();
                if (compareSignatures(target.getSignature(), genericSignature)) {
                    parser = new GenericSignatureParser(genericSignature);
                }
            }
        }
        Iterator<String> iter = parser == null ? null : parser.parameterSignatureIterator();
        return iter;
    } catch (RuntimeException e) {
    } // degrade gracefully
    return null;
}
 
Example 21
Source Project: spotbugs   Source File: TypeAnalysis.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param method
 *            TODO
 * @param methodGen
 *            the MethodGen whose CFG we'll be analyzing
 * @param cfg
 *            the control flow graph
 * @param dfs
 *            DepthFirstSearch of the method
 * @param typeMerger
 *            object to merge types
 * @param visitor
 *            a TypeFrameModelingVisitor to use to model the effect of
 *            instructions
 * @param lookupFailureCallback
 *            lookup failure callback
 * @param exceptionSetFactory
 *            factory for creating ExceptionSet objects
 */
public TypeAnalysis(Method method, MethodGen methodGen, CFG cfg, DepthFirstSearch dfs, TypeMerger typeMerger,
        TypeFrameModelingVisitor visitor, RepositoryLookupFailureCallback lookupFailureCallback,
        ExceptionSetFactory exceptionSetFactory) {
    super(dfs);
    this.method = method;
    Code code = method.getCode();
    if (code == null) {
        throw new IllegalArgumentException(method.getName() + " has no code");
    }
    for (Attribute a : code.getAttributes()) {
        if (a instanceof LocalVariableTypeTable) {
            visitor.setLocalTypeTable((LocalVariableTypeTable) a);
        }
    }
    this.methodGen = methodGen;
    this.cfg = cfg;
    this.typeMerger = typeMerger;
    this.visitor = visitor;
    this.thrownExceptionSetMap = new HashMap<>();
    this.lookupFailureCallback = lookupFailureCallback;
    this.exceptionSetFactory = exceptionSetFactory;
    this.instanceOfCheckMap = new HashMap<>();
    if (DEBUG) {
        System.out.println("\n\nAnalyzing " + methodGen);
    }
}
 
Example 22
static @CheckForNull StackMap getStackMapTable(Code code) {
    for (Attribute a : code.getAttributes()) {
        if (a instanceof StackMap) {
            return (StackMap) a;
        }
    }
    return null;
}
 
Example 23
Source Project: spotbugs   Source File: MemberUtils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean internalIsSynthetic(final FieldOrMethod m) {
    if (m.isSynthetic()) {
        return true;
    }

    for (final Attribute a : m.getAttributes()) {
        if (a instanceof Synthetic) {
            return true;
        }
    }

    return false;
}
 
Example 24
Source Project: spotbugs   Source File: MemberUtils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean internalIsSynthetic(final FieldGenOrMethodGen m) {
    if (m.isSynthetic()) {
        return true;
    }

    for (final Attribute a : m.getAttributes()) {
        if (a instanceof Synthetic) {
            return true;
        }
    }

    return false;
}
 
Example 25
Source Project: commons-bcel   Source File: JasminVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unfortunately Jasmin expects ".end method" after each method. Thus we've to check
 * for every of the method's attributes if it's the last one and print ".end method"
 * then.
 */
private void printEndMethod(final Attribute attr) {
    final Attribute[] attributes = _method.getAttributes();

    if (attr == attributes[attributes.length - 1]) {
        out.println(".end method");
    }
}
 
Example 26
Source Project: commons-bcel   Source File: JasminVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(final Method method) {
    this._method = method; // Remember for use in subsequent visitXXX calls

    out.println("\n.method " + Utility.accessToString(_method.getAccessFlags()) +
            " " + _method.getName() + _method.getSignature());

    final Attribute[] attributes = _method.getAttributes();
    if ((attributes == null) || (attributes.length == 0)) {
        out.println(".end method");
    }
}
 
Example 27
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @since 6.0
 */
public void addAnnotationsAsAttribute(final ConstantPoolGen cp) {
    final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries());
    for (final Attribute attr : attrs) {
        addAttribute(attr);
    }
}
 
Example 28
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @since 6.0
 */
public void addParameterAnnotationsAsAttribute(final ConstantPoolGen cp) {
    if (!hasParameterAnnotations) {
        return;
    }
    final Attribute[] attrs = AnnotationEntryGen.getParameterAnnotationAttributes(cp, paramAnnotations);
    if (attrs != null) {
        for (final Attribute attr : attrs) {
            addAttribute(attr);
        }
    }
}
 
Example 29
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
private Attribute[] addRuntimeAnnotationsAsAttribute(final ConstantPoolGen cp) {
    final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries());
    for (final Attribute attr : attrs) {
        addAttribute(attr);
    }
    return attrs;
}
 
Example 30
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
private Attribute[] addRuntimeParameterAnnotationsAsAttribute(final ConstantPoolGen cp) {
    if (!hasParameterAnnotations) {
        return new Attribute[0];
    }
    final Attribute[] attrs = AnnotationEntryGen.getParameterAnnotationAttributes(cp, paramAnnotations);
    for (final Attribute attr : attrs) {
        addAttribute(attr);
    }
    return attrs;
}