Java Code Examples for org.apache.bcel.classfile.JavaClass#getConstantPool()

The following examples show how to use org.apache.bcel.classfile.JavaClass#getConstantPool() . 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: LocalVariableTypeTableTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private byte[] getBytesFromClass(final String className) throws ClassNotFoundException {
    final JavaClass clazz = getTestClass(className);
    final ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());

    final Method[] methods = clazz.getMethods();

    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        if (!method.isNative() && !method.isAbstract()) {
            methods[i] = injection(clazz, method, cp, findFirstStringLocalVariableOffset(method));
        }
    }

    clazz.setConstantPool(cp.getFinalConstantPool());

    return clazz.getBytes();
}
 
Example 2
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private CPESSC_Visitor(final JavaClass _jc) {
    jc = _jc;
    cp = _jc.getConstantPool();
    cplen = cp.getLength();

    CONST_Class = ConstantClass.class;
    /*
    CONST_Fieldref = ConstantFieldref.class;
    CONST_Methodref = ConstantMethodref.class;
    CONST_InterfaceMethodref = ConstantInterfaceMethodref.class;
    */
    CONST_String = ConstantString.class;
    CONST_Integer = ConstantInteger.class;
    CONST_Float = ConstantFloat.class;
    CONST_Long = ConstantLong.class;
    CONST_Double = ConstantDouble.class;
    CONST_NameAndType = ConstantNameAndType.class;
    CONST_Utf8 = ConstantUtf8.class;

    carrier = new DescendingVisitor(_jc, this);
    carrier.visit();
}
 
Example 3
Source File: EnclosingMethodAttributeTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: Peephole.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) {
    try {
        // Load the class from CLASSPATH.
        final JavaClass clazz = Repository.lookupClass(argv[0]);
        final Method[] methods = clazz.getMethods();
        final ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());

        for (int i = 0; i < methods.length; i++) {
            if (!(methods[i].isAbstract() || methods[i].isNative())) {
                final MethodGen mg = new MethodGen(methods[i], clazz.getClassName(), cp);
                final Method stripped = removeNOPs(mg);

                if (stripped != null) {
                    methods[i] = stripped; // Overwrite with stripped method
                }
            }
        }

        // Dump the class to <class name>_.class
        clazz.setConstantPool(cp.getFinalConstantPool());
        clazz.dump(clazz.getClassName() + "_.class");
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: helloify.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String arg : argv) {
        if (arg.endsWith(".class")) {
            final JavaClass java_class = new ClassParser(arg).parse();
            final ConstantPool constants = java_class.getConstantPool();
            final String file_name = arg.substring(0, arg.length() - 6) + "_hello.class";
            cp = new ConstantPoolGen(constants);

            helloifyClassName(java_class);

            out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;");
            println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V");
            // Patch all methods.
            final Method[] methods = java_class.getMethods();

            for (int j = 0; j < methods.length; j++) {
                methods[j] = helloifyMethod(methods[j]);
            }

            // Finally dump it back to a file.
            java_class.setConstantPool(cp.getFinalConstantPool());
            java_class.dump(file_name);
        }
    }
}
 
Example 6
Source File: FindStrings.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Main class, to find strings in class files.
 * @param args Arguments to program.
 */
public static void main(String[] args) {
    try {
        JavaClass clazz = Repository.lookupClass(args[0]);
        ConstantPool cp = clazz.getConstantPool();
        Constant[] consts = cp.getConstantPool();


        for (int i = 0; i < consts.length; i++) {

            if (consts[i] instanceof ConstantString) {
                System.out.println("Found String: " +
                        ((ConstantString)consts[i]).getBytes(cp));
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: EnclosingMethodAttributeTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source File: ClassDumper.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the indices of all class symbol references to {@code targetClassName} in the constant
 * pool of {@code sourceJavaClass}.
 */
ImmutableSet<Integer> constantPoolIndexForClass(
    JavaClass sourceJavaClass, String targetClassName) {
  ImmutableSet.Builder<Integer> constantPoolIndicesForTarget = ImmutableSet.builder();

  ConstantPool sourceConstantPool = sourceJavaClass.getConstantPool();
  Constant[] constantPool = sourceConstantPool.getConstantPool();
  // constantPool indexes start from 1. 0th entry is null.
  for (int poolIndex = 1; poolIndex < constantPool.length; poolIndex++) {
    Constant constant = constantPool[poolIndex];
    if (constant != null) {
      byte constantTag = constant.getTag();
      if (constantTag == Const.CONSTANT_Class) {
        ConstantClass constantClass = (ConstantClass) constant;
        ClassSymbol classSymbol = makeSymbol(constantClass, sourceConstantPool, sourceJavaClass);
        if (targetClassName.equals(classSymbol.getClassBinaryName())) {
          constantPoolIndicesForTarget.add(poolIndex);
        }
      }
    }
  }

  return constantPoolIndicesForTarget.build();
}
 
Example 9
Source File: FindStrings.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Main class, to find strings in class files.
 * @param args Arguments to program.
 */
public static void main(String[] args) {
    try {
        JavaClass clazz = Repository.lookupClass(args[0]);
        ConstantPool cp = clazz.getConstantPool();
        Constant[] consts = cp.getConstantPool();


        for (int i = 0; i < consts.length; i++) {

            if (consts[i] instanceof ConstantString) {
                System.out.println("Found String: " +
                        ((ConstantString)consts[i]).getBytes(cp));
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: EnclosingMethodAttributeTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Check that we can save and load the attribute correctly.
 */
public void testAttributeSerializtion() throws ClassNotFoundException,
        IOException
{
    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);
    // Write it out
    final File tfile = createTestdataFile("AttributeTestClassEM02$1.class");
    clazz.dump(tfile);
    // Read in the new version and check it is OK
    final SyntheticRepository repos2 = createRepos(".");
    final JavaClass clazz2 = repos2.loadClass("AttributeTestClassEM02$1");
    Assert.assertNotNull(clazz2); // Use the variable to avoid a warning
    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"));
    tfile.deleteOnExit();
}
 
Example 11
Source File: TapestryEndpointDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {

    JavaClass javaClass = classContext.getJavaClass();

    if (!javaClass.getPackageName().contains(".pages")) {
        return;
    }

    //The package contains ".pages" and has some references to tapestry
    // then it must be an endpoint.
    //The constants pool contains all references that are reused in the bytecode
    // including full class name and interface name.
    if (javaClass.getPackageName().contains(".pages")) {
        ConstantPool constants = javaClass.getConstantPool();
        for (Constant c : constants.getConstantPool()) {
            if (c instanceof ConstantUtf8) {
                ConstantUtf8 utf8 = (ConstantUtf8) c;
                String constantValue = String.valueOf(utf8.getBytes());
                if (constantValue.startsWith("Lorg/apache/tapestry5/annotations")) {
                    bugReporter.reportBug(new BugInstance(this, TAPESTRY_ENDPOINT_TYPE, Priorities.LOW_PRIORITY) //
                            .addClass(javaClass));
                    return;
                }
            }
        }
    }

}
 
Example 12
Source File: Class2HTML.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Write contents of the given JavaClass into HTML files.
 *
 * @param java_class The class to write
 * @param dir The directory to put the files in
 */
public Class2HTML(final JavaClass java_class, final String dir) throws IOException {
    final Method[] methods = java_class.getMethods();
    this.java_class = java_class;
    this.dir = dir;
    class_name = java_class.getClassName(); // Remember full name
    constant_pool = java_class.getConstantPool();
    // Get package name by tacking off everything after the last `.'
    final int index = class_name.lastIndexOf('.');
    if (index > -1) {
        class_package = class_name.substring(0, index);
    } else {
        class_package = ""; // default package
    }
    final ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods,
            constant_pool);
    /* Attributes can't be written in one step, so we just open a file
     * which will be written consequently.
     */
    final AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool,
            constant_html);
    new MethodHTML(dir, class_name, methods, java_class.getFields(),
            constant_html, attribute_html);
    // Write main file (with frames, yuk)
    writeMainHTML(attribute_html);
    new CodeHTML(dir, class_name, methods, constant_pool, constant_html);
    attribute_html.close();
}
 
Example 13
Source File: Package.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Add this class to allClasses. Then go through all its dependents
 * and add them to the dependents list if they are not in allClasses
 */
void addDependents(final JavaClass clazz) throws IOException {
    final String name = clazz.getClassName().replace('.', '/');
    allClasses.put(name, clazz);
    final ConstantPool pool = clazz.getConstantPool();
    for (int i = 1; i < pool.getLength(); i++) {
        final Constant cons = pool.getConstant(i);
        //System.out.println("("+i+") " + cons );
        if (cons != null && cons.getTag() == Constants.CONSTANT_Class) {
            final int idx = ((ConstantClass) pool.getConstant(i)).getNameIndex();
            final String clas = ((ConstantUtf8) pool.getConstant(idx)).getBytes();
            addClassString(clas, name);
        }
    }
}
 
Example 14
Source File: TransitiveHull.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Start traversal using DescendingVisitor pattern.
 */
public void start() {
    while (!queue.empty()) {
        final JavaClass clazz = queue.dequeue();
        cp = clazz.getConstantPool();

        new org.apache.bcel.classfile.DescendingVisitor(clazz, this).visit();
    }
}
 
Example 15
Source File: ClassDumper.java    From cloud-opensource-java with 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 16
Source File: ClassGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize with existing class.
 * @param clazz JavaClass object (e.g. read from file)
 */
public ClassGen(final JavaClass clazz) {
    super(clazz.getAccessFlags());
    classNameIndex = clazz.getClassNameIndex();
    superclass_name_index = clazz.getSuperclassNameIndex();
    className = clazz.getClassName();
    superClassName = clazz.getSuperclassName();
    fileName = clazz.getSourceFileName();
    cp = new ConstantPoolGen(clazz.getConstantPool());
    major = clazz.getMajor();
    minor = clazz.getMinor();
    final Attribute[] attributes = clazz.getAttributes();
    // J5TODO: Could make unpacking lazy, done on first reference
    final AnnotationEntryGen[] annotations = unpackAnnotations(attributes);
    final Method[] methods = clazz.getMethods();
    final Field[] fields = clazz.getFields();
    final String[] interfaces = clazz.getInterfaceNames();
    for (final String interface1 : interfaces) {
        addInterface(interface1);
    }
    for (final Attribute attribute : attributes) {
        if (!(attribute instanceof Annotations)) {
            addAttribute(attribute);
        }
    }
    for (final AnnotationEntryGen annotation : annotations) {
        addAnnotationEntry(annotation);
    }
    for (final Method method : methods) {
        addMethod(method);
    }
    for (final Field field : fields) {
        addField(field);
    }
}
 
Example 17
Source File: AssertionMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
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 18
Source File: ResolveAllReferences.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    compute();
    ConstantPool cp = obj.getConstantPool();
    Constant[] constants = cp.getConstantPool();
    checkConstant: for (int i = 0; i < constants.length; i++) {
        Constant co = constants[i];
        if (co instanceof ConstantDouble || co instanceof ConstantLong) {
            i++;
        }
        if (co instanceof ConstantClass) {
            String ref = getClassName(obj, i);
            if ((ref.startsWith("java") || ref.startsWith("org.w3c.dom")) && !defined.contains(ref)) {
                bugReporter.reportBug(new BugInstance(this, "VR_UNRESOLVABLE_REFERENCE", NORMAL_PRIORITY).addClass(obj)
                        .addString(ref));
            }

        } else if (co instanceof ConstantFieldref) {
            // do nothing until we handle static fields defined in
            // interfaces

        } else if (co instanceof ConstantInvokeDynamic) {
            // ignore. BCEL puts garbage data into ConstantInvokeDynamic
        } else if (co instanceof ConstantCP) {
            ConstantCP co2 = (ConstantCP) co;
            String className = getClassName(obj, co2.getClassIndex());

            // System.out.println("checking " + ref);
            if (className.equals(obj.getClassName()) || !defined.contains(className)) {
                // System.out.println("Skipping check of " + ref);
                continue checkConstant;
            }
            ConstantNameAndType nt = (ConstantNameAndType) cp.getConstant(co2.getNameAndTypeIndex());
            String name = ((ConstantUtf8) obj.getConstantPool().getConstant(nt.getNameIndex(), Const.CONSTANT_Utf8)).getBytes();
            String signature = ((ConstantUtf8) obj.getConstantPool().getConstant(nt.getSignatureIndex(), Const.CONSTANT_Utf8))
                    .getBytes();

            try {
                JavaClass target = Repository.lookupClass(className);
                if (!find(target, name, signature)) {
                    bugReporter.reportBug(new BugInstance(this, "VR_UNRESOLVABLE_REFERENCE", NORMAL_PRIORITY).addClass(obj)
                            .addString(getMemberName(target.getClassName(), name, signature)));
                }

            } catch (ClassNotFoundException e) {
                bugReporter.reportMissingClass(e);
            }
        }

    }
}
 
Example 19
Source File: Pass3bVerifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Pass 3b implements the data flow analysis as described in the Java Virtual
 * Machine Specification, Second Edition.
 * Later versions will use LocalVariablesInfo objects to verify if the
 * verifier-inferred types and the class file's debug information (LocalVariables
 * attributes) match [TODO].
 *
 * @see org.apache.bcel.verifier.statics.LocalVariablesInfo
 * @see org.apache.bcel.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
 */
@Override
public VerificationResult do_verify() {
    if (! myOwner.doPass3a(methodNo).equals(VerificationResult.VR_OK)) {
        return VerificationResult.VR_NOTYET;
    }

    // Pass 3a ran before, so it's safe to assume the JavaClass object is
    // in the BCEL repository.
    JavaClass jc;
    try {
        jc = Repository.lookupClass(myOwner.getClassName());
    } catch (final ClassNotFoundException e) {
        // FIXME: maybe not the best way to handle this
        throw new AssertionViolatedException("Missing class: " + e, e);
    }

    final ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool());
    // Init Visitors
    final InstConstraintVisitor icv = new InstConstraintVisitor();
    icv.setConstantPoolGen(constantPoolGen);

    final ExecutionVisitor ev = new ExecutionVisitor();
    ev.setConstantPoolGen(constantPoolGen);

    final Method[] methods = jc.getMethods(); // Method no "methodNo" exists, we ran Pass3a before on it!

    try{

        final MethodGen mg = new MethodGen(methods[methodNo], myOwner.getClassName(), constantPoolGen);

        icv.setMethodGen(mg);

        ////////////// DFA BEGINS HERE ////////////////
        if (! (mg.isAbstract() || mg.isNative()) ) { // IF mg HAS CODE (See pass 2)

            final ControlFlowGraph cfg = new ControlFlowGraph(mg);

            // Build the initial frame situation for this method.
            final Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack());
            if ( !mg.isStatic() ) {
                if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) {
                    Frame.setThis(new UninitializedObjectType(ObjectType.getInstance(jc.getClassName())));
                    f.getLocals().set(0, Frame.getThis());
                }
                else{
                    Frame.setThis(null);
                    f.getLocals().set(0, ObjectType.getInstance(jc.getClassName()));
                }
            }
            final Type[] argtypes = mg.getArgumentTypes();
            int twoslotoffset = 0;
            for (int j=0; j<argtypes.length; j++) {
                if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE ||
                    argtypes[j] == Type.CHAR || argtypes[j] == Type.BOOLEAN) {
                    argtypes[j] = Type.INT;
                }
                f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), argtypes[j]);
                if (argtypes[j].getSize() == 2) {
                    twoslotoffset++;
                    f.getLocals().set(twoslotoffset + j + (mg.isStatic()?0:1), Type.UNKNOWN);
                }
            }
            circulationPump(mg,cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
        }
    }
    catch (final VerifierConstraintViolatedException ce) {
        ce.extendMessage("Constraint violated in method '"+methods[methodNo]+"':\n","");
        return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
    }
    catch (final RuntimeException re) {
        // These are internal errors

        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        re.printStackTrace(pw);

        throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+
            "', method '"+methods[methodNo]+"'. Original RuntimeException's stack trace:\n---\n"+sw+"---\n", re);
    }
    return VerificationResult.VR_OK;
}
 
Example 20
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private FAMRAV_Visitor(final JavaClass _jc) {
    cp = _jc.getConstantPool();
}