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

The following examples show how to use org.apache.bcel.classfile.Constant. 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: uyuni   Source File: FindStrings.java    License: 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 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 3
Source Project: ApkToolPlus   Source File: InstConstraintVisitor.java    License: 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 4
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 5
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 6
/**
 * 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 7
@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 8
Source Project: spotbugs   Source File: DumbMethods.java    License: 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 9
@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 10
@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 11
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 12
Source Project: spacewalk   Source File: FindStrings.java    License: 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 13
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 14
Source Project: commons-bcel   Source File: InvokeInstruction.java    License: 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 15
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 16
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. */
// 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 17
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 18
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 19
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 20
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 21
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 22
Source Project: commons-bcel   Source File: InstConstraintVisitor.java    License: 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 23
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 24
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 25
Source Project: cloud-opensource-java   Source File: ClassDumper.java    License: 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 26
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 27
@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 28
Source Project: ApkToolPlus   Source File: InstructionList.java    License: Apache License 2.0 5 votes vote down vote up
/** Replace all references to the old constant pool with references to the new
  *  constant pool
  */
 public void replaceConstantPool(ConstantPoolGen old_cp, ConstantPoolGen new_cp) {
   for(InstructionHandle ih=start; ih != null; ih = ih.next) {
     Instruction i = ih.instruction;

     if(i instanceof CPInstruction) {
CPInstruction ci = (CPInstruction)i;
Constant      c  = old_cp.getConstant(ci.getIndex());
ci.setIndex(new_cp.addConstant(c, old_cp));
     }
   }    
 }
 
Example 29
Source Project: ApkToolPlus   Source File: ExecutionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/** Symbolically executes the corresponding Java Virtual Machine instruction. */ 
public void visitLDC(LDC o){
	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);
	}
}
 
Example 30
Source Project: ApkToolPlus   Source File: ExecutionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/** Symbolically executes the corresponding Java Virtual Machine instruction. */ 
public void visitLDC_W(LDC_W o){
	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);
	}
}