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

The following examples show how to use org.apache.bcel.classfile.Method. 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
public boolean isCaught(ClassContext classContext, Method method, UnconditionalValueDerefSet entryFact, ValueNumber paramVN) {
    boolean caught = true;

    Set<Location> dereferenceSites = entryFact.getDerefLocationSet(paramVN);
    if (dereferenceSites != null && !dereferenceSites.isEmpty()) {
        ConstantPool cp = classContext.getJavaClass().getConstantPool();

        for (Location loc : dereferenceSites) {
            if (!FindNullDeref.catchesNull(cp, method.getCode(), loc)) {
                caught = false;
            }
        }

    }
    return caught;
}
 
Example 2
Source Project: JQF   Source File: JavaClassGenerator.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Method generateMethod(String className, SourceOfRandomness r) {
    int flags = r.nextInt(0, Short.MAX_VALUE);
    Type returnType = r.nextBoolean() ? Type.VOID : generateType(r, true);
    String methodName = generateMemberName(r);
    int numArgs = r.nextInt(4);
    Type[] argTypes = new Type[numArgs];
    String[] argNames = new String[numArgs];
    for (int i = 0; i < numArgs; i++) {
        argTypes[i] = generateType(r, true);
        argNames[i] = generateMemberName(r);
    }
    InstructionList code = generateCode(r, argTypes, returnType);
    MethodGen methodGen = new MethodGen(flags, returnType, argTypes, argNames, methodName, className, code, constants);
    // Validate flags
    Assume.assumeFalse(methodGen.isFinal() && methodGen.isAbstract());
    return methodGen.getMethod();
}
 
Example 3
private boolean hasTestMethods(JavaClass jClass) {
    boolean foundTest = false;
    Method[] methods = jClass.getMethods();
    for (Method m : methods) {
        if (m.isPublic() && m.getName().startsWith("test") && m.getSignature().equals("()V")) {
            return true;
        }
        if (m.getName().startsWith("runTest") && m.getSignature().endsWith("()V")) {
            return true;
        }
    }
    if (hasSuite(methods)) {
        return true;
    }

    try {
        JavaClass sClass = jClass.getSuperClass();
        if (sClass != null) {
            return hasTestMethods(sClass);
        }
    } catch (ClassNotFoundException e) {
        AnalysisContext.reportMissingClass(e);
    }

    return false;
}
 
Example 4
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClasses)
{
    final Iterator it = aJavaClasses.iterator();
    while (it.hasNext()) {
        final JavaClass javaClass = (JavaClass) it.next();
        final String className = javaClass.getClassName();
        final JavaClassDefinition classDef = findJavaClassDef(javaClass);
        final MethodDefinition[] methodDefs = classDef.getMethodDefs();
        for (int i = 0; i < methodDefs.length; i++) {
            if (!classDef.hasReference(methodDefs[i], getReferenceDAO())) {
                final Method method = methodDefs[i].getMethod();
                if (!ignore(className, method)) {
                    log(
                        javaClass,
                        0,
                        "unused.method",
                        new Object[] {methodDefs[i]});
                }
            }
        }
    }
}
 
Example 5
Source Project: spotbugs   Source File: Subtypes2.java    License: 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 6
@Override
public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor());
    Method[] methodList = jclass.getMethods();

    Method result = null;

    // As a side-effect, cache all of the Methods for this JavaClass
    for (Method method : methodList) {
        MethodDescriptor methodDescriptor = DescriptorFactory.instance().getMethodDescriptor(
                descriptor.getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic());

        // Put in cache eagerly
        analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method);

        if (methodDescriptor.equals(descriptor)) {
            result = method;
        }
    }

    return result;
}
 
Example 7
@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 8
private static boolean isVulnerable(Method method) {

        // If the method is not annotated with `@RequestMapping`, there is no vulnerability.
        AnnotationEntry requestMappingAnnotation = findRequestMappingAnnotation(method);
        if (requestMappingAnnotation == null) {
            return false;
        }

        // If the `@RequestMapping` annotation is used without the `method` annotation attribute,
        // there is a vulnerability.
        ElementValuePair methodAnnotationAttribute = findMethodAnnotationAttribute(requestMappingAnnotation);
        if (methodAnnotationAttribute == null) {
            return true;
        }

        // If the `@RequestMapping` annotation is used with the `method` annotation attribute equal to `{}`,
        // there is a vulnerability.
        ElementValue methodAnnotationAttributeValue = methodAnnotationAttribute.getValue();
        if (isEmptyArray(methodAnnotationAttributeValue)) {
            return true;
        }

        // If the `@RequestMapping` annotation is used with the `method` annotation attribute but contains a mix of
        // unprotected and protected HTTP request methods, there is a vulnerability.
        return isMixOfUnprotectedAndProtectedHttpRequestMethods(methodAnnotationAttributeValue);
    }
 
Example 9
@Override
public void visit(JavaClass obj) {
    try {
        methodMap.clear();
        badOverrideMap.clear();
        JavaClass superClass = obj.getSuperClass();
        if (superClass == null) {
            return;
        }
        String packageName = superClass.getPackageName();
        String className = superClass.getClassName();

        // A more generic way to add Adapters would be nice here
        isAdapter = ((className.endsWith("Adapter")) && ("java.awt.event".equals(packageName) || "javax.swing.event".equals(packageName)))
                || (("DefaultHandler".equals(className) && ("org.xml.sax.helpers".equals(packageName))));
        if (isAdapter) {
            Method[] methods = superClass.getMethods();
            for (Method method1 : methods) {
                methodMap.put(method1.getName(), method1.getSignature());
            }
        }
    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
}
 
Example 10
public void visitClassContext(ClassContext classContext) {
    boolean fullAnalysis = AnalysisContext.currentAnalysisContext().getBoolProperty(
            FindBugsAnalysisFeatures.INTERPROCEDURAL_ANALYSIS_OF_REFERENCED_CLASSES);
    if (!fullAnalysis && !AnalysisContext.currentAnalysisContext()./*
                                                                   * getSubtypes
                                                                   * ().
                                                                   */isApplicationClass(classContext.getJavaClass())) {
        return;
    }
    if (VERBOSE_DEBUG) {
        System.out.println("Visiting class " + classContext.getJavaClass().getClassName());
    }

    for (Method m : classContext.getMethodsInCallOrder()) {
        considerMethod(classContext, m);
    }
}
 
Example 11
Source Project: commons-bcel   Source File: JdkGenericDumpTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private void testJar(final File file) throws Exception {
    System.out.println(file);
    try (JarFile jar = new JarFile(file)) {
        final Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            final JarEntry jarEntry = en.nextElement();
            final String name = jarEntry.getName();
            if (name.endsWith(".class")) {
                // System.out.println("- " + name);
                try (InputStream inputStream = jar.getInputStream(jarEntry)) {
                    final ClassParser classParser = new ClassParser(inputStream, name);
                    final JavaClass javaClass = classParser.parse();
                    for (final Method method : javaClass.getMethods()) {
                        compare(name, method);
                    }
                }
            }
        }
    }
}
 
Example 12
Source Project: spotbugs   Source File: Naming.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean markedAsNotUsable(Method obj) {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof Deprecated) {
            return true;
        }
    }
    Code code = obj.getCode();
    if (code == null) {
        return false;
    }
    byte[] codeBytes = code.getCode();
    if (codeBytes.length > 1 && codeBytes.length < 10) {
        int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff;
        if (lastOpcode != Const.ATHROW) {
            return false;
        }
        for (int b : codeBytes) {
            if ((b & 0xff) == Const.RETURN) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example 13
Source Project: spotbugs   Source File: BugInstance.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public BugInstance addSomeSourceForTopTwoStackValues(ClassContext classContext, Method method, Location location) {
    int pc = location.getHandle().getPosition();
    try {
        OpcodeStack stack = OpcodeStackScanner.getStackAt(classContext.getJavaClass(), method, pc);
        BugAnnotation a1 = getSomeSource(classContext, method, location, stack, 1);
        BugAnnotation a0 = getSomeSource(classContext, method, location, stack, 0);
        addOptionalUniqueAnnotations(a0, a1);
    } catch (UnreachableCodeException e) {
        if (SystemProperties.ASSERTIONS_ENABLED) {
            AnalysisContext.logError(e.getMessage(), e);
        }
        assert true;
    }
    return this;

}
 
Example 14
Source Project: commons-bcel   Source File: PLSETestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-295:
 */
public void testB295() throws Exception
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass2");
    final ClassGen cg = new ClassGen(clazz);
    final ConstantPoolGen pool = cg.getConstantPool();
    final Method m = cg.getMethodAt(1);  // 'main'
    final LocalVariableTable lvt = m.getLocalVariableTable();
    final LocalVariable lv = lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(lv);
    final MethodGen mg = new MethodGen(m, cg.getClassName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    final LocalVariable new_lv = new_lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(new_lv);
    assertEquals("live range length", lv.getLength(), new_lv.getLength());
}
 
Example 15
Source Project: spotbugs   Source File: Lookup.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static @CheckForNull JavaClass findSuperImplementor(JavaClass clazz, String name, String signature, BugReporter bugReporter) {
    try {
        JavaClass c = clazz;
        while (true) {
            c = c.getSuperClass();
            if (c == null) {
                return null;
            }
            Method m = findImplementation(c, name, signature);
            if (m != null && !m.isAbstract()) {
                return c;
            }

        }
    } catch (ClassNotFoundException e) {
        bugReporter.reportMissingClass(e);
        return null;
    }
}
 
Example 16
Source Project: spotbugs   Source File: DerefFinder.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static NullnessAnnotation getMethodNullnessAnnotation(ClassContext classContext, Method method) {

        if (method.getSignature().indexOf(")L") >= 0 || method.getSignature().indexOf(")[") >= 0) {

            XMethod m = XFactory.createXMethod(classContext.getJavaClass(), method);
            return AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase().getResolvedAnnotation(m, false);
        }
        return NullnessAnnotation.UNKNOWN_NULLNESS;
    }
 
Example 17
Set<String> definedInClass(JavaClass clazz) {
    HashSet<String> result = new HashSet<>();
    for (Method m : clazz.getMethods()) {
        if (!skip(m)) {
            result.add(m.getName() + m.getSignature());
        }
    }
    return result;
}
 
Example 18
private boolean hasRequestMapping(JavaClass clazz) {
    Method[] methods = clazz.getMethods();
    for (Method m: methods) {
        AnnotationEntry[] annotations = m.getAnnotationEntries();

        for (AnnotationEntry ae: annotations) {
            if (REQUEST_MAPPING_ANNOTATION_TYPES.contains(ae.getAnnotationType())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 19
@Override
public UsagesRequiringNonNullValues analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
        throws CheckedAnalysisException {
    // ClassContext classContext = getClassContext(jclass);
    ClassContext classContext = analysisCache.getClassAnalysis(ClassContext.class, descriptor.getClassDescriptor());
    Method method = getMethod(analysisCache, descriptor);
    return DerefFinder.getAnalysis(classContext, method);
}
 
Example 20
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] getByteCodes(final Method method) {
    final Code code = method.getCode();
    if (code == null) {
        throw new IllegalStateException(String.format("The method '%s' has no code.", method));
    }
    return code.getCode();
}
 
Example 21
/**
 * Methods marked with the "Synthetic" attribute do not appear in the source
 * code
 */
private boolean isSynthetic(Method m) {
    if ((m.getAccessFlags() & Const.ACC_SYNTHETIC) != 0) {
        return true;
    }
    Attribute[] attrs = m.getAttributes();
    for (Attribute attr : attrs) {
        if (attr instanceof Synthetic) {
            return true;
        }
    }
    return false;
}
 
Example 22
Source Project: spotbugs   Source File: XFactory.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create an XMethod object from a BCEL Method.
 *
 * @param javaClass
 *            the class to which the Method belongs
 * @param method
 *            the Method
 * @return an XMethod representing the Method
 */

public static XMethod createXMethod(JavaClass javaClass, Method method) {
    if (method == null) {
        throw new NullPointerException("method must not be null");
    }
    XMethod xmethod = createXMethod(javaClass.getClassName(), method);
    assert xmethod.isResolved();
    return xmethod;
}
 
Example 23
private boolean classDefinesMethod(JavaClass c, XMethod m) {
    for (Method definedMethod : c.getMethods()) {
        if (definedMethod.getName().equals(m.getName()) && definedMethod.getSignature().equals(m.getSignature())
                && definedMethod.isStatic() == m.isStatic()) {
            return true;
        }
    }
    return false;
}
 
Example 24
Source Project: commons-bcel   Source File: maxstack.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String class_name : argv) {
        JavaClass java_class = Repository.lookupClass(class_name);

        if (java_class == null) {
            java_class = new ClassParser(class_name).parse();
        }

        final ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());

        for (final Method m : java_class.getMethods()) {
            if (!(m.isAbstract() || m.isNative())) {
                final MethodGen mg = new MethodGen(m, class_name, cp);

                final int compiled_stack = mg.getMaxStack();
                final int compiled_locals = mg.getMaxLocals();
                mg.setMaxStack(); // Recompute value
                mg.setMaxLocals();
                final int computed_stack = mg.getMaxStack();
                final int computed_locals = mg.getMaxLocals();

                mg.getInstructionList().dispose(); // Reuse instruction handles

                System.out.println(m);

                if (computed_stack == compiled_stack) {
                    System.out.println("Stack ok(" + computed_stack + ")");
                } else {
                    System.out.println("\nCompiled stack size " + compiled_stack + " computed size " + computed_stack);
                }

                if (computed_locals == compiled_locals) {
                    System.out.println("Locals ok(" + computed_locals + ")");
                } else {
                    System.out.println("\nCompiled locals " + compiled_locals + " computed size " + computed_locals);
                }
            }
        }
    }
}
 
Example 25
private void addToReport(Method m, ClassContext classContext, Location locationWeakness, Number n){
    JavaClass clz = classContext.getJavaClass();
    int priority = (n.intValue() < 1024) ? Priorities.NORMAL_PRIORITY : Priorities.LOW_PRIORITY;
    bugReporter.reportBug(new BugInstance(this, RSA_KEY_SIZE_TYPE, priority) //
            .addClass(clz)
            .addMethod(clz, m)
            .addSourceLine(classContext, m, locationWeakness));
}
 
Example 26
Source Project: spotbugs   Source File: DumbMethods.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Method method) {
    String cName = getDottedClassName();

    for (SubDetector subDetector : subDetectors) {
        subDetector.initMethod(method);
    }

    // System.out.println(getFullyQualifiedMethodName());
    isPublicStaticVoidMain = method.isPublic() && method.isStatic() && "main".equals(getMethodName())
            || cName.toLowerCase().indexOf("benchmark") >= 0;
    prevOpcodeWasReadLine = false;
    Code code = method.getCode();
    if (code != null) {
        this.exceptionTable = code.getExceptionTable();
    }
    if (this.exceptionTable == null) {
        this.exceptionTable = new CodeException[0];
    }
    primitiveObjCtorSeen = null;
    ctorSeen = false;
    randomNextIntState = 0;
    checkForBitIorofSignedByte = false;
    sinceBufferedInputStreamReady = 100000;
    sawCheckForNonNegativeSignedByte = -1000;
    sawLoadOfMinValue = false;
    previousMethodCall = null;

}
 
Example 27
Source Project: spotbugs   Source File: BugInstance.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull BugAnnotation getSourceForStackValue(ClassContext classContext, Method method, Location location, int depth) {
    try {
        int pc = location.getHandle().getPosition();
        OpcodeStack stack = OpcodeStackScanner.getStackAt(classContext.getJavaClass(), method, pc);
        BugAnnotation a0 = getSomeSource(classContext, method, location, stack, depth);
        return a0;
    } catch (UnreachableCodeException e) {
        if (SystemProperties.ASSERTIONS_ENABLED) {
            AnalysisContext.logError(e.getMessage(), e);
        }
        return null;
    }
}
 
Example 28
Source Project: spotbugs   Source File: Naming.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean isVoidConstructor(JavaClass clazz, Method m) {
    String outerClassSignature = getSignatureOfOuterClass(clazz);
    if (outerClassSignature == null) {
        outerClassSignature = "";
    }
    return Const.CONSTRUCTOR_NAME.equals(m.getName()) && m.getSignature().equals("(" + outerClassSignature + ")V");
}
 
Example 29
HashSet<String> thrownExceptions(Method m) {
    HashSet<String> result = new HashSet<>();
    ExceptionTable exceptionTable = m.getExceptionTable();
    if (exceptionTable != null) {
        Collections.addAll(result, exceptionTable.getExceptionNames());
    }
    return result;
}
 
Example 30
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();

    for (Method method : javaClass.getMethods()) {
        if (isVulnerable(method)) {
            bugReporter.reportBug(new BugInstance(this, SPRING_CSRF_UNRESTRICTED_REQUEST_MAPPING_TYPE, Priorities.HIGH_PRIORITY) //
                    .addClassAndMethod(javaClass, method));
        }
    }
}