Java Code Examples for org.apache.bcel.classfile.JavaClass#getFields()

The following examples show how to use org.apache.bcel.classfile.JavaClass#getFields() . 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: UnsafeJacksonDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();
    if (OBJECT_MAPPER_CLASSES.contains(javaClass.getClassName())) {
        return;
    }
    for (Field field : javaClass.getFields()) {
        analyzeField(field, javaClass);
    }
    for (Method m : javaClass.getMethods()) {
        try {
            analyzeMethod(m, classContext);
        }
        catch (CFGBuilderException | DataflowAnalysisException e) {
        }
    }
}
 
Example 2
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 visitGETSTATIC(final GETSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 3
Source File: id.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example 4
Source File: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isJSP(JavaClass javaClass) {
    @DottedClassName
    String className = javaClass.getClassName();
    if (className.endsWith("_jsp") || className.endsWith("_tag")) {
        return true;
    }
    for (Method m : javaClass.getMethods()) {
        if (m.getName().startsWith("_jsp")) {
            return true;
        }
    }

    for (Field f : javaClass.getFields()) {
        if (f.getName().startsWith("_jsp")) {
            return true;
        }
    }
    return Subtypes2.instanceOf(className, "javax.servlet.jsp.JspPage")
            || Subtypes2.instanceOf(className, "org.apache.jasper.runtime.HttpJspBase")
            || Subtypes2.instanceOf(className, "javax.servlet.jsp.tagext.SimpleTagSupport")
            || Subtypes2.instanceOf(className, " org.apache.jasper.runtime.JspSourceDependent");
}
 
Example 5
Source File: ComparatorIdiom.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(JavaClass obj) {

    if (Subtypes2.instanceOf(obj, "java.util.Comparator") && !ClassName.isLocalOrAnonymous(getClassName())
            && !Subtypes2.instanceOf(obj, "java.io.Serializable")) {
        int priority = NORMAL_PRIORITY;
        if (obj.isInterface() || obj.isAbstract()) {
            return;
        }

        double easilySerializable = 1.0;
        for (Field f : obj.getFields()) {
            try {
                if (f.getName().startsWith("this$")) {
                    return;
                }
                String signature = f.getSignature();
                char firstChar = signature.charAt(0);
                if (firstChar == 'L' || firstChar == '[') {
                    easilySerializable *= DeepSubtypeAnalysis.isDeepSerializable(signature);
                }
            } catch (ClassNotFoundException e) {
                easilySerializable = 0.0;
                break;
            }
        }

        if (easilySerializable < 0.9) {
            priority = LOW_PRIORITY;
        }

        bugReporter.reportBug(new BugInstance(this, "SE_COMPARATOR_SHOULD_BE_SERIALIZABLE", priority).addClass(this));

    }

}
 
Example 6
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static @CheckForNull String getSignatureOfOuterClass(JavaClass obj) {
    for (Field f : obj.getFields()) {
        if (f.getName().startsWith("this$")) {
            return f.getSignature();
        }
    }
    return null;
}
 
Example 7
Source File: Class2HTML.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Write contents of the given JavaClass into HTML files.
 *
 * @param java_class The class to write
 * @param dir The directory to put the files in
 */
public Class2HTML(final JavaClass java_class, final String dir) throws IOException {
    final Method[] methods = java_class.getMethods();
    this.java_class = java_class;
    this.dir = dir;
    class_name = java_class.getClassName(); // Remember full name
    constant_pool = java_class.getConstantPool();
    // Get package name by tacking off everything after the last `.'
    final int index = class_name.lastIndexOf('.');
    if (index > -1) {
        class_package = class_name.substring(0, index);
    } else {
        class_package = ""; // default package
    }
    final ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods,
            constant_pool);
    /* Attributes can't be written in one step, so we just open a file
     * which will be written consequently.
     */
    final AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool,
            constant_html);
    new MethodHTML(dir, class_name, methods, java_class.getFields(),
            constant_html, attribute_html);
    // Write main file (with frames, yuk)
    writeMainHTML(attribute_html);
    new CodeHTML(dir, class_name, methods, constant_pool, constant_html);
    attribute_html.close();
}
 
Example 8
Source File: FieldAnnotationsTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void checkAnnotatedField(final JavaClass clazz, final String fieldname,
        final String AnnotationEntryName, final String AnnotationEntryElementName,
        final String AnnotationEntryElementValue)
{
    final Field[] fields = clazz.getFields();
    for (final Field f : fields) {
        final AnnotationEntry[] fieldAnnotationEntrys = f.getAnnotationEntries();
        if (f.getName().equals(fieldname))
        {
            checkAnnotationEntry(fieldAnnotationEntrys[0], AnnotationEntryName,
                    AnnotationEntryElementName, AnnotationEntryElementValue);
        }
    }
}
 
Example 9
Source File: HiddenInheritedFieldCheck.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aJavaClass)
{
    final JavaClass javaClass = (JavaClass) aJavaClass;
    final String className = javaClass.getClassName();
    final JavaClass[] superClasses = javaClass.getSuperClasses();
    final Field[] fields = javaClass.getFields();
    // Check all fields
    for (int i = 0; i < fields.length; i++) {
        final Field field = fields[i];
        // Go through all superclasses
        for (int j = 0; j < superClasses.length; j++) {
            final JavaClass superClass = superClasses[j];
            final String superClassName = superClass.getClassName();
            final Field[] superClassFields = superClass.getFields();
            // Go through the filds of the superclasses
            for (int k = 0; k < superClassFields.length; k++) {
                final Field superClassField = superClassFields[k];
                if (!superClassField.isPrivate() &&
                    superClassField.getName().equals(field.getName()) &&
                    !ignore(className, field)) {
                    log(
                        javaClass,
                        0,
                        "hidden.inherited.field",
                        new Object[] {fields[i], superClassName});
                }
            }
        }
    }
}
 
Example 10
Source File: JavaClassDefinition.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a JavaClassDefinition from a JavaClass. The fields and
 * methods of the JavaClassDefinition are those whose scopes are
 * in restricted sets of Scopes.
 * @param aJavaClass the JavaClass for the definition.
 * @param aFieldScopes the restricted set of field scopes.
 * @param aMethodScopes the restriced set of method scopes.
 */
public JavaClassDefinition(
    JavaClass aJavaClass,
    Set aFieldScopes,
    Set aMethodScopes)
{
    mJavaClass = aJavaClass;

    // create method definitions, restricted by scope
    final Method[] methods = aJavaClass.getMethods();
    final Set methodSet = new HashSet();
    mMethodDefs = new MethodDefinition[methods.length];
    for (int i = 0; i < methods.length; i++) {
        if (Utils.inScope(methods[i], aMethodScopes)) {
            methodSet.add(new MethodDefinition(methods[i]));
        }
    }
    mMethodDefs =
        (MethodDefinition[]) methodSet.toArray(
            new MethodDefinition[methodSet.size()]);

    // create field definitions, restricted by scope
    final Field[] fields = aJavaClass.getFields();
    mFieldDefs = new HashMap(fields.length);
    for (int i = 0; i < fields.length; i++) {
        if (Utils.inScope(fields[i], aFieldScopes)) {
            mFieldDefs.put(
                fields[i].getName(),
                new FieldDefinition(fields[i]));
        }
    }
}
 
Example 11
Source File: ClassGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize with existing class.
 * @param clazz JavaClass object (e.g. read from file)
 */
public ClassGen(final JavaClass clazz) {
    super(clazz.getAccessFlags());
    classNameIndex = clazz.getClassNameIndex();
    superclass_name_index = clazz.getSuperclassNameIndex();
    className = clazz.getClassName();
    superClassName = clazz.getSuperclassName();
    fileName = clazz.getSourceFileName();
    cp = new ConstantPoolGen(clazz.getConstantPool());
    major = clazz.getMajor();
    minor = clazz.getMinor();
    final Attribute[] attributes = clazz.getAttributes();
    // J5TODO: Could make unpacking lazy, done on first reference
    final AnnotationEntryGen[] annotations = unpackAnnotations(attributes);
    final Method[] methods = clazz.getMethods();
    final Field[] fields = clazz.getFields();
    final String[] interfaces = clazz.getInterfaceNames();
    for (final String interface1 : interfaces) {
        addInterface(interface1);
    }
    for (final Attribute attribute : attributes) {
        if (!(attribute instanceof Annotations)) {
            addAttribute(attribute);
        }
    }
    for (final AnnotationEntryGen annotation : annotations) {
        addAnnotationEntry(annotation);
    }
    for (final Method method : methods) {
        addMethod(method);
    }
    for (final Field field : fields) {
        addField(field);
    }
}
 
Example 12
Source File: InstConstraintVisitor.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitPUTSTATIC(PUTSTATIC o){
	String field_name = o.getFieldName(cpg);
	JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
	Field[] fields = jc.getFields();
	Field f = null;
	for (int i=0; i<fields.length; i++){
		if (fields[i].getName().equals(field_name)){
			f = fields[i];
			break;
		}
	}
	if (f == null){
		throw new AssertionViolatedException("Field not found?!?");
	}
	Type value = stack().peek();
	Type t = Type.getType(f.getSignature());
	Type shouldbe = t;
	if (shouldbe == Type.BOOLEAN ||
			shouldbe == Type.BYTE ||
			shouldbe == Type.CHAR ||
			shouldbe == Type.SHORT){
		shouldbe = Type.INT;
	}
	if (t instanceof ReferenceType){
		ReferenceType rvalue = null;
		if (value instanceof ReferenceType){
			rvalue = (ReferenceType) value;
			referenceTypeIsInitialized(o, rvalue);
		}
		else{
			constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
		}
		// TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
		// using "wider cast object types" created during verification.
		// Comment it out if you encounter problems. See also the analogon at visitPUTFIELD.
		if (!(rvalue.isAssignmentCompatibleWith(shouldbe))){
			constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
		}
	}
	else{
		if (shouldbe != value){
			constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
		}
	}
	// TODO: Interface fields may be assigned to only once. (Hard to implement in
	//       JustIce's execution model). This may only happen in <clinit>, see Pass 3a.
}
 
Example 13
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    String name = obj.getClassName();
    String[] parts = name.split("[$+.]");
    baseClassName = parts[parts.length - 1];
    for (String p : name.split("[.]")) {
        if (p.length() == 1) {
            return;
        }
    }
    if (name.indexOf("Proto$") >= 0) {
        return;
    }
    classIsPublicOrProtected = obj.isPublic() || obj.isProtected();
    if (Character.isLetter(baseClassName.charAt(0)) && !Character.isUpperCase(baseClassName.charAt(0))
            && baseClassName.indexOf('_') == -1) {
        int priority = classIsPublicOrProtected ? NORMAL_PRIORITY : LOW_PRIORITY;

        bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NAMING_CONVENTION", priority).addClass(this));
    }
    if (name.endsWith("Exception")) {
        // Does it ultimately inherit from Throwable?
        if (!mightInheritFromException(DescriptorFactory.createClassDescriptor(obj))) {
            // It doens't, so the name is misleading
            bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NOT_EXCEPTION", NORMAL_PRIORITY).addClass(this));
        }
    }

    int badFieldNames = 0;
    for (Field f : obj.getFields()) {
        if (f.getName().length() >= 2 && badFieldName(f)) {
            badFieldNames++;
        }
    }
    hasBadFieldNames = badFieldNames > 3 && badFieldNames > obj.getFields().length / 3;
    int badMethodNames = 0;
    for (Method m : obj.getMethods()) {
        if (badMethodName(m.getName())) {
            badMethodNames++;
        }
    }
    hasBadMethodNames = badMethodNames > 3 && badMethodNames > obj.getMethods().length / 3;
    isEclipseNLS = "org.eclipse.osgi.util.NLS".equals(obj.getSuperclassName());
    super.visit(obj);
}
 
Example 14
Source File: FindMaskedFields.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    classFields.clear();

    Field[] fields = obj.getFields();
    String fieldName;
    for (Field field : fields) {
        if (!field.isStatic() && !field.isPrivate()) {
            fieldName = field.getName();
            classFields.put(fieldName, field);
        }
    }

    // Walk up the super class chain, looking for name collisions

    XClass c = getXClass();
    while (true) {
        ClassDescriptor s = c.getSuperclassDescriptor();
        if (s == null || "java/lang/Object".equals(s.getClassName())) {
            break;
        }
        try {
            c = Global.getAnalysisCache().getClassAnalysis(XClass.class, s);
        } catch (CheckedAnalysisException e) {
            break;
        }

        for (XField fld : c.getXFields()) {
            if (!fld.isStatic() && (fld.isPublic() || fld.isProtected())) {
                fieldName = fld.getName();
                if (fieldName.length() == 1) {
                    continue;
                }
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                String superClassName = s.getClassName();
                if (superClassName.startsWith("java/io")
                        && (superClassName.endsWith("InputStream") && "in".equals(fieldName) || superClassName
                                .endsWith("OutputStream") && "out".equals(fieldName))) {
                    continue;
                }
                if (classFields.containsKey(fieldName)) {
                    Field maskingField = classFields.get(fieldName);
                    String mClassName = getDottedClassName();
                    FieldAnnotation fa = new FieldAnnotation(mClassName, maskingField.getName(), maskingField.getSignature(),
                            maskingField.isStatic());
                    int priority = NORMAL_PRIORITY;
                    if (maskingField.isStatic() || maskingField.isFinal()) {
                        priority++;
                    } else if (fld.getSignature().charAt(0) == 'L' && !fld.getSignature().startsWith("Ljava/lang/")
                            || fld.getSignature().charAt(0) == '[') {
                        priority--;
                    }
                    if (!fld.getSignature().equals(maskingField.getSignature())) {
                        priority += 2;
                    } else if (fld.getAccessFlags() != maskingField.getAccessFlags()) {
                        priority++;
                    }
                    if (fld.isSynthetic() || fld.getName().indexOf('$') >= 0) {
                        priority++;
                    }

                    FieldAnnotation maskedFieldAnnotation = FieldAnnotation.fromFieldDescriptor(fld.getFieldDescriptor());
                    BugInstance bug = new BugInstance(this, "MF_CLASS_MASKS_FIELD", priority).addClass(this).addField(fa)
                            .describe("FIELD_MASKING").addField(maskedFieldAnnotation).describe("FIELD_MASKED");
                    rememberedBugs.add(new RememberedBug(bug, fa, maskedFieldAnnotation));

                }
            }
        }
    }

    super.visit(obj);
}
 
Example 15
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitPUTSTATIC(final PUTSTATIC o) {
    try {
    final String field_name = o.getFieldName(cpg);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
                final Type f_type = Type.getType(field.getSignature());
              final Type o_type = o.getType(cpg);
                /* TODO: Check if assignment compatibility is sufficient.
               * What does Sun do?
               */
              if (f_type.equals(o_type)) {
                    f = field;
                    break;
                }
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }
    final Type value = stack().peek();
    final Type t = Type.getType(f.getSignature());
    Type shouldbe = t;
    if (shouldbe == Type.BOOLEAN ||
            shouldbe == Type.BYTE ||
            shouldbe == Type.CHAR ||
            shouldbe == Type.SHORT) {
        shouldbe = Type.INT;
    }
    if (t instanceof ReferenceType) {
        ReferenceType rvalue = null;
        if (value instanceof ReferenceType) {
            rvalue = (ReferenceType) value;
            referenceTypeIsInitialized(o, rvalue);
        }
        else{
            constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
        }
        // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
        // using "wider cast object types" created during verification.
        // Comment it out if you encounter problems. See also the analogon at visitPUTFIELD.
        if (!(rvalue.isAssignmentCompatibleWith(shouldbe))) {
            constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
        }
    }
    else{
        if (shouldbe != value) {
            constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
        }
    }
    // TODO: Interface fields may be assigned to only once. (Hard to implement in
    //       JustIce's execution model). This may only happen in <clinit>, see Pass 3a.

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 16
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitPUTFIELD(final PUTFIELD o) {
    try {

    final Type objectref = stack().peek(1);
    if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ) {
        constraintViolated(o,
            "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'.");
    }

    final String field_name = o.getFieldName(cpg);

    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
              final Type f_type = Type.getType(field.getSignature());
              final Type o_type = o.getType(cpg);
                /* TODO: Check if assignment compatibility is sufficient.
               * What does Sun do?
               */
              if (f_type.equals(o_type)) {
                    f = field;
                    break;
                }
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    final Type value = stack().peek();
    final Type t = Type.getType(f.getSignature());
    Type shouldbe = t;
    if (shouldbe == Type.BOOLEAN ||
            shouldbe == Type.BYTE ||
            shouldbe == Type.CHAR ||
            shouldbe == Type.SHORT) {
        shouldbe = Type.INT;
    }
    if (t instanceof ReferenceType) {
        ReferenceType rvalue = null;
        if (value instanceof ReferenceType) {
            rvalue = (ReferenceType) value;
            referenceTypeIsInitialized(o, rvalue);
        }
        else{
            constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
        }
        // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
        // using "wider cast object types" created during verification.
        // Comment it out if you encounter problems. See also the analogon at visitPUTSTATIC.
        if (!(rvalue.isAssignmentCompatibleWith(shouldbe))) {
            constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
        }
    }
    else{
        if (shouldbe != value) {
            constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
        }
    }

    if (f.isProtected()) {
        final ObjectType classtype = getObjectType(o);
        final ObjectType curr = ObjectType.getInstance(mg.getClassName());

        if (    classtype.equals(curr) ||
                    curr.subclassOf(classtype)    ) {
            final Type tp = stack().peek(1);
            if (tp == Type.NULL) {
                return;
            }
            if (! (tp instanceof ObjectType) ) {
                constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+tp+"'.");
            }
            final ObjectType objreftype = (ObjectType) tp;
            if (! ( objreftype.equals(curr) ||
                        objreftype.subclassOf(curr) ) ) {
                constraintViolated(o,
                    "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or"+
                    " a superclass of the current class. However, the referenced object type '"+stack().peek()+
                    "' is not the current class or a subclass of the current class.");
            }
        }
    }

    // TODO: Could go into Pass 3a.
    if (f.isStatic()) {
        constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 17
Source File: BCELifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
@Override
public void visitJavaClass( final JavaClass clazz ) {
    String class_name = clazz.getClassName();
    final String super_name = clazz.getSuperclassName();
    final String package_name = clazz.getPackageName();
    final String inter = Utility.printArray(clazz.getInterfaceNames(), false, true);
    if (!"".equals(package_name)) {
        class_name = class_name.substring(package_name.length() + 1);
        _out.println("package " + package_name + ";");
        _out.println();
    }
    _out.println("import " + BASE_PACKAGE + ".generic.*;");
    _out.println("import " + BASE_PACKAGE + ".classfile.*;");
    _out.println("import " + BASE_PACKAGE + ".*;");
    _out.println("import java.io.*;");
    _out.println();
    _out.println("public class " + class_name + "Creator {");
    _out.println("  private InstructionFactory _factory;");
    _out.println("  private ConstantPoolGen    _cp;");
    _out.println("  private ClassGen           _cg;");
    _out.println();
    _out.println("  public " + class_name + "Creator() {");
    _out.println("    _cg = new ClassGen(\""
            + (("".equals(package_name)) ? class_name : package_name + "." + class_name)
            + "\", \"" + super_name + "\", " + "\"" + clazz.getSourceFileName() + "\", "
            + printFlags(clazz.getAccessFlags(), FLAGS.CLASS) + ", "
            + "new String[] { " + inter + " });");
    _out.println("    _cg.setMajor(" + clazz.getMajor() +");");
    _out.println("    _cg.setMinor(" + clazz.getMinor() +");");
    _out.println();
    _out.println("    _cp = _cg.getConstantPool();");
    _out.println("    _factory = new InstructionFactory(_cg, _cp);");
    _out.println("  }");
    _out.println();
    printCreate();
    final Field[] fields = clazz.getFields();
    if (fields.length > 0) {
        _out.println("  private void createFields() {");
        _out.println("    FieldGen field;");
        for (final Field field : fields) {
            field.accept(this);
        }
        _out.println("  }");
        _out.println();
    }
    final Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        _out.println("  private void createMethod_" + i + "() {");
        methods[i].accept(this);
        _out.println("  }");
        _out.println();
    }
    printMain();
    _out.println("}");
}
 
Example 18
Source File: InstConstraintVisitor.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
public void visitGETFIELD(GETFIELD o){
	Type objectref = stack().peek();
	if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ){
		constraintViolated(o, "Stack top should be an object reference that's not an array reference, but is '"+objectref+"'.");
	}
	
	String field_name = o.getFieldName(cpg);
	
	JavaClass jc = Repository.lookupClass(o.getClassType(cpg).getClassName());
	Field[] fields = jc.getFields();
	Field f = null;
	for (int i=0; i<fields.length; i++){
		if (fields[i].getName().equals(field_name)){
			f = fields[i];
			break;
		}
	}
	if (f == null){
		throw new AssertionViolatedException("Field not found?!?");
	}

	if (f.isProtected()){
		ObjectType classtype = o.getClassType(cpg);
		ObjectType curr = new ObjectType(mg.getClassName());

		if (	classtype.equals(curr) ||
					curr.subclassOf(classtype)	){
			Type t = stack().peek();
			if (t == Type.NULL){
				return;
			}
			if (! (t instanceof ObjectType) ){
				constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+t+"'.");
			}
			ObjectType objreftype = (ObjectType) t;
			if (! ( objreftype.equals(curr) ||
					    objreftype.subclassOf(curr) ) ){
				//TODO: One day move to Staerk-et-al's "Set of object types" instead of "wider" object types
				//      created during the verification.
				//      "Wider" object types don't allow us to check for things like that below.
				//constraintViolated(o, "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or a superclass of the current class. However, the referenced object type '"+stack().peek()+"' is not the current class or a subclass of the current class.");
			}
		} 
	}
	
	// TODO: Could go into Pass 3a.
	if (f.isStatic()){
		constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
	}
}
 
Example 19
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitPUTSTATIC(final PUTSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (f.isFinal()) {
        if (!(myOwner.getClassName().equals(getObjectType(o).getClassName()))) {
            constraintViolated(o,
                "Referenced field '"+f+"' is final and must therefore be declared in the current class '"+
                    myOwner.getClassName()+"' which is not the case: it is declared in '"+o.getReferenceType(constantPoolGen)+"'.");
        }
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }

    final String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[methodNo].getName();

    // If it's an interface, it can be set only in <clinit>.
    if ((!(jc.isClass())) && (!(meth_name.equals(Const.STATIC_INITIALIZER_NAME)))) {
        constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Const.STATIC_INITIALIZER_NAME+"' method.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 20
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an {@code Optional} describing the linkage error for the field reference if the
 * reference does not have a valid referent in the input class path; otherwise an empty {@code
 * Optional}.
 */
@VisibleForTesting
Optional<SymbolProblem> findSymbolProblem(ClassFile classFile, FieldSymbol symbol) {
  String sourceClassName = classFile.getBinaryName();
  String targetClassName = symbol.getClassBinaryName();

  String fieldName = symbol.getName();
  try {
    JavaClass targetJavaClass = classDumper.loadJavaClass(targetClassName);
    ClassPathEntry classFileLocation = classDumper.findClassLocation(targetClassName);
    ClassFile containingClassFile =
        classFileLocation == null ? null : new ClassFile(classFileLocation, targetClassName);

    if (!isClassAccessibleFrom(targetJavaClass, sourceClassName)) {
      return Optional.of(
          new SymbolProblem(symbol, ErrorType.INACCESSIBLE_CLASS, containingClassFile));
    }

    for (JavaClass javaClass : getClassHierarchy(targetJavaClass)) {
      for (Field field : javaClass.getFields()) {
        if (field.getName().equals(fieldName)) {
          if (!isMemberAccessibleFrom(javaClass, field, sourceClassName)) {
            return Optional.of(
                new SymbolProblem(symbol, ErrorType.INACCESSIBLE_MEMBER, containingClassFile));
          }
          // The field is found and accessible. Returning no error.
          return Optional.empty();
        }
      }
    }
    // The field was not found in the class from the classpath
    return Optional.of(
        new SymbolProblem(symbol, ErrorType.SYMBOL_NOT_FOUND, containingClassFile));
  } catch (ClassNotFoundException ex) {
    if (classDumper.catchesLinkageErrorOnClass(sourceClassName)) {
      return Optional.empty();
    }
    ClassSymbol classSymbol = new ClassSymbol(symbol.getClassBinaryName());
    return Optional.of(new SymbolProblem(classSymbol, ErrorType.CLASS_NOT_FOUND, null));
  }
}