org.apache.bcel.classfile.ConstantClass Java Examples

The following examples show how to use org.apache.bcel.classfile.ConstantClass. 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: Util.java    From spotbugs with GNU Lesser General Public License v2.1 7 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 #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: 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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
Source File: Pass2Verifier.java    From commons-bcel with 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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #20
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 #21
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitINSTANCEOF(final INSTANCEOF 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+"'.");
    }
}
 
Example #22
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitCHECKCAST(final CHECKCAST 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+"'.");
    }
}
 
Example #23
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 #24
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 #25
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantClass(final ConstantClass obj) {
    if (obj.getTag() != Const.CONSTANT_Class) {
        throw new ClassConstraintException("Wrong constant tag in '"+tostring(obj)+"'.");
    }
    checkIndex(obj, obj.getNameIndex(), CONST_Utf8);

}
 
Example #26
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantFieldref(final ConstantFieldref obj) {
    if (obj.getTag() != Const.CONSTANT_Fieldref) {
        throw new ClassConstraintException("ConstantFieldref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validFieldName(name)) {
        throw new ClassConstraintException("Invalid field name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

    final String sig  = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor)

    try{
        Type.getType(sig); /* Don't need the return value */
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }
}
 
Example #27
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantMethodref(final ConstantMethodref obj) {
    if (obj.getTag() != Const.CONSTANT_Methodref) {
        throw new ClassConstraintException("ConstantMethodref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validClassMethodName(name)) {
        throw new ClassConstraintException(
            "Invalid (non-interface) method name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

    final String sig  = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor)

    try{
        final Type   t  = Type.getReturnType(sig);
        if ( name.equals(Const.CONSTRUCTOR_NAME) && (t != Type.VOID) ) {
            throw new ClassConstraintException("Instance initialization method must have VOID return type.");
        }
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }
}
 
Example #28
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantInterfaceMethodref(final ConstantInterfaceMethodref obj) {
    if (obj.getTag() != Const.CONSTANT_InterfaceMethodref) {
        throw new ClassConstraintException("ConstantInterfaceMethodref '"+tostring(obj)+"' has wrong tag!");
    }
    final int name_and_type_index = obj.getNameAndTypeIndex();
    final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index));
    final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name
    if (!validInterfaceMethodName(name)) {
        throw new ClassConstraintException("Invalid (interface) method name '"+name+"' referenced by '"+tostring(obj)+"'.");
    }

    final int class_index = obj.getClassIndex();
    final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index));
    final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form
    if (! validClassName(className)) {
        throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'.");
    }

    final String sig  = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor)

    try{
        final Type   t  = Type.getReturnType(sig);
        if ( name.equals(Const.STATIC_INITIALIZER_NAME) && (t != Type.VOID) ) {
            addMessage("Class or interface initialization method '"+Const.STATIC_INITIALIZER_NAME+
                "' usually has VOID return type instead of '"+t+
                "'. Note this is really not a requirement of The Java Virtual Machine Specification, Second Edition.");
        }
    }
    catch (final ClassFormatException cfe) {
        throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe);
    }

}
 
Example #29
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/** This method casually visits ConstantClass references. */
@Override
public void visitConstantClass(final ConstantClass obj) {
    final Constant c = cp.getConstant(obj.getNameIndex());
    if (c instanceof ConstantUtf8) { //Ignore the case where it's not a ConstantUtf8 here, we'll find out later.
        final String classname = ((ConstantUtf8) c).getBytes();
        if (classname.startsWith(jc.getClassName().replace('.','/')+"$")) {
            hasInnerClass = true;
        }
    }
}
 
Example #30
Source File: ConstantPoolGen.java    From commons-bcel with 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;
}