org.apache.bcel.classfile.Constant Java Examples

The following examples show how to use org.apache.bcel.classfile.Constant. 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: HugeSharedStringConstants.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(ConstantValue s) {
    if (!visitingField()) {
        return;
    }
    int i = s.getConstantValueIndex();
    Constant c = getConstantPool().getConstant(i);
    if (c instanceof ConstantString) {
        String value = ((ConstantString) c).getBytes(getConstantPool());
        if (value.length() < SIZE_OF_HUGE_CONSTANT) {
            return;
        }
        String key = getStringKey(value);
        definition.put(key, XFactory.createXField(this));
        stringSize.put(key, value.length());
    }

}
 
Example #2
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures the general preconditions of a FieldInstruction instance.
 */
 @Override
public void visitFieldInstruction(final FieldInstruction o) {
     // visitLoadClass(o) has been called before: Every FieldOrMethod
     // implements LoadClass.
     // visitCPInstruction(o) has been called before.
    // A FieldInstruction may be: GETFIELD, GETSTATIC, PUTFIELD, PUTSTATIC
        final Constant c = cpg.getConstant(o.getIndex());
        if (!(c instanceof ConstantFieldref)) {
            constraintViolated(o,
                "Index '"+o.getIndex()+"' should refer to a CONSTANT_Fieldref_info structure, but refers to '"+c+"'.");
        }
        // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).
        final Type t = o.getType(cpg);
        if (t instanceof ObjectType) {
            final String name = ((ObjectType)t).getClassName();
            final Verifier v = VerifierFactory.getVerifier( name );
            final VerificationResult vr = v.doPass2();
            if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
                constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
            }
        }
 }
 
Example #3
Source File: InstConstraintVisitor.java    From commons-bcel with 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 #4
Source File: InstConstraintVisitor.java    From commons-bcel with 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 #5
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 #6
Source File: ExecutionVisitor.java    From commons-bcel with 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 #7
Source File: InstConstraintVisitor.java    From ApkToolPlus with Apache License 2.0 6 votes vote down vote up
/**
* Ensures the general preconditions of a FieldInstruction instance.
*/
public void visitFieldInstruction(FieldInstruction o){
	// visitLoadClass(o) has been called before: Every FieldOrMethod
	// implements LoadClass.
	// visitCPInstruction(o) has been called before.
// A FieldInstruction may be: GETFIELD, GETSTATIC, PUTFIELD, PUTSTATIC 
	Constant c = cpg.getConstant(o.getIndex());
	if (!(c instanceof ConstantFieldref)){
		constraintViolated(o, "Index '"+o.getIndex()+"' should refer to a CONSTANT_Fieldref_info structure, but refers to '"+c+"'.");
	}
	// the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o).
	Type t = o.getType(cpg);
	if (t instanceof ObjectType){
		String name = ((ObjectType)t).getClassName();
		Verifier v = VerifierFactory.getVerifier( name );
		VerificationResult vr = v.doPass2();
		if (vr.getStatus() != VerificationResult.VERIFIED_OK){
			constraintViolated((Instruction) o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'.");
		}
	}
}
 
Example #8
Source File: InstConstraintVisitor.java    From ApkToolPlus with 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 #9
Source File: InstConstraintVisitor.java    From ApkToolPlus with 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 #10
Source File: ExecutionVisitor.java    From commons-bcel with 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 #11
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 #12
Source File: Pass3aVerifier.java    From commons-bcel with 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 #13
Source File: Pass3aVerifier.java    From commons-bcel with 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 #14
Source File: Pass3aVerifier.java    From commons-bcel with 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 #15
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
// LDC2_W
@Override
public void visitLDC2_W(final LDC2_W o) {
    indexValid(o, o.getIndex());
    final Constant c = constantPoolGen.getConstant(o.getIndex());
    if (! ( (c instanceof ConstantLong)    ||
                    (c instanceof ConstantDouble) ) ) {
        constraintViolated(o, "Operand of LDC2_W must be CONSTANT_Long or CONSTANT_Double, but is '"+c+"'.");
    }
    try{
        indexValid(o, o.getIndex()+1);
    }
    catch(final StaticCodeInstructionOperandConstraintException e) {
        throw new AssertionViolatedException("Does not BCEL handle that? LDC2_W operand has a problem.", e);
    }
}
 
Example #16
Source File: Pass3aVerifier.java    From commons-bcel with 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 #17
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 #18
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 #19
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 #20
Source File: FindRoughConstants.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (seen == Const.LDC || seen == Const.LDC_W || seen == Const.LDC2_W) {
        Constant c = getConstantRefOperand();
        if (c instanceof ConstantFloat) {
            checkConst(((ConstantFloat) c).getBytes());
        } else if (c instanceof ConstantDouble) {
            checkConst(((ConstantDouble) c).getBytes());
        }
        return;
    }
    // Lower priority if the constant is put into array immediately or after the boxing:
    // this is likely to be just similar number in some predefined dataset (like lookup table)
    if (seen == Const.INVOKESTATIC && lastBug != null) {
        if (getNextOpcode() == Const.AASTORE
                && getNameConstantOperand().equals("valueOf")
                && (getClassConstantOperand().equals("java/lang/Double") || getClassConstantOperand().equals(
                        "java/lang/Float"))) {
            lastBug = ((BugInstance) lastBug.clone());
            lastBug.setPriority(lastPriority + 1);
            bugAccumulator.forgetLastBug();
            bugAccumulator.accumulateBug(lastBug, this);
        }
    }
    lastBug = null;
}
 
Example #21
Source File: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field field) {
    ConstantValue value = field.getConstantValue();
    if (value == null) {
        return;
    }
    Constant c = getConstantPool().getConstant(value.getConstantValueIndex());

    if (testingEnabled && c instanceof ConstantLong && ((ConstantLong) c).getBytes() == MICROS_PER_DAY_OVERFLOWED_AS_INT) {
        bugReporter.reportBug(new BugInstance(this, "TESTING", HIGH_PRIORITY).addClass(this).addField(this)
                .addString("Did you mean MICROS_PER_DAY")
                .addInt(MICROS_PER_DAY_OVERFLOWED_AS_INT)
                .describe(IntAnnotation.INT_VALUE));

    }
}
 
Example #22
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 #23
Source File: OpcodeStack.java    From spotbugs with 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 #24
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 #25
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitLDC2_W(final LDC2_W o) {
    // visitCPInstruction is called first.

    final Constant c = cpg.getConstant(o.getIndex());
    if     (!    (    ( c instanceof ConstantLong) ||
                        ( c instanceof ConstantDouble )    )    ) {
        constraintViolated(o,
                "Referenced constant should be a CONSTANT_Integer, a CONSTANT_Float or a CONSTANT_String, but is '"+c+"'.");
    }
}
 
Example #26
Source File: OpcodeStack.java    From spotbugs with 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
Source File: UnnecessaryMath.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (state == SEEN_NOTHING) {
        if ((seen == Const.DCONST_0) || (seen == Const.DCONST_1)) {
            constValue = seen - Const.DCONST_0;
            state = SEEN_DCONST;
        } else if ((seen == Const.LDC2_W) || (seen == Const.LDC_W)) {
            state = SEEN_DCONST;
            Constant c = this.getConstantRefOperand();
            if (c instanceof ConstantDouble) {
                constValue = ((ConstantDouble) c).getBytes();
            } else if (c instanceof ConstantFloat) {
                constValue = ((ConstantFloat) c).getBytes();
            } else if (c instanceof ConstantLong) {
                constValue = ((ConstantLong) c).getBytes();
            } else {
                state = SEEN_NOTHING;
            }
        }
    } else if (state == SEEN_DCONST) {
        if (seen == Const.INVOKESTATIC) {
            state = SEEN_NOTHING;
            if ("java.lang.Math".equals(getDottedClassConstantOperand())) {
                String methodName = getNameConstantOperand();

                if (((constValue == 0.0) && zeroMethods.contains(methodName))
                        || ((constValue == 1.0) && oneMethods.contains(methodName)) || (anyMethods.contains(methodName))) {
                    bugReporter.reportBug(new BugInstance(this, "UM_UNNECESSARY_MATH", LOW_PRIORITY).addClassAndMethod(this)
                            .addSourceLine(this));
                }
            }
        }
        state = SEEN_NOTHING;
    }
}
 
Example #28
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitLDC(final LDC o) {
    // visitCPInstruction is called first.

    final Constant c = cpg.getConstant(o.getIndex());
    if     (!    (    ( c instanceof ConstantInteger) ||
                ( c instanceof ConstantFloat    )    ||
                ( c instanceof ConstantString    )    ||
                ( c instanceof ConstantClass    ) )    ) {
        constraintViolated(o,
            "Referenced constant should be a CONSTANT_Integer, a CONSTANT_Float, a CONSTANT_String or a CONSTANT_Class, but is '"+
             c + "'.");
    }
}
 
Example #29
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitLDC_W(final LDC_W o) {
    // visitCPInstruction is called first.

    final Constant c = cpg.getConstant(o.getIndex());
    if     (!    (    ( c instanceof ConstantInteger) ||
                ( c instanceof ConstantFloat    )    ||
                ( c instanceof ConstantString    )    ||
                ( c instanceof ConstantClass    ) )    ) {
        constraintViolated(o,
            "Referenced constant should be a CONSTANT_Integer, a CONSTANT_Float, a CONSTANT_String or a CONSTANT_Class, but is '"+
             c + "'.");
    }
}
 
Example #30
Source File: ExecutionVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** Symbolically executes the corresponding Java Virtual Machine instruction. */
@Override
public void visitLDC2_W(final LDC2_W o) {
    final Constant c = cpg.getConstant(o.getIndex());
    if (c instanceof ConstantLong) {
        stack().push(Type.LONG);
    }
    if (c instanceof ConstantDouble) {
        stack().push(Type.DOUBLE);
    }
}