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

The following examples show how to use org.apache.bcel.classfile.ConstantClass. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: 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 2
Source Project: ApkToolPlus   Source File: InstConstraintVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitCHECKCAST(CHECKCAST o){
	// The objectref must be of type reference.
	Type objectref = stack().peek(0);
	if (!(objectref instanceof ReferenceType)){
		constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+".");
	}
	else{
		referenceTypeIsInitialized(o, (ReferenceType) objectref);
	}
	// The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the
	// current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant
	// pool item at the index must be a symbolic reference to a class, array, or interface type.
	Constant c = cpg.getConstant(o.getIndex());
	if (! (c instanceof ConstantClass)){
		constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'.");
	}
}
 
Example 3
Source Project: ApkToolPlus   Source File: InstConstraintVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitINSTANCEOF(INSTANCEOF o){
	// The objectref must be of type reference.
	Type objectref = stack().peek(0);
	if (!(objectref instanceof ReferenceType)){
		constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+".");
	}
	else{
		referenceTypeIsInitialized(o, (ReferenceType) objectref);
	}
	// The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the
	// current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant
	// pool item at the index must be a symbolic reference to a class, array, or interface type.
	Constant c = cpg.getConstant(o.getIndex());
	if (! (c instanceof ConstantClass)){
		constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'.");
	}
}
 
Example 4
public void setupVisitorForClass(JavaClass obj) {
    constantPool = obj.getConstantPool();
    thisClass = obj;
    ConstantClass c = (ConstantClass) constantPool.getConstant(obj.getClassNameIndex());
    className = getStringFromIndex(c.getNameIndex());
    dottedClassName = className.replace('/', '.');
    packageName = obj.getPackageName();
    sourceFile = obj.getSourceFileName();
    dottedSuperclassName = obj.getSuperclassName();
    superclassName = dottedSuperclassName.replace('.', '/');

    ClassDescriptor cDesc = DescriptorFactory.createClassDescriptor(className);
    if (!FindBugs.isNoAnalysis()) {
        try {
            thisClassInfo = (ClassInfo) Global.getAnalysisCache().getClassAnalysis(XClass.class, cDesc);
        } catch (CheckedAnalysisException e) {
            throw new AssertionError("Can't find ClassInfo for " + cDesc);
        }
    }

    super.visitJavaClass(obj);
}
 
Example 5
Source Project: spotbugs   Source File: Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Determine the outer class of obj.
 *
 * @param obj
 * @return JavaClass for outer class, or null if obj is not an outer class
 * @throws ClassNotFoundException
 */

@CheckForNull
public static JavaClass getOuterClass(JavaClass obj) throws ClassNotFoundException {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof InnerClasses) {
            for (InnerClass ic : ((InnerClasses) a).getInnerClasses()) {
                if (obj.getClassNameIndex() == ic.getInnerClassIndex()) {
                    // System.out.println("Outer class is " +
                    // ic.getOuterClassIndex());
                    ConstantClass oc = (ConstantClass) obj.getConstantPool().getConstant(ic.getOuterClassIndex());
                    String ocName = oc.getBytes(obj.getConstantPool());
                    return Repository.lookupClass(ocName);
                }
            }
        }
    }
    return null;
}
 
Example 6
@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 7
Source Project: spotbugs   Source File: OpcodeStack.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void pushByConstant(DismantleBytecode dbc, Constant c) {

        if (c instanceof ConstantClass) {
            push(new Item("Ljava/lang/Class;", ((ConstantClass) c).getConstantValue(dbc.getConstantPool())));
        } else if (c instanceof ConstantInteger) {
            push(new Item("I", Integer.valueOf(((ConstantInteger) c).getBytes())));
        } else if (c instanceof ConstantString) {
            int s = ((ConstantString) c).getStringIndex();
            push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
        } else if (c instanceof ConstantFloat) {
            push(new Item("F", Float.valueOf(((ConstantFloat) c).getBytes())));
        } else if (c instanceof ConstantDouble) {
            push(new Item("D", Double.valueOf(((ConstantDouble) c).getBytes())));
        } else if (c instanceof ConstantLong) {
            push(new Item("J", Long.valueOf(((ConstantLong) c).getBytes())));
        } else {
            throw new UnsupportedOperationException("StaticConstant type not expected");
        }
    }
 
Example 8
/**
 * 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 9
Source Project: commons-bcel   Source File: listclass.java    License: 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 10
Source Project: commons-bcel   Source File: Pass3aVerifier.java    License: Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
// LDC and LDC_W (LDC_W is a subclass of LDC in BCEL's model)
@Override
public void visitLDC(final LDC ldc) {
    indexValid(ldc, ldc.getIndex());
    final Constant c = constantPoolGen.getConstant(ldc.getIndex());
    if (c instanceof ConstantClass) {
      addMessage("Operand of LDC or LDC_W is CONSTANT_Class '"+c+"' - this is only supported in JDK 1.5 and higher.");
    }
    else{
      if (! ( (c instanceof ConstantInteger)    ||
              (c instanceof ConstantFloat)         ||
        (c instanceof ConstantString) ) ) {
    constraintViolated(ldc,
        "Operand of LDC or LDC_W must be one of CONSTANT_Integer, CONSTANT_Float or CONSTANT_String, but is '"+c+"'.");
      }
    }
}
 
Example 11
Source Project: commons-bcel   Source File: Pass3aVerifier.java    License: Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitNEW(final NEW o) {
    indexValid(o, o.getIndex());
    final Constant c = constantPoolGen.getConstant(o.getIndex());
    if (!    (c instanceof ConstantClass)) {
        constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'.");
    }
    else{
        final ConstantUtf8 cutf8 = (ConstantUtf8) (constantPoolGen.getConstant( ((ConstantClass) c).getNameIndex() ));
        final Type t = Type.getType("L"+cutf8.getBytes()+";");
        if (t instanceof ArrayType) {
            constraintViolated(o, "NEW must not be used to create an array.");
        }
    }

}
 
Example 12
Source Project: commons-bcel   Source File: Pass3aVerifier.java    License: Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitMULTIANEWARRAY(final MULTIANEWARRAY o) {
    indexValid(o, o.getIndex());
    final Constant c = constantPoolGen.getConstant(o.getIndex());
    if (!    (c instanceof ConstantClass)) {
        constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'.");
    }
    final int dimensions2create = o.getDimensions();
    if (dimensions2create < 1) {
        constraintViolated(o, "Number of dimensions to create must be greater than zero.");
    }
    final Type t = o.getType(constantPoolGen);
    if (t instanceof ArrayType) {
        final int dimensions = ((ArrayType) t).getDimensions();
        if (dimensions < dimensions2create) {
            constraintViolated(o,
                "Not allowed to create array with more dimensions ('"+dimensions2create+
                "') than the one referenced by the CONSTANT_Class '"+t+"'.");
        }
    }
    else{
        constraintViolated(o, "Expecting a CONSTANT_Class referencing an array type."+
            " [Constraint not found in The Java Virtual Machine Specification, Second Edition, 4.8.1]");
    }
}
 
Example 13
Source Project: commons-bcel   Source File: Pass3aVerifier.java    License: Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitANEWARRAY(final ANEWARRAY o) {
    indexValid(o, o.getIndex());
    final Constant c = constantPoolGen.getConstant(o.getIndex());
    if (!    (c instanceof ConstantClass)) {
        constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'.");
    }
    final Type t = o.getType(constantPoolGen);
    if (t instanceof ArrayType) {
        final int dimensions = ((ArrayType) t).getDimensions();
        if (dimensions > Const.MAX_ARRAY_DIMENSIONS) {
            constraintViolated(o,
                "Not allowed to create an array with more than "+ Const.MAX_ARRAY_DIMENSIONS + " dimensions;"+
                " actual: " + dimensions);
        }
    }
}
 
Example 14
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: 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 15
Source Project: commons-bcel   Source File: ExecutionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** Symbolically executes the corresponding Java Virtual Machine instruction. */
@Override
public void visitLDC(final LDC o) {
    final Constant c = cpg.getConstant(o.getIndex());
    if (c instanceof ConstantInteger) {
        stack().push(Type.INT);
    }
    if (c instanceof ConstantFloat) {
        stack().push(Type.FLOAT);
    }
    if (c instanceof ConstantString) {
        stack().push(Type.STRING);
    }
    if (c instanceof ConstantClass) {
        stack().push(Type.CLASS);
    }
}
 
Example 16
Source Project: commons-bcel   Source File: ExecutionVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** Symbolically executes the corresponding Java Virtual Machine instruction. */
public void visitLDC_W(final LDC_W o) {
    final Constant c = cpg.getConstant(o.getIndex());
    if (c instanceof ConstantInteger) {
        stack().push(Type.INT);
    }
    if (c instanceof ConstantFloat) {
        stack().push(Type.FLOAT);
    }
    if (c instanceof ConstantString) {
        stack().push(Type.STRING);
    }
    if (c instanceof ConstantClass) {
        stack().push(Type.CLASS);
    }
}
 
Example 17
Source Project: commons-bcel   Source File: InstConstraintVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitCHECKCAST(final CHECKCAST o) {
    // The objectref must be of type reference.
    final Type objectref = stack().peek(0);
    if (!(objectref instanceof ReferenceType)) {
        constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+".");
    }
    //else{
    //    referenceTypeIsInitialized(o, (ReferenceType) objectref);
    //}
    // The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the
    // current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant
    // pool item at the index must be a symbolic reference to a class, array, or interface type.
    final Constant c = cpg.getConstant(o.getIndex());
    if (! (c instanceof ConstantClass)) {
        constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'.");
    }
}
 
Example 18
Source Project: commons-bcel   Source File: InstConstraintVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitINSTANCEOF(final INSTANCEOF o) {
    // The objectref must be of type reference.
    final Type objectref = stack().peek(0);
    if (!(objectref instanceof ReferenceType)) {
        constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+".");
    }
    //else{
    //    referenceTypeIsInitialized(o, (ReferenceType) objectref);
    //}
    // The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the
    // current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant
    // pool item at the index must be a symbolic reference to a class, array, or interface type.
    final Constant c = cpg.getConstant(o.getIndex());
    if (! (c instanceof ConstantClass)) {
        constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'.");
    }
}
 
Example 19
Source Project: commons-bcel   Source File: ClassLoader.java    License: 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 20
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: Apache License 2.0 5 votes vote down vote up
private static ClassSymbol makeSymbol(
    ConstantClass constantClass, ConstantPool constantPool, JavaClass sourceClass) {
  int nameIndex = constantClass.getNameIndex();
  Constant classNameConstant = constantPool.getConstant(nameIndex);
  if (!(classNameConstant instanceof ConstantUtf8)) {
    // This constant_pool entry must be a CONSTANT_Utf8_info
    // as specified https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.1
    throw new ClassFormatException(
        "Failed to lookup ConstantUtf8 constant indexed at "
            + nameIndex
            + ". However, the content is not ConstantUtf8. It is "
            + classNameConstant);
  }
  ConstantUtf8 classNameConstantUtf8 = (ConstantUtf8) classNameConstant;
  // classNameConstantUtf8 has internal form of class names that uses '.' to separate identifiers
  String targetClassNameInternalForm = classNameConstantUtf8.getBytes();
  // Adjust the internal form to comply with binary names defined in JLS 13.1
  String targetClassName = targetClassNameInternalForm.replace('/', '.');
  String superClassName = sourceClass.getSuperclassName();

  // Relationships between superclass and subclass need special validation for 'final' keyword
  boolean referenceIsForInheritance = superClassName.equals(targetClassName);
  if (referenceIsForInheritance) {
    return new SuperClassSymbol(targetClassName);
  }
  return new ClassSymbol(targetClassName);
}
 
Example 21
public void printOpCode(int seen) {
    System.out.print("  " + this.getClass().getSimpleName() + ": [" + formatter.format(getPC()) + "]  " + Const.getOpcodeName(seen));
    if ((seen == Const.INVOKEVIRTUAL) || (seen == Const.INVOKESPECIAL) || (seen == Const.INVOKEINTERFACE) || (seen == Const.INVOKESTATIC)) {
        System.out.print("   " + getClassConstantOperand() + "." + getNameConstantOperand() + " " + getSigConstantOperand());
    } else if (seen == Const.LDC || seen == Const.LDC_W || seen == Const.LDC2_W) {
        Constant c = getConstantRefOperand();
        if (c instanceof ConstantString) {
            System.out.print("   \"" + getStringConstantOperand() + "\"");
        } else if (c instanceof ConstantClass) {
            System.out.print("   " + getClassConstantOperand());
        } else {
            System.out.print("   " + c);
        }
    } else if ((seen == Const.ALOAD) || (seen == Const.ASTORE)) {
        System.out.print("   " + getRegisterOperand());
    } else if ((seen == Const.GOTO) || (seen == Const.GOTO_W) || (seen == Const.IF_ACMPEQ) || (seen == Const.IF_ACMPNE)
            || (seen == Const.IF_ICMPEQ)
            || (seen == Const.IF_ICMPGE) || (seen == Const.IF_ICMPGT) || (seen == Const.IF_ICMPLE) || (seen == Const.IF_ICMPLT)
            || (seen == Const.IF_ICMPNE) || (seen == Const.IFEQ) || (seen == Const.IFGE) || (seen == Const.IFGT) || (seen == Const.IFLE)
            || (seen == Const.IFLT)
            || (seen == Const.IFNE) || (seen == Const.IFNONNULL) || (seen == Const.IFNULL)) {
        System.out.print("   " + getBranchTarget());
    } else if ((seen == Const.NEW) || (seen == Const.INSTANCEOF)) {
        System.out.print("   " + getClassConstantOperand());
    } else if ((seen == Const.TABLESWITCH) || (seen == Const.LOOKUPSWITCH)) {
        System.out.print("    [");
        int switchPC = getPC();
        int[] offsets = getSwitchOffsets();
        for (int offset : offsets) {
            System.out.print((switchPC + offset) + ",");
        }
        System.out.print((switchPC + getDefaultSwitchOffset()) + "]");
    }

    System.out.println();
}
 
Example 22
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 23
Source Project: spotbugs   Source File: Util.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull CodeException getSurroundingTryBlock(ConstantPool constantPool, Code code,
        @CheckForNull String vmNameOfExceptionClass, int pc) {
    int size = Integer.MAX_VALUE;
    if (code.getExceptionTable() == null) {
        return null;
    }
    CodeException result = null;
    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;
                result = catchBlock;
            }
        }
    }
    return result;
}
 
Example 24
@Override
public void visitClass(ClassDescriptor classDescriptor) throws CheckedAnalysisException {
    IAnalysisCache analysisCache = Global.getAnalysisCache();

    ObligationFactory factory = database.getFactory();

    JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, classDescriptor);
    for (Constant c : jclass.getConstantPool().getConstantPool()) {
        if (c instanceof ConstantNameAndType) {
            ConstantNameAndType cnt = (ConstantNameAndType) c;
            String signature = cnt.getSignature(jclass.getConstantPool());
            if (factory.signatureInvolvesObligations(signature)) {
                super.visitClass(classDescriptor);
                return;
            }
        } else if (c instanceof ConstantClass) {
            String className = ((ConstantClass) c).getBytes(jclass.getConstantPool());
            if (factory.signatureInvolvesObligations(className)) {
                super.visitClass(classDescriptor);
                return;
            }
        }
    }
    if (DEBUG) {
        System.out.println(classDescriptor + " isn't interesting for obligation analysis");
    }
}
 
Example 25
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass jclass = classContext.getJavaClass();

    // We can ignore classes that were compiled for anything
    // less than JDK 1.5. This should avoid lots of unnecessary work
    // when analyzing code for older VM targets.
    if (BCELUtil.preTiger(jclass)) {
        return;
    }

    boolean sawUtilConcurrentLocks = false;
    for (Constant c : jclass.getConstantPool().getConstantPool()) {
        if (c instanceof ConstantMethodref) {
            ConstantMethodref m = (ConstantMethodref) c;
            ConstantClass cl = (ConstantClass) jclass.getConstantPool().getConstant(m.getClassIndex());
            ConstantUtf8 name = (ConstantUtf8) jclass.getConstantPool().getConstant(cl.getNameIndex());
            String nameAsString = name.getBytes();
            if (nameAsString.startsWith("java/util/concurrent/locks")) {
                sawUtilConcurrentLocks = true;
            }

        }
    }
    if (sawUtilConcurrentLocks) {
        super.visitClassContext(classContext);
    }
}
 
Example 26
Source Project: spotbugs   Source File: OpcodeStack.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
    if (e.getCatchType() == 0) {
        return "Ljava/lang/Throwable;";
    }
    Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
    if (c instanceof ConstantClass) {
        return "L" + ((ConstantClass) c).getBytes(dbc.getConstantPool()) + ";";
    }
    return "Ljava/lang/Throwable;";
}
 
Example 27
static private Item getItem(StackMapType t) {

        switch (t.getType()) {

        case Const.ITEM_Double:
            return Item.typeOnly("D");
        case Const.ITEM_Float:
            return Item.typeOnly("F");
        case Const.ITEM_Integer:
            return Item.typeOnly("I");
        case Const.ITEM_Long:
            return Item.typeOnly("J");
        case Const.ITEM_Bogus:
        case Const.ITEM_NewObject:
            return Item.typeOnly("Ljava/lang/Object;");
        case Const.ITEM_Null:
            Item it = new Item();
            it.setSpecialKind(Item.TYPE_ONLY);
            return it;
        case Const.ITEM_InitObject:
            return Item.typeOnly("Ljava/lang/Object;");
        case Const.ITEM_Object:
            int index = t.getIndex();
            ConstantClass c = (ConstantClass) t.getConstantPool().getConstant(index);
            String name = c.getBytes(t.getConstantPool());
            if (name.charAt(0) != '[') {
                name = "L" + name + ";";
            }
            return Item.typeOnly(name);
        default:
            throw new IllegalArgumentException("Bad item type: " + t.getType());

        }
    }
 
Example 28
Source Project: commons-bcel   Source File: helloify.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Change class name to <old_name>_hello
 */
private static void helloifyClassName(final JavaClass java_class) {
    class_name = java_class.getClassName() + "_hello";
    int index = java_class.getClassNameIndex();

    index = ((ConstantClass) cp.getConstant(index)).getNameIndex();
    cp.setConstant(index, new ConstantUtf8(class_name.replace('.', '/')));
}
 
Example 29
Source Project: commons-bcel   Source File: Package.java    License: 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 30
Source Project: commons-bcel   Source File: ConstantPoolGen.java    License: Apache License 2.0 5 votes vote down vote up
private int addClass_( final String clazz ) {
    int ret;
    if ((ret = lookupClass(clazz)) != -1) {
        return ret; // Already in CP
    }
    adjustSize();
    final ConstantClass c = new ConstantClass(addUtf8(clazz));
    ret = index;
    constants[index++] = c;
    if (!classTable.containsKey(clazz)) {
        classTable.put(clazz, new Index(ret));
    }
    return ret;
}