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

The following examples show how to use org.apache.bcel.classfile.ClassFormatException. 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
static StackFrameType get(int frame_type) {
    if (frame_type >= Const.SAME_FRAME && frame_type <= Const.SAME_FRAME_MAX) {
        return SAME_FRAME;
    } else if (frame_type >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME
            && frame_type <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_MAX) {
        return SAME_LOCALS_1_STACK_ITEM_FRAME;
    } else if (frame_type == Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
        return SAME_LOCALS_1_STACK_ITEM_FRAME;
    } else if (frame_type >= Const.CHOP_FRAME && frame_type <= Const.CHOP_FRAME_MAX) {
        return CHOP_FRAME;
    } else if (frame_type == Const.SAME_FRAME_EXTENDED) {
        return SAME_FRAME;
    } else if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) {
        return APPEND_FRAME;
    } else if (frame_type == Const.FULL_FRAME) {
        return FULL_FRAME;
    } else {
        /* Can't happen */
        throw new ClassFormatException("Invalid frame type : " + frame_type);
    }
}
 
Example 2
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Processes information about the interfaces implemented by this class.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processInterfaces () throws IOException, ClassFormatException {
    int interfaces_count;
    interfaces_count = file.readUnsignedShort();
    interfaces = new int[interfaces_count];

    System.out.printf("%nInterfaces(%d):%n", interfaces_count);

    for (int i = 0; i < interfaces_count; i++) {
        interfaces[i] = file.readUnsignedShort();
        // i'm sure there is a better way to do this
        if (i < 10) {
            System.out.printf("   #%1d = ", i);
        } else if (i <100) {
            System.out.printf("  #%2d = ", i);
        } else {
            System.out.printf(" #%d = ", i);
        }
        System.out.println(interfaces[i] + " (" +
                constant_pool.getConstantString(interfaces[i],
                        Const.CONSTANT_Class) + ")");
    }
}
 
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 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 4
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 5
Source Project: commons-bcel   Source File: Type.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert arguments of a method (signature) to an array of Type objects.
 * @param signature signature string such as (Ljava/lang/String;)V
 * @return array of argument types
 */
public static Type[] getArgumentTypes( final String signature ) {
    final List<Type> vec = new ArrayList<>();
    int index;
    Type[] types;
    try {
        // Skip any type arguments to read argument declarations between `(' and `)'
        index = signature.indexOf('(') + 1;
        if (index <= 0) {
            throw new ClassFormatException("Invalid method signature: " + signature);
        }
        while (signature.charAt(index) != ')') {
            vec.add(getType(signature.substring(index)));
            //corrected concurrent private static field acess
            index += unwrap(consumed_chars); // update position
        }
    } catch (final StringIndexOutOfBoundsException e) { // Should never occur
        throw new ClassFormatException("Invalid method signature: " + signature, e);
    }
    types = new Type[vec.size()];
    vec.toArray(types);
    return types;
}
 
Example 6
Source Project: commons-bcel   Source File: Type.java    License: Apache License 2.0 6 votes vote down vote up
static int getArgumentTypesSize( final String signature ) {
    int res = 0;
    int index;
    try {
        // Skip any type arguments to read argument declarations between `(' and `)'
        index = signature.indexOf('(') + 1;
        if (index <= 0) {
            throw new ClassFormatException("Invalid method signature: " + signature);
        }
        while (signature.charAt(index) != ')') {
            final int coded = getTypeSize(signature.substring(index));
            res += size(coded);
            index += consumed(coded);
        }
    } catch (final StringIndexOutOfBoundsException e) { // Should never occur
        throw new ClassFormatException("Invalid method signature: " + signature, e);
    }
    return res;
}
 
Example 7
Source Project: commons-bcel   Source File: Type.java    License: Apache License 2.0 6 votes vote down vote up
static int getTypeSize( final String signature ) throws StringIndexOutOfBoundsException {
    final byte type = Utility.typeOfSignature(signature);
    if (type <= Const.T_VOID) {
        return encode(BasicType.getType(type).getSize(), 1);
    } else if (type == Const.T_ARRAY) {
        int dim = 0;
        do { // Count dimensions
            dim++;
        } while (signature.charAt(dim) == '[');
        // Recurse, but just once, if the signature is ok
        final int consumed = consumed(getTypeSize(signature.substring(dim)));
        return encode(1, dim + consumed);
    } else { // type == T_REFERENCE
        final int index = signature.indexOf(';'); // Look for closing `;'
        if (index < 0) {
            throw new ClassFormatException("Invalid signature: " + signature);
        }
        return encode(1, index + 1);
    }
}
 
Example 8
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
private static ConstantNameAndType constantNameAndType(
    ConstantCP constantCP, ConstantPool constantPool) {
  int nameAndTypeIndex = constantCP.getNameAndTypeIndex();
  Constant constantAtNameAndTypeIndex = constantPool.getConstant(nameAndTypeIndex);
  if (!(constantAtNameAndTypeIndex instanceof ConstantNameAndType)) {
    // This constant_pool entry must be a CONSTANT_NameAndType_info
    // as specified https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.2
    throw new ClassFormatException(
        "Failed to lookup nameAndType constant indexed at "
            + nameAndTypeIndex
            + ". However, the content is not ConstantNameAndType. It is "
            + constantAtNameAndTypeIndex);
  }
  return (ConstantNameAndType) constantAtNameAndTypeIndex;
}
 
Example 9
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
private static ClassSymbol makeSymbol(
    ConstantClass constantClass, ConstantPool constantPool, JavaClass sourceClass) {
  int nameIndex = constantClass.getNameIndex();
  Constant classNameConstant = constantPool.getConstant(nameIndex);
  if (!(classNameConstant instanceof ConstantUtf8)) {
    // This constant_pool entry must be a CONSTANT_Utf8_info
    // as specified https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.1
    throw new ClassFormatException(
        "Failed to lookup ConstantUtf8 constant indexed at "
            + nameIndex
            + ". However, the content is not ConstantUtf8. It is "
            + classNameConstant);
  }
  ConstantUtf8 classNameConstantUtf8 = (ConstantUtf8) classNameConstant;
  // classNameConstantUtf8 has internal form of class names that uses '.' to separate identifiers
  String targetClassNameInternalForm = classNameConstantUtf8.getBytes();
  // Adjust the internal form to comply with binary names defined in JLS 13.1
  String targetClassName = targetClassNameInternalForm.replace('/', '.');
  String superClassName = sourceClass.getSuperclassName();

  // Relationships between superclass and subclass need special validation for 'final' keyword
  boolean referenceIsForInheritance = superClassName.equals(targetClassName);
  if (referenceIsForInheritance) {
    return new SuperClassSymbol(targetClassName);
  }
  return new ClassSymbol(targetClassName);
}
 
Example 10
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of {@link JavaClass}es which have entries in the {@code entry} through {@link
 * #classRepository}.
 */
private ImmutableSet<JavaClass> listClasses(ClassPathEntry entry) throws IOException {
  ImmutableSet.Builder<JavaClass> javaClasses = ImmutableSet.builder();

  ImmutableList.Builder<String> corruptedClassFileNames = ImmutableList.builder();

  for (String classFileName : entry.getFileNames()) {
    if (classFileName.startsWith("META-INF.versions.")) {
      // Linkage Checker does not support multi-release JAR (for Java 9+) yet
      // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/897
      continue;
    }

    try {
      JavaClass javaClass = classRepository.loadClass(classFileName);
      javaClasses.add(javaClass);
    } catch (ClassNotFoundException | ClassFormatException ex) {
      // We couldn't read the class in the JAR file where we found it.
      corruptedClassFileNames.add(classFileName);
    }
  }

  ImmutableList<String> corruptedFiles = corruptedClassFileNames.build();
  int corruptedFileCount = corruptedFiles.size();
  if (corruptedFileCount > 0) {
    logger.warning(
        "Corrupt files in "
            + entry
            + "; could not load "
            + corruptedFiles.get(0)
            + (corruptedFileCount > 1
                ? " and other " + (corruptedFileCount - 1) + " files"
                : ""));
  }
  return javaClasses.build();
}
 
Example 11
Source Project: JQF   Source File: ParserTest.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithInputStream(InputStream inputStream) throws IOException {
    JavaClass clazz;
    try {
        clazz = new ClassParser(inputStream, "Hello.class").parse();
    } catch (ClassFormatException e) {
        // ClassFormatException thrown by the parser is just invalid input
        Assume.assumeNoException(e);
        return;
    }

    // Any non-IOException thrown here should be marked a failure
    // (including ClassFormatException)
    verifyJavaClass(clazz);
}
 
Example 12
Source Project: JQF   Source File: ParserTest.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithGenerator(@From(JavaClassGenerator.class) JavaClass javaClass) throws IOException {

    try {
        // Dump the javaclass to a byte stream and get an input pipe
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        javaClass.dump(out);

        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        testWithInputStream(in);
    } catch (ClassFormatException e) {
        throw e;
    }
}
 
Example 13
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given Java class file and return an object that represents
 * the contained data, i.e., constants, methods, fields and commands.
 * A <em>ClassFormatException</em> is raised, if the file is not a valid
 * .class file. (This does not include verification of the byte code as it
 * is performed by the java interpreter).
 *
 * @throws  IOException
 * @throws  ClassFormatException
 */
public void dump () throws IOException, ClassFormatException {
    try {
        // Check magic tag of class file
        processID();
        // Get compiler version
        processVersion();
        // process constant pool entries
        processConstantPool();
        // Get class information
        processClassInfo();
        // Get interface information, i.e., implemented interfaces
        processInterfaces();
        // process class fields, i.e., the variables of the class
        processFields();
        // process class methods, i.e., the functions in the class
        processMethods();
        // process class attributes
        processAttributes();
    } finally {
        // Processed everything of interest, so close the file
        try {
            if (file != null) {
                file.close();
            }
        } catch (final IOException ioe) {
            //ignore close exceptions
        }
    }
}
 
Example 14
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the header of the file is ok.
 * Of course, this has to be the first action on successive file reads.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processID () throws IOException, ClassFormatException {
    final int magic = file.readInt();
    if (magic != Const.JVM_CLASSFILE_MAGIC) {
        throw new ClassFormatException(file_name + " is not a Java .class file");
    }
    System.out.println("Java Class Dump");
    System.out.println("  file: " + file_name);
    System.out.printf("%nClass header:%n");
    System.out.printf("  magic: %X%n", magic);
}
 
Example 15
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes major and minor version of compiler which created the file.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processVersion () throws IOException, ClassFormatException {
    minor = file.readUnsignedShort();
    System.out.printf("  minor version: %s%n", minor);

    major = file.readUnsignedShort();
    System.out.printf("  major version: %s%n", major);
}
 
Example 16
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes constant pool entries.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processConstantPool () throws IOException, ClassFormatException {
    byte tag;
    final int constant_pool_count = file.readUnsignedShort();
    constant_items = new Constant[constant_pool_count];
    constant_pool = new ConstantPool(constant_items);

    // constant_pool[0] is unused by the compiler
    System.out.printf("%nConstant pool(%d):%n", constant_pool_count - 1);

    for (int i = 1; i < constant_pool_count; i++) {
        constant_items[i] = Constant.readConstant(file);
        // i'm sure there is a better way to do this
        if (i < 10) {
            System.out.printf("    #%1d = ", i);
        } else if (i <100) {
            System.out.printf("   #%2d = ", i);
        } else {
            System.out.printf("  #%d = ", i);
        }
        System.out.println(constant_items[i]);

        // All eight byte constants take up two spots in the constant pool
        tag = constant_items[i].getTag();
        if ((tag == Const.CONSTANT_Double) ||
                (tag == Const.CONSTANT_Long)) {
            i++;
        }
    }
}
 
Example 17
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes information about the class and its super class.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processClassInfo () throws IOException, ClassFormatException {
    access_flags = file.readUnsignedShort();
    /* Interfaces are implicitely abstract, the flag should be set
     * according to the JVM specification.
     */
    if ((access_flags & Const.ACC_INTERFACE) != 0) {
        access_flags |= Const.ACC_ABSTRACT;
    }
    if (((access_flags & Const.ACC_ABSTRACT) != 0)
            && ((access_flags & Const.ACC_FINAL) != 0)) {
        throw new ClassFormatException("Class " + file_name +
                " can't be both final and abstract");
    }

    System.out.printf("%nClass info:%n");
    System.out.println("  flags: " + BCELifier.printFlags(access_flags,
            BCELifier.FLAGS.CLASS));
    class_name_index = file.readUnsignedShort();
    System.out.printf("  this_class: %d (", class_name_index);
    System.out.println(constantToString(class_name_index) + ")");

    superclass_name_index = file.readUnsignedShort();
    System.out.printf("  super_class: %d (", superclass_name_index);
    if (superclass_name_index > 0) {
        System.out.printf("%s", constantToString(superclass_name_index));
    }
    System.out.println(")");
}
 
Example 18
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Processes information about the methods of the class.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processMethods () throws IOException, ClassFormatException {
    int methods_count;
    methods_count = file.readUnsignedShort();
    methods = new Method[methods_count];

    System.out.printf("%nMethods(%d):%n", methods_count);

    for (int i = 0; i < methods_count; i++) {
        processFieldOrMethod();
        if (i < methods_count - 1) {
            System.out.println();
        }
    }
}
 
Example 19
Source Project: commons-bcel   Source File: Type.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert return value of a method (signature) to a Type object.
 *
 * @param signature signature string such as (Ljava/lang/String;)V
 * @return return type
 */
public static Type getReturnType( final String signature ) {
    try {
        // Read return type after `)'
        final int index = signature.lastIndexOf(')') + 1;
        return getType(signature.substring(index));
    } catch (final StringIndexOutOfBoundsException e) { // Should never occur
        throw new ClassFormatException("Invalid method signature: " + signature, e);
    }
}
 
Example 20
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantFieldref(final ConstantFieldref obj) {
    if (obj.getTag() != Const.CONSTANT_Fieldref) {
        throw new ClassConstraintException("ConstantFieldref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validFieldName(name)) {
        throw new ClassConstraintException("Invalid field name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

    final String sig  = ((ConstantUtf8) (cp.getConstant(cnat.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);
    }
}
 
Example 21
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantMethodref(final ConstantMethodref obj) {
    if (obj.getTag() != Const.CONSTANT_Methodref) {
        throw new ClassConstraintException("ConstantMethodref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validClassMethodName(name)) {
        throw new ClassConstraintException(
            "Invalid (non-interface) method name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

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

    try{
        final Type   t  = Type.getReturnType(sig);
        if ( name.equals(Const.CONSTRUCTOR_NAME) && (t != Type.VOID) ) {
            throw new ClassConstraintException("Instance initialization method must have VOID return type.");
        }
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }
}
 
Example 22
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantInterfaceMethodref(final ConstantInterfaceMethodref obj) {
    if (obj.getTag() != Const.CONSTANT_InterfaceMethodref) {
        throw new ClassConstraintException("ConstantInterfaceMethodref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validInterfaceMethodName(name)) {
        throw new ClassConstraintException("Invalid (interface) method name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

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

    try{
        final Type   t  = Type.getReturnType(sig);
        if ( name.equals(Const.STATIC_INITIALIZER_NAME) && (t != Type.VOID) ) {
            addMessage("Class or interface initialization method '"+Const.STATIC_INITIALIZER_NAME+
                "' usually has VOID return type instead of '"+t+
                "'. Note this is really not a requirement of The Java Virtual Machine Specification, Second Edition.");
        }
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }

}
 
Example 23
private void init(JavaClass jclass) {
    ConstantPool cp = jclass.getConstantPool();
    int numConstants = cp.getLength();
    for (int i = 0; i < numConstants; ++i) {
        try {
            Constant c = cp.getConstant(i);
            if (c instanceof ConstantMethodref) {
                ConstantMethodref cmr = (ConstantMethodref) c;
                ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex(),
                        Const.CONSTANT_NameAndType);
                String methodName = ((ConstantUtf8) cp.getConstant(cnat.getNameIndex(), Const.CONSTANT_Utf8)).getBytes();
                String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class).replace('/', '.');
                String methodSig = ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex(), Const.CONSTANT_Utf8)).getBytes();

                String classNameLC = className.toLowerCase();
                String methodNameLC = methodName.toLowerCase();

                boolean voidReturnType = methodSig.endsWith(")V");
                boolean boolReturnType = methodSig.endsWith(")Z");



                if (DEBUG) {
                    System.out.print("Is " + className + "." + methodName + " assertion method: " + voidReturnType);
                }

                if (isUserAssertionMethod(className, methodName)
                        || className.endsWith("Assert")
                                && methodName.startsWith("is")
                        || (voidReturnType || boolReturnType)
                                && (classNameLC.indexOf("assert") >= 0 || methodNameLC.startsWith("throw")
                                        || methodName.startsWith("affirm") || methodName.startsWith("panic")
                                        || "logTerminal".equals(methodName) || methodName.startsWith("logAndThrow")
                                        || "insist".equals(methodNameLC) || "usage".equals(methodNameLC)
                                        || "exit".equals(methodNameLC) || methodNameLC.startsWith("fail")
                                        || methodNameLC.startsWith("fatal") || methodNameLC.indexOf("assert") >= 0
                                        || methodNameLC.indexOf("legal") >= 0 || methodNameLC.indexOf("error") >= 0
                                        || methodNameLC.indexOf("abort") >= 0
                                        // || methodNameLC.indexOf("check") >= 0
                                        || methodNameLC.indexOf("failed") >= 0) || "addOrThrowException".equals(methodName)) {
                    assertionMethodRefSet.set(i);
                    if (DEBUG) {
                        System.out.println("==> YES");
                    }
                } else {
                    if (DEBUG) {
                        System.out.println("==> NO");
                    }
                }
            }
        } catch (ClassFormatException e) {
            // FIXME: should report
        }
    }
}
 
Example 24
Source Project: commons-bcel   Source File: ClassDumper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructs object from file stream.
 * @param file Input stream
 * @throws IOException
 * @throws ClassFormatException
 */
private final void processFieldOrMethod () throws IOException, ClassFormatException {
    final int access_flags = file.readUnsignedShort();
    final int name_index = file.readUnsignedShort();
    System.out.printf("  name_index: %d (", name_index);
    System.out.println(constantToString(name_index) + ")");
    System.out.println("  access_flags: " + BCELifier.printFlags(access_flags,
            BCELifier.FLAGS.METHOD));
    final int descriptor_index = file.readUnsignedShort();
    System.out.printf("  descriptor_index: %d (", descriptor_index);
    System.out.println(constantToString(descriptor_index) + ")");

    final int attributes_count = file.readUnsignedShort();
    final Attribute[] attributes = new Attribute[attributes_count];
    System.out.println("  attribute count: " + attributes_count);

    for (int i = 0; i < attributes_count; i++) {
        // going to peek ahead a bit
        file.mark();
        final int attribute_name_index = file.readUnsignedShort();
        final int attribute_length = file.readInt();
        // restore file location
        file.reset();
        // Usefull for debugging
        // System.out.printf("  attribute_name_index: %d (", attribute_name_index);
        // System.out.println(constantToString(attribute_name_index) + ")");
        // System.out.printf("  atribute offset in file: %x%n", + file.getStreamPosition());
        // System.out.println("  atribute_length: " + attribute_length);

        // A stronger verification test would be to read attribute_length bytes
        // into a buffer.  Then pass that buffer to readAttribute and also
        // verify we're at EOF of the buffer on return.

        final long pos1 = file.getStreamPosition();
        attributes[i] = Attribute.readAttribute(file, constant_pool);
        final long pos2 = file.getStreamPosition();
        if ((pos2 - pos1) != (attribute_length + 6)) {
            System.out.printf("%nattribute_length: %d pos2-pos1-6: %d pos1: %x(%d) pos2: %x(%d)%n",
                    attribute_length, pos2-pos1-6, pos1, pos1, pos2, pos2);
        }
        System.out.printf("  ");
        System.out.println(attributes[i]);
    }
}
 
Example 25
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: 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.");
        }
    }
}