org.apache.bcel.classfile.ConstantPool Java Examples

The following examples show how to use org.apache.bcel.classfile.ConstantPool. 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: 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 #2
Source File: InvokeInstruction.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * @return mnemonic for instruction with symbolic references resolved
 */
@Override
public String toString( final ConstantPool cp ) {
    final Constant c = cp.getConstant(super.getIndex());
    final StringTokenizer tok = new StringTokenizer(cp.constantToString(c));

    final String opcodeName = Const.getOpcodeName(super.getOpcode());

    final StringBuilder sb = new StringBuilder(opcodeName);
    if (tok.hasMoreTokens()) {
        sb.append(" ");
        sb.append(tok.nextToken().replace('.', '/'));
        if (tok.hasMoreTokens()) {
            sb.append(tok.nextToken());
        }
    }

    return sb.toString();
}
 
Example #3
Source File: StaticCalendarDetector.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(ConstantPool pool) {
    for (Constant constant : pool.getConstantPool()) {
        if (constant instanceof ConstantClass) {
            ConstantClass cc = (ConstantClass) constant;
            @SlashedClassName
            String className = cc.getBytes(pool);
            if ("java/util/Calendar".equals(className) || "java/text/DateFormat".equals(className)) {
                sawDateClass = true;
                break;
            }
            if (className.charAt(0) != '[') {
                try {
                    ClassDescriptor cDesc = DescriptorFactory.createClassDescriptor(className);

                    if (subtypes2.isSubtype(cDesc, calendarType) || subtypes2.isSubtype(cDesc, dateFormatType)) {
                        sawDateClass = true;
                        break;
                    }
                } catch (ClassNotFoundException e) {
                    reporter.reportMissingClass(e);
                }
            }
        }
    }
}
 
Example #4
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns true if given constant pool probably has a reference to any of supplied methods
 * Useful to exclude from analysis uninteresting classes
 * @param cp constant pool
 * @param methods methods collection
 * @return true if method is found
 */
public static boolean hasInterestingMethod(ConstantPool cp, Collection<MethodDescriptor> methods) {
    for (Constant c : cp.getConstantPool()) {
        if (c instanceof ConstantMethodref || c instanceof ConstantInterfaceMethodref) {
            ConstantCP desc = (ConstantCP) c;
            ConstantNameAndType nameAndType = (ConstantNameAndType) cp.getConstant(desc.getNameAndTypeIndex());
            String className = cp.getConstantString(desc.getClassIndex(), Const.CONSTANT_Class);
            String name = ((ConstantUtf8) cp.getConstant(nameAndType.getNameIndex())).getBytes();
            String signature = ((ConstantUtf8) cp.getConstant(nameAndType.getSignatureIndex())).getBytes();
            // We don't know whether method is static thus cannot use equals
            int hash = FieldOrMethodDescriptor.getNameSigHashCode(name, signature);
            for (MethodDescriptor method : methods) {
                if (method.getNameSigHashCode() == hash
                        && (method.getSlashedClassName().isEmpty() || method.getSlashedClassName().equals(className))
                        && method.getName().equals(name) && method.getSignature().equals(signature)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #5
Source File: listclass.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static String[] getClassDependencies(final ConstantPool pool) {
    final String[] tempArray = new String[pool.getLength()];
    int size = 0;
    final StringBuilder buf = new StringBuilder();

    for (int idx = 0; idx < pool.getLength(); idx++) {
        final Constant c = pool.getConstant(idx);
        if (c != null && c.getTag() == Constants.CONSTANT_Class) {
            final ConstantUtf8 c1 = (ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex());
            buf.setLength(0);
            buf.append(c1.getBytes());
            for (int n = 0; n < buf.length(); n++) {
                if (buf.charAt(n) == '/') {
                    buf.setCharAt(n, '.');
                }
            }

            tempArray[size++] = buf.toString();
        }
    }

    final String[] dependencies = new String[size];
    System.arraycopy(tempArray, 0, dependencies, 0, size);
    return dependencies;
}
 
Example #6
Source File: BuildUnconditionalParamDerefDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean isCaught(ClassContext classContext, Method method, UnconditionalValueDerefSet entryFact, ValueNumber paramVN) {
    boolean caught = true;

    Set<Location> dereferenceSites = entryFact.getDerefLocationSet(paramVN);
    if (dereferenceSites != null && !dereferenceSites.isEmpty()) {
        ConstantPool cp = classContext.getJavaClass().getConstantPool();

        for (Location loc : dereferenceSites) {
            if (!FindNullDeref.catchesNull(cp, method.getCode(), loc)) {
                caught = false;
            }
        }

    }
    return caught;
}
 
Example #7
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 #8
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 #9
Source File: ClassGen.java    From commons-bcel with 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 #10
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 #11
Source File: ClassLoader.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Override this method to create you own classes on the fly. The
 * name contains the special token $$BCEL$$. Everything before that
 * token is considered to be a package name. You can encode your own
 * arguments into the subsequent string. You must ensure however not
 * to use any "illegal" characters, i.e., characters that may not
 * appear in a Java class name too
 * <p>
 * The default implementation interprets the string as a encoded compressed
 * Java class, unpacks and decodes it with the Utility.decode() method, and
 * parses the resulting byte array and returns the resulting JavaClass object.
 * </p>
 *
 * @param class_name compressed byte code with "$$BCEL$$" in it
 */
protected JavaClass createClass( final String class_name ) {
    final int index = class_name.indexOf(BCEL_TOKEN);
    final String real_name = class_name.substring(index + BCEL_TOKEN.length());
    JavaClass clazz = null;
    try {
        final byte[] bytes = Utility.decode(real_name, true);
        final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo");
        clazz = parser.parse();
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }
    // Adapt the class name to the passed value
    final ConstantPool cp = clazz.getConstantPool();
    final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(),
            Const.CONSTANT_Class);
    final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(),
            Const.CONSTANT_Utf8);
    name.setBytes(class_name.replace('.', '/'));
    return clazz;
}
 
Example #12
Source File: ConstantHTML.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
ConstantHTML(final String dir, final String class_name, final String class_package, final Method[] methods,
        final ConstantPool constant_pool) throws IOException {
    this.className = class_name;
    this.classPackage = class_package;
    this.constantPool = constant_pool;
    this.methods = methods;
    constants = constant_pool.getConstantPool();
    file = new PrintWriter(new FileOutputStream(dir + class_name + "_cp.html"));
    constantRef = new String[constants.length];
    constantRef[0] = "&lt;unknown&gt;";
    file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\"><TABLE BORDER=0>");
    // Loop through constants, constants[0] is reserved
    for (int i = 1; i < constants.length; i++) {
        if (i % 2 == 0) {
            file.print("<TR BGCOLOR=\"#C0C0C0\"><TD>");
        } else {
            file.print("<TR BGCOLOR=\"#A0A0A0\"><TD>");
        }
        if (constants[i] != null) {
            writeConstant(i);
        }
        file.print("</TD></TR>\n");
    }
    file.println("</TABLE></BODY></HTML>");
    file.close();
}
 
Example #13
Source File: InnerClassAccessMap.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Called to indicate that a field load or store was encountered.
 *
 * @param cpIndex
 *            the constant pool index of the fieldref
 * @param isStatic
 *            true if it is a static field access
 * @param isLoad
 *            true if the access is a load
 */
private void setField(int cpIndex, boolean isStatic, boolean isLoad) {
    // We only allow one field access for an accessor method.
    accessCount++;
    if (accessCount != 1) {
        access = null;
        return;
    }

    ConstantPool cp = javaClass.getConstantPool();
    ConstantFieldref fieldref = (ConstantFieldref) cp.getConstant(cpIndex);

    ConstantClass cls = (ConstantClass) cp.getConstant(fieldref.getClassIndex());
    String className = cls.getBytes(cp).replace('/', '.');

    ConstantNameAndType nameAndType = (ConstantNameAndType) cp.getConstant(fieldref.getNameAndTypeIndex());
    String fieldName = nameAndType.getName(cp);
    String fieldSig = nameAndType.getSignature(cp);


    XField xfield = Hierarchy.findXField(className, fieldName, fieldSig, isStatic);
    if (xfield != null && xfield.isStatic() == isStatic && isValidAccessMethod(methodSig, xfield, isLoad)) {
        access = new InnerClassAccess(methodName, methodSig, xfield, isLoad);
    }

}
 
Example #14
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 #15
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 #16
Source File: AttributeHTML.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
AttributeHTML(final String dir, final String class_name, final ConstantPool constant_pool,
        final ConstantHTML constant_html) throws IOException {
    this.class_name = class_name;
    this.constant_pool = constant_pool;
    this.constant_html = constant_html;
    file = new PrintWriter(new FileOutputStream(dir + class_name + "_attributes.html"));
    file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\"><TABLE BORDER=0>");
}
 
Example #17
Source File: INVOKEDYNAMIC.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Override the parent method because our classname is held elsewhere.
 */
@Override
public String getClassName( final ConstantPoolGen cpg ) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantInvokeDynamic cid = (ConstantInvokeDynamic) cp.getConstant(super.getIndex(), Const.CONSTANT_InvokeDynamic);
    return ((ConstantNameAndType) cp.getConstant(cid.getNameAndTypeIndex())).getName(cp);
}
 
Example #18
Source File: CPInstruction.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** @return type related with this instruction.
 */
@Override
public Type getType( final ConstantPoolGen cpg ) {
    final ConstantPool cp = cpg.getConstantPool();
    String name = cp.getConstantString(index, org.apache.bcel.Const.CONSTANT_Class);
    if (!name.startsWith("[")) {
        name = "L" + name + ";";
    }
    return Type.getType(name);
}
 
Example #19
Source File: InvokeInstruction.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * This overrides the deprecated version as we know here that the referenced class
 * may legally be an array.
 *
 * @return name of the referenced class/interface
 * @throws IllegalArgumentException if the referenced class is an array (this should not happen)
 */
@Override
public String getClassName( final ConstantPoolGen cpg ) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
    return className.replace('/', '.');
}
 
Example #20
Source File: FieldOrMethod.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @return name of the referenced class/interface
 * @deprecated If the instruction references an array class,
 *    this method will return "java.lang.Object".
 *    For code generated by Java 1.5, this answer is
 *    sometimes wrong (e.g., if the "clone()" method is
 *    called on an array).  A better idea is to use
 *    the {@link #getReferenceType(ConstantPoolGen)} method, which correctly distinguishes
 *    between class types and array types.
 *
 */
@Deprecated
public String getClassName(final ConstantPoolGen cpg) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
    if (className.startsWith("[")) {
        // Turn array classes into java.lang.Object.
        return "java.lang.Object";
    }
    return className.replace('/', '.');
}
 
Example #21
Source File: FieldOrMethod.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** @return signature of referenced method/field.
 */
public String getSignature(final ConstantPoolGen cpg) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex());
    return ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes();
}
 
Example #22
Source File: FieldOrMethod.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** @return name of referenced method/field.
 */
public String getName(final ConstantPoolGen cpg) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex());
    return ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes();
}
 
Example #23
Source File: ReferenceVisitor.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IDeepVisitor */
public void visitObject(Object aObject)
{
    final JavaClass javaClass = (JavaClass) aObject;
    final ConstantPool pool = javaClass.getConstantPool();
    mCurrentPoolGen = new ConstantPoolGen(pool);
}
 
Example #24
Source File: CodeHTML.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
CodeHTML(final String dir, final String class_name, final Method[] methods, final ConstantPool constant_pool,
            final ConstantHTML constant_html) throws IOException {
        this.className = class_name;
//        this.methods = methods;
        this.constantPool = constant_pool;
        this.constantHtml = constant_html;
        file = new PrintWriter(new FileOutputStream(dir + class_name + "_code.html"));
        file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\">");
        for (int i = 0; i < methods.length; i++) {
            writeMethod(methods[i], i);
        }
        file.println("</BODY></HTML>");
        file.close();
    }
 
Example #25
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 #26
Source File: CPInstruction.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @return mnemonic for instruction with symbolic references resolved
 */
@Override
public String toString( final ConstantPool cp ) {
    final Constant c = cp.getConstant(index);
    String str = cp.constantToString(c);
    if (c instanceof ConstantClass) {
        str = str.replace('.', '/');
    }
    return org.apache.bcel.Const.getOpcodeName(super.getOpcode()) + " " + str;
}
 
Example #27
Source File: ClassDumper.java    From commons-bcel with 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 #28
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 #29
Source File: VisitorSet.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @see org.apache.bcel.classfile.Visitor
 */
public void visitConstantPool(ConstantPool aConstantPool)
{
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aConstantPool.accept(v);
    }
}
 
Example #30
Source File: listclass.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Dump the list of classes this class is dependent on
 */
public static void printClassDependencies(final ConstantPool pool) {
    System.out.println("Dependencies:");
    for (final String name : getClassDependencies(pool)) {
        System.out.println("\t" + name);
    }
}