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

The following examples show how to use org.apache.bcel.classfile.JavaClass#getSuperclassName() . 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: 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 2
Source File: UselessSubclassMethod.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    try {
        JavaClass cls = classContext.getJavaClass();
        superclassName = cls.getSuperclassName();
        JavaClass[] interfaces = null;
        if (cls.isClass() && ((cls.getAccessFlags() & Const.ACC_ABSTRACT) != 0)) {
            interfaces = cls.getAllInterfaces();
            interfaceMethods = new HashSet<>();
            for (JavaClass aInterface : interfaces) {
                Method[] infMethods = aInterface.getMethods();
                for (Method meth : infMethods) {
                    interfaceMethods.add(meth.getName() + meth.getSignature());
                }
            }
        }
    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
    super.visitClassContext(classContext);
}
 
Example 3
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 4
Source File: WicketEndpointDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();

    String superClassName = javaClass.getSuperclassName();
    if ("org.apache.wicket.markup.html.WebPage".equals(superClassName)) {
        bugReporter.reportBug(new BugInstance(this, WICKET_ENDPOINT_TYPE, Priorities.LOW_PRIORITY) //
                .addClass(javaClass));
        return;
    }
}
 
Example 5
Source File: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    String superclassName = obj.getSuperclassName();
    isSynthetic = "java.rmi.server.RemoteStub".equals(superclassName);
    Attribute[] attributes = obj.getAttributes();
    if (attributes != null) {
        for (Attribute a : attributes) {
            if (a instanceof Synthetic) {
                isSynthetic = true;
            }
        }
    }

}
 
Example 6
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitJavaClass(JavaClass obj) {
    if (BCELUtil.isSynthetic(obj)) {
        return;
    }
    String name = obj.getClassName();
    if (!visited.add(name)) {
        return;
    }

    String superClassName = obj.getSuperclassName();
    if (!Values.DOTTED_JAVA_LANG_OBJECT.equals(name)) {
        if (sameSimpleName(superClassName, name)) {
            bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", HIGH_PRIORITY).addClass(name)
                    .addClass(superClassName));
        }
        for (String interfaceName : obj.getInterfaceNames()) {
            if (sameSimpleName(interfaceName, name)) {
                bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_INTERFACE", NORMAL_PRIORITY).addClass(
                        name).addClass(interfaceName));
            }
        }
    }
    if (obj.isInterface()) {
        return;
    }

    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClassName) && !visited.contains(superClassName)) {
        try {
            visitJavaClass(obj.getSuperClass());
        } catch (ClassNotFoundException e) {
            // ignore it
        }
    }
    super.visitJavaClass(obj);
}
 
Example 7
Source File: RedundantInterfaces.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass obj = classContext.getJavaClass();

    String superClassName = obj.getSuperclassName();
    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClassName)) {
        return;
    }

    String[] interfaceNames = obj.getInterfaceNames();
    if ((interfaceNames == null) || (interfaceNames.length == 0)) {
        return;
    }

    try {
        JavaClass superObj = obj.getSuperClass();
        SortedSet<String> redundantInfNames = new TreeSet<>();

        for (String interfaceName : interfaceNames) {
            if (!"java.io.Serializable".equals(interfaceName)) {
                JavaClass inf = Repository.lookupClass(interfaceName);
                if (superObj.instanceOf(inf)) {
                    redundantInfNames.add(inf.getClassName());
                }
            }
        }

        if (redundantInfNames.size() > 0) {
            BugInstance bug = new BugInstance(this, "RI_REDUNDANT_INTERFACES", LOW_PRIORITY).addClass(obj);
            for (String redundantInfName : redundantInfNames) {
                bug.addClass(redundantInfName).describe("INTERFACE_TYPE");
            }

            bugReporter.reportBug(bug);
        }

    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
}
 
Example 8
Source File: MultithreadedInstanceAccess.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    try {
        JavaClass cls = classContext.getJavaClass();
        String superClsName = cls.getSuperclassName();
        if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClsName)) {
            return;
        }

        if (STRUTS_ACTION_NAME.equals(superClsName)) {
            mtClassName = STRUTS_ACTION_NAME;
            super.visitClassContext(classContext);
        } else if (SERVLET_NAME.equals(superClsName)) {
            mtClassName = SERVLET_NAME;
            super.visitClassContext(classContext);
        } else {
            for (JavaClass mtClass : getMtClasses()) {
                /*
                 * note: We could just call cls.instanceOf(mtClass) and it
                 * would work for both classes and interfaces, but if
                 * mtClass is an interface it is more efficient to call
                 * cls.implementationOf() and since we're doing this on each
                 * visit that's what we'll do. also note:
                 * implementationOf(mtClass) throws an
                 * IllegalArgumentException when mtClass is not an
                 * interface. See bug#1428253.
                 */
                if (mtClass.isClass() ? cls.instanceOf(mtClass) : cls.implementationOf(mtClass)) {
                    mtClassName = mtClass.getClassName();
                    super.visitClassContext(classContext);
                    return;
                }
            }
        }
    } catch (Exception e) {
        // already reported
    }
}
 
Example 9
Source File: UselessSubclassMethod.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Method findSuperclassMethod(@DottedClassName String superclassName, Method subclassMethod) throws ClassNotFoundException {

        String methodName = subclassMethod.getName();
        Type[] subArgs = null;
        JavaClass superClass = Repository.lookupClass(superclassName);
        Method[] methods = superClass.getMethods();
        outer: for (Method m : methods) {
            if (m.getName().equals(methodName)) {
                if (subArgs == null) {
                    subArgs = Type.getArgumentTypes(subclassMethod.getSignature());
                }
                Type[] superArgs = Type.getArgumentTypes(m.getSignature());
                if (subArgs.length == superArgs.length) {
                    for (int j = 0; j < subArgs.length; j++) {
                        if (!superArgs[j].equals(subArgs[j])) {
                            continue outer;
                        }
                    }
                    return m;
                }
            }
        }

        if (!"Object".equals(superclassName)) {
            @DottedClassName
            String superSuperClassName = superClass.getSuperclassName();
            if (superSuperClassName.equals(superclassName)) {
                throw new ClassNotFoundException("superclass of " + superclassName + " is itself");
            }
            return findSuperclassMethod(superSuperClassName, subclassMethod);
        }

        return null;
    }
 
Example 10
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 11
Source File: UnreadFields.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    data.calledFromConstructors.clear();
    hasNativeMethods = false;
    sawSelfCallInConstructor = false;
    publicOrProtectedConstructor = false;
    isSerializable = false;
    if (obj.isAbstract()) {
        data.abstractClasses.add(getDottedClassName());
    } else {
        String superClass = obj.getSuperclassName();
        if (superClass != null) {
            data.hasNonAbstractSubClass.add(superClass);
        }
    }
    data.classesScanned.add(getDottedClassName());
    boolean superClassIsObject = Values.DOTTED_JAVA_LANG_OBJECT.equals(obj.getSuperclassName());
    if (getSuperclassName().indexOf('$') >= 0 || getSuperclassName().indexOf('+') >= 0
            || withinAnonymousClass.matcher(getDottedClassName()).find()) {
        // System.out.println("hicfsc: " + betterClassName);
        data.innerClassCannotBeStatic.add(getDottedClassName());
        // System.out.println("hicfsc: " + betterSuperclassName);
        data.innerClassCannotBeStatic.add(getDottedSuperclassName());
    }
    // Does this class directly implement Serializable?
    String[] interface_names = obj.getInterfaceNames();
    for (String interface_name : interface_names) {
        if ("java.io.Externalizable".equals(interface_name)) {
            isSerializable = true;
        } else if ("java.io.Serializable".equals(interface_name)) {
            isSerializable = true;
            break;
        }
    }

    // Does this class indirectly implement Serializable?
    if ((!superClassIsObject || interface_names.length > 0) && !isSerializable) {
        try {
            Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
            ClassDescriptor desc = DescriptorFactory.createClassDescriptor(obj);
            if (subtypes2.getSubtypes(serializable).contains(desc) || subtypes2.getSubtypes(externalizable).contains(desc)
                    || subtypes2.getSubtypes(remote).contains(desc)) {
                isSerializable = true;
            }
        } catch (ClassNotFoundException e) {
            bugReporter.reportMissingClass(e);
        }
    }

    // System.out.println(getDottedClassName() + " is serializable: " +
    // isSerializable);
    super.visit(obj);
}
 
Example 12
Source File: MethodGenFactory.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public MethodGen analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = getMethod(analysisCache, descriptor);

    if (method.getCode() == null) {
        return null;
    }
    XMethod xmethod = XFactory.createXMethod(descriptor);
    if (xmethod.usesInvokeDynamic() && false) {
        AnalysisContext.currentAnalysisContext().analysisSkippedDueToInvokeDynamic(xmethod);
        return null;
    }

    try {
        AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
        JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
        ConstantPoolGen cpg = getConstantPoolGen(analysisCache, descriptor.getClassDescriptor());

        String methodName = method.getName();
        int codeLength = method.getCode().getCode().length;
        String superclassName = jclass.getSuperclassName();
        if (codeLength > 6000 && Const.STATIC_INITIALIZER_NAME.equals(methodName) && "java.lang.Enum".equals(superclassName)) {
            analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                    new JavaClassAndMethod(jclass, method).toMethodDescriptor());
            return null;
        }
        if (analysisContext.getBoolProperty(AnalysisFeatures.SKIP_HUGE_METHODS)) {
            if (codeLength > 6000 || (Const.STATIC_INITIALIZER_NAME.equals(methodName) || "getContents".equals(methodName))
                    && codeLength > 2000) {
                analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                        new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                return null;
            }
        }

        return new MethodGen(method, jclass.getClassName(), cpg);
    } catch (Exception e) {
        AnalysisContext.logError("Error constructing methodGen", e);
        return null;
    }
}
 
Example 13
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures that every class has a super class and that
 * <B>final</B> classes are not subclassed.
 * This means, the class this Pass2Verifier operates
 * on has proper super classes (transitively) up to
 * java.lang.Object.
 * The reason for really loading (and Pass1-verifying)
 * all of those classes here is that we need them in
 * Pass2 anyway to verify no final methods are overridden
 * (that could be declared anywhere in the ancestor hierarchy).
 *
 * @throws ClassConstraintException otherwise.
 */
private void every_class_has_an_accessible_superclass() {
    try {
    final Set<String> hs = new HashSet<>(); // save class names to detect circular inheritance
    JavaClass jc = Repository.lookupClass(myOwner.getClassName());
    int supidx = -1;

    while (supidx != 0) {
        supidx = jc.getSuperclassNameIndex();

        if (supidx == 0) {
            if (jc != Repository.lookupClass(Type.OBJECT.getClassName())) {
                throw new ClassConstraintException("Superclass of '"+jc.getClassName()+
                        "' missing but not "+Type.OBJECT.getClassName()+" itself!");
            }
        }
        else{
            final String supername = jc.getSuperclassName();
            if (! hs.add(supername)) {    // If supername already is in the list
                throw new ClassConstraintException("Circular superclass hierarchy detected.");
            }
            final Verifier v = VerifierFactory.getVerifier(supername);
            final VerificationResult vr = v.doPass1();

            if (vr != VerificationResult.VR_OK) {
                throw new ClassConstraintException("Could not load in ancestor class '"+supername+"'.");
            }
            jc = Repository.lookupClass(supername);

            if (jc.isFinal()) {
                throw new ClassConstraintException("Ancestor class '"+supername+
                        "' has the FINAL access modifier and must therefore not be subclassed.");
            }
        }
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: this might not be the best way to handle missing classes.
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 14
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 15
Source File: ClassFilePreDecompilationScan.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void addClassFileMetadata(GraphRewrite event, EvaluationContext context, JavaClassFileModel javaClassFileModel)
{
    try (FileInputStream fis = new FileInputStream(javaClassFileModel.getFilePath()))
    {
        final ClassParser parser = new ClassParser(fis, javaClassFileModel.getFilePath());
        final JavaClass bcelJavaClass = parser.parse();
        final String packageName = bcelJavaClass.getPackageName();

        final String qualifiedName = bcelJavaClass.getClassName();

        final JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
        final JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
        int majorVersion = bcelJavaClass.getMajor();
        int minorVersion = bcelJavaClass.getMinor();

        String simpleName = qualifiedName;
        if (packageName != null && !packageName.isEmpty() && simpleName != null)
        {
            simpleName = StringUtils.substringAfterLast(simpleName, ".");
        }

        javaClassFileModel.setMajorVersion(majorVersion);
        javaClassFileModel.setMinorVersion(minorVersion);
        javaClassFileModel.setPackageName(packageName);

        javaClassModel.setSimpleName(simpleName);
        javaClassModel.setPackageName(packageName);
        javaClassModel.setQualifiedName(qualifiedName);
        javaClassModel.setClassFile(javaClassFileModel);
        javaClassModel.setPublic(bcelJavaClass.isPublic());
        javaClassModel.setInterface(bcelJavaClass.isInterface());

        final String[] interfaceNames = bcelJavaClass.getInterfaceNames();
        if (interfaceNames != null)
        {
            for (final String interfaceName : interfaceNames)
            {
                JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(interfaceName);
                javaClassService.addInterface(javaClassModel, interfaceModel);
            }
        }

        String superclassName = bcelJavaClass.getSuperclassName();
        if (!bcelJavaClass.isInterface() && !StringUtils.isBlank(superclassName))
            javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));

        javaClassFileModel.setJavaClass(javaClassModel);
    }
    catch (Exception ex)
    {
        String nl = ex.getMessage() != null ? Util.NL + "\t" : " ";
        final String message = "BCEL was unable to parse class file '" + javaClassFileModel.getFilePath() + "':" + nl + ex.toString();
        LOG.log(Level.WARNING, message);
        ClassificationService classificationService = new ClassificationService(event.getGraphContext());
        classificationService.attachClassification(event, context, javaClassFileModel, UNPARSEABLE_CLASS_CLASSIFICATION, UNPARSEABLE_CLASS_DESCRIPTION);
        javaClassFileModel.setParseError(message);
        javaClassFileModel.setSkipDecompilation(true);
    }
}