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

The following examples show how to use org.apache.bcel.classfile.ConstantPool#getConstant() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: FieldOrMethod.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the reference type representing the class, interface,
 * or array class referenced by the instruction.
 * @param cpg the ConstantPoolGen used to create the instruction
 * @return an ObjectType (if the referenced class type is a class
 *   or interface), or an ArrayType (if the referenced class
 *   type is an array class)
 */
public ReferenceType getReferenceType(final ConstantPoolGen cpg) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
    if (className.startsWith("[")) {
        return (ArrayType) Type.getType(className);
    }
    className = className.replace('/', '.');
    return ObjectType.getInstance(className);
}
 
Example 9
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 10
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 11
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 12
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 13
Source File: ClassDumper.java    From cloud-opensource-java with 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 14
Source File: ClassDumper.java    From cloud-opensource-java with 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 15
Source File: FieldGen.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private void setValue( final int index ) {
    final ConstantPool cp = super.getConstantPool().getConstantPool();
    final Constant c = cp.getConstant(index);
    value = ((ConstantObject) c).getConstantValue(cp);
}
 
Example 16
Source File: NameSignatureInstruction.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
public ConstantNameAndType getNameAndType(final ConstantPoolGen cpg) {
    final ConstantPool cp = cpg.getConstantPool();
    final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
    return  (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex());
}
 
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: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Flush out cached state at the end of a method.
 */
private void flush() {

    if (pendingAbsoluteValueBug != null) {
        absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine);
        pendingAbsoluteValueBug = null;
        pendingAbsoluteValueBugSourceLine = null;
    }
    accumulator.reportAccumulatedBugs();
    if (sawLoadOfMinValue) {
        absoluteValueAccumulator.clearBugs();
    } else {
        absoluteValueAccumulator.reportAccumulatedBugs();
    }
    if (gcInvocationBugReport != null && !sawCurrentTimeMillis) {
        // Make sure the GC invocation is not in an exception handler
        // for OutOfMemoryError.
        boolean outOfMemoryHandler = false;
        for (CodeException handler : exceptionTable) {
            if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) {
                continue;
            }
            int catchTypeIndex = handler.getCatchType();
            if (catchTypeIndex > 0) {
                ConstantPool cp = getThisClass().getConstantPool();
                Constant constant = cp.getConstant(catchTypeIndex);
                if (constant instanceof ConstantClass) {
                    String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp);
                    if ("java/lang/OutOfMemoryError".equals(exClassName)) {
                        outOfMemoryHandler = true;
                        break;
                    }
                }
            }
        }

        if (!outOfMemoryHandler) {
            bugReporter.reportBug(gcInvocationBugReport);
        }
    }

    sawCurrentTimeMillis = false;
    gcInvocationBugReport = null;

    exceptionTable = null;
}
 
Example 19
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 20
Source File: Util.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static int getSizeOfSurroundingTryBlock(ConstantPool constantPool, Code code,
        @CheckForNull @SlashedClassName String vmNameOfExceptionClass, int pc) {
    int size = Integer.MAX_VALUE;
    int tightStartPC = 0;
    int tightEndPC = Integer.MAX_VALUE;
    if (code.getExceptionTable() == null) {
        return size;
    }
    for (CodeException catchBlock : code.getExceptionTable()) {
        if (vmNameOfExceptionClass != null) {
            Constant catchType = constantPool.getConstant(catchBlock.getCatchType());
            if (catchType == null && !vmNameOfExceptionClass.isEmpty() || catchType instanceof ConstantClass
                    && !((ConstantClass) catchType).getBytes(constantPool).equals(vmNameOfExceptionClass)) {
                continue;
            }
        }
        int startPC = catchBlock.getStartPC();
        int endPC = catchBlock.getEndPC();
        if (pc >= startPC && pc <= endPC) {
            int thisSize = endPC - startPC;
            if (size > thisSize) {
                size = thisSize;
                tightStartPC = startPC;
                tightEndPC = endPC;
            }
        }
    }
    if (size == Integer.MAX_VALUE) {
        return size;
    }

    // try to guestimate number of lines that correspond
    size = (size + 7) / 8;
    LineNumberTable lineNumberTable = code.getLineNumberTable();
    if (lineNumberTable == null) {
        return size;
    }

    int count = 0;
    for (LineNumber line : lineNumberTable.getLineNumberTable()) {
        if (line.getStartPC() > tightEndPC) {
            break;
        }
        if (line.getStartPC() >= tightStartPC) {
            count++;
        }
    }
    return count;

}