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

The following examples show how to use org.apache.bcel.classfile.ConstantPool#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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitConstantPool(ConstantPool obj) {
    super.visitConstantPool(obj);
    Constant[] constant_pool = obj.getConstantPool();
    for (int i = 1; i < constant_pool.length; i++) {
        constant_pool[i].accept(this);
        byte tag = constant_pool[i].getTag();
        if ((tag == Const.CONSTANT_Double) || (tag == Const.CONSTANT_Long)) {
            i++;
        }
    }
}
 
Example 9
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static boolean hasInterestingClass(ConstantPool cp, Collection<String> classes) {
    for (Constant c : cp.getConstantPool()) {
        if (c instanceof ConstantClass) {
            String className = ((ConstantUtf8) cp.getConstant(((ConstantClass) c).getNameIndex())).getBytes();
            if (classes.contains(className)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 10
Source File: ClassDumper.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
private static SymbolReferences.Builder findSymbolReferences(
    ClassFile source, JavaClass javaClass) {
  SymbolReferences.Builder builder = new SymbolReferences.Builder();

  ConstantPool constantPool = javaClass.getConstantPool();
  Constant[] constants = constantPool.getConstantPool();
  for (Constant constant : constants) {
    if (constant == null) {
       continue;
    }

    byte constantTag = constant.getTag();
    switch (constantTag) {
      case Const.CONSTANT_Class:
        ConstantClass constantClass = (ConstantClass) constant;
        ClassSymbol classSymbol = makeSymbol(constantClass, constantPool, javaClass);
        // skip array class because it is provided by runtime
        if (classSymbol.getClassBinaryName().startsWith("[")) {
          break;
        }
        builder.addClassReference(source, classSymbol);
        break;
      case Const.CONSTANT_Methodref:
      case Const.CONSTANT_InterfaceMethodref:
        // Both ConstantMethodref and ConstantInterfaceMethodref are subclass of ConstantCP
        ConstantCP constantMethodref = (ConstantCP) constant;
        builder.addMethodReference(source, makeSymbol(constantMethodref, constantPool));
        break;
      case Const.CONSTANT_Fieldref:
        ConstantFieldref constantFieldref = (ConstantFieldref) constant;
        builder.addFieldReference(source, makeSymbol(constantFieldref, constantPool));
        break;
      default:
        break;
    }
  }

  for (String interfaceName : javaClass.getInterfaceNames()) {
    builder.addClassReference(source, new InterfaceSymbol(interfaceName));
  }

  return builder;
}
 
Example 11
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 12
Source File: ConstantPoolGen.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize with given constant pool.
 */
public ConstantPoolGen(final ConstantPool cp) {
    this(cp.getConstantPool());
}