Package edu.umd.cs.findbugs.ba

Examples of edu.umd.cs.findbugs.ba.XMethod


     * @return TypeQualifierAnnotation directly applied to the parameter, or
     *         null if there is no directly applied TypeQualifierAnnotation
     */
    public static @CheckForNull @CheckReturnValue
    TypeQualifierAnnotation getDirectTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue<?> typeQualifierValue) {
        XMethod bridge = xmethod.bridgeTo();
        if (bridge != null) {
            xmethod = bridge;
        }
        Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>();
        getDirectApplications(applications, xmethod, parameter);
View Full Code Here


        String calledMethodSig = inv.getSignature(cpg);
        if (calledMethodSig.endsWith(")V")) {
            return;
        }

        XMethod calledXMethod = XFactory.createXMethod(inv, cpg);
        if (TypeQualifierDataflowAnalysis.isIdentifyFunctionForTypeQualifiers(calledXMethod)) {
            return;
        }

        if (calledXMethod.isResolved()) {
            TypeQualifierAnnotation tqa = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(calledXMethod,
                    typeQualifierValue);

            boolean interproc = false;
            if (TypeQualifierDatabase.USE_DATABASE && tqa == null) {
                // See if there's an entry in the interprocedural
                // type qualifier database.
                TypeQualifierDatabase tqdb = Global.getAnalysisCache().getDatabase(TypeQualifierDatabase.class);
                tqa = tqdb.getReturnValue(calledXMethod.getMethodDescriptor(), typeQualifierValue);
                if (tqa != null) {
                    interproc = true;
                }
            }
View Full Code Here

    public static Collection<TypeQualifierValue<?>> getRelevantTypeQualifiers(MethodDescriptor methodDescriptor, CFG cfg)
            throws CheckedAnalysisException {

        final HashSet<TypeQualifierValue<?>> result = new HashSet<TypeQualifierValue<?>>();

        XMethod xmethod = XFactory.createXMethod(methodDescriptor);

        if (FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
            if (DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
                System.out.println("**** Finding effective type qualifiers for " + xmethod);
            }

            //
            // This will take care of methods using fields annotated with
            // a type qualifier.
            //
            getDirectlyRelevantTypeQualifiers(xmethod, result);

            // For all known type qualifiers, find the effective (direct,
            // inherited,
            // or default) type qualifier annotations
            // on the method and all methods directly called by the method.
            //

            addEffectiveRelevantQualifiers(result, xmethod);

            IAnalysisCache analysisCache = Global.getAnalysisCache();
            ConstantPoolGen cpg = analysisCache.getClassAnalysis(ConstantPoolGen.class, methodDescriptor.getClassDescriptor());
            for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
                Location location = i.next();
                Instruction ins = location.getHandle().getInstruction();
                if (ins instanceof InvokeInstruction) {
                    XMethod called = XFactory.createXMethod((InvokeInstruction) ins, cpg);
                    addEffectiveRelevantQualifiers(result, called);
                }

                if (DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
                    System.out.println("===> result: " + result);
View Full Code Here

    }

    private void killLoadsOfObjectsPassed(InvokeInstruction ins) {
        try {

            XMethod called = Hierarchy2.findExactMethod(ins, methodGen.getConstantPool(), Hierarchy.ANY_METHOD);
            FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
            Set<XField> touched = fieldSummary.getFieldsWritten(called);
            if (!touched.isEmpty()) {
                getFrame().killLoadsOf(touched);
            }
View Full Code Here

        try {
            IAnalysisCache analysisCache = Global.getAnalysisCache();

            DepthFirstSearch dfs = analysisCache.getMethodAnalysis(DepthFirstSearch.class, methodDescriptor);
            XMethod xmethod = XFactory.createXMethod(methodDescriptor);
            CFG cfg = analysisCache.getMethodAnalysis(CFG.class, methodDescriptor);
            ValueNumberDataflow vnaDataflow = analysisCache.getMethodAnalysis(ValueNumberDataflow.class, methodDescriptor);
            ConstantPoolGen cpg = analysisCache.getClassAnalysis(ConstantPoolGen.class, methodDescriptor.getClassDescriptor());

            DataflowType dataflow = getDataflow(dfs, xmethod, cfg, vnaDataflow, cpg, analysisCache, methodDescriptor,
View Full Code Here

            boolean wasMethodInvocationWasGeneric = methodInvocationWasGeneric;
            methodInvocationWasGeneric = false;
            if (ins instanceof InvokeInstruction) {
                InvokeInstruction iinv = (InvokeInstruction) ins;
                XMethod m = XFactory.createXMethod(iinv, cpg);
                if (m != null) {
                    String sourceSignature = m.getSourceSignature();
                    methodInvocationWasGeneric = sourceSignature != null
                            && (sourceSignature.startsWith("<") || sourceSignature.indexOf("java/lang/Class") >= 0);
                    if (DEBUG && methodInvocationWasGeneric) {
                        System.out.println(m + " has source signature " + sourceSignature);
                    }
                }

            }
            if (ins instanceof LDC) {
                LDC ldc = (LDC) ins;
                Object value = ldc.getValue(cpg);
                if (value instanceof ConstantClass) {
                    ConstantClass cc = (ConstantClass) value;
                    constantClass = cc.getBytes(classContext.getJavaClass().getConstantPool());
                    pcForConstantClass = pc;
                }
            }

            if (!(ins instanceof CHECKCAST) && !(ins instanceof INSTANCEOF)) {
                continue;
            }

            boolean isCast = ins instanceof CHECKCAST;
            int occurrences = cfg.getLocationsContainingInstructionWithOffset(pc).size();
            boolean split = occurrences > 1;
            if (lineNumberTable != null) {
                int line = lineNumberTable.getSourceLine(handle.getPosition());
                if (line > 0 && linesMentionedMultipleTimes.get(line)) {
                    split = true;
                }
            }

            IsNullValueFrame nullFrame = isNullDataflow.getFactAtLocation(location);
            if (!nullFrame.isValid()) {
                continue;
            }
            IsNullValue operandNullness = nullFrame.getTopValue();
            if (DEBUG) {
                String kind = isCast ? "checkedCast" : "instanceof";
                System.out.println(kind + " at pc: " + pc + " in " + methodName);
                System.out.println(" occurrences: " + occurrences);
                System.out.println("XXX: " + operandNullness);
            }

            if (split && !isCast) {
                // don't report this case; it might be infeasible due to
                // inlining
                continue;
            }

            TypeFrame frame = typeDataflow.getFactAtLocation(location);
            if (!frame.isValid()) {
                // This basic block is probably dead
                continue;
            }

            Type operandType = frame.getTopValue();
            if (operandType.equals(TopType.instance())) {
                // unreachable
                continue;
            }
            boolean operandTypeIsExact = frame.isExact(frame.getStackLocation(0));
            final Type castType = ((TypedInstruction) ins).getType(cpg);

            if (!(castType instanceof ReferenceType)) {
                // This shouldn't happen either
                continue;
            }
            String castSig = castType.getSignature();

            if (operandType.equals(NullType.instance()) || operandNullness.isDefinitelyNull()) {
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
                        sourceFile, handle);
                assert castSig.length() > 1;
                if (!isCast) {
                    accumulator.accumulateBug(new BugInstance(this, "NP_NULL_INSTANCEOF", split ? LOW_PRIORITY : NORMAL_PRIORITY)
                    .addClassAndMethod(methodGen, sourceFile).addType(castSig), sourceLineAnnotation);
                }
                continue;

            }
            if (!(operandType instanceof ReferenceType)) {
                // Shouldn't happen - illegal bytecode
                continue;
            }
            final ReferenceType refType = (ReferenceType) operandType;
            boolean impliesByGenerics = typeDataflow.getAnalysis().isImpliedByGenericTypes(refType);

            if (impliesByGenerics && !isCast) {
                continue;
            }

            final boolean typesAreEqual = refType.equals(castType);
            if (isCast && typesAreEqual) {
                // System.out.println("self-cast to " +
                // castType.getSignature());
                continue;
            }

            String refSig = refType.getSignature();
            String castSig2 = castSig;
            String refSig2 = refSig;
            while (castSig2.charAt(0) == '[' && refSig2.charAt(0) == '[') {
                castSig2 = castSig2.substring(1);
                refSig2 = refSig2.substring(1);
            }

            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
                    sourceFile, handle);

            if (refSig2.charAt(0) != 'L' || castSig2.charAt(0) != 'L') {
                if (castSig2.charAt(0) == '['
                        && (refSig2.equals("Ljava/io/Serializable;") || refSig2.equals("Ljava/lang/Object;") || refSig2
                                .equals("Ljava/lang/Cloneable;"))) {
                    continue;
                }
                if (refSig2.charAt(0) == '['
                        && (castSig2.equals("Ljava/io/Serializable;") || castSig2.equals("Ljava/lang/Object;") || castSig2
                                .equals("Ljava/lang/Cloneable;"))) {
                    continue;
                }
                int priority = HIGH_PRIORITY;
                if (split && (castSig2.endsWith("Error;") || castSig2.endsWith("Exception;"))) {
                    priority = LOW_PRIORITY;
                }
                // report bug only if types are not equal, see bug 3598482
                if(!typesAreEqual){
                    bugReporter.reportBug(new BugInstance(this, isCast ? "BC_IMPOSSIBLE_CAST" : "BC_IMPOSSIBLE_INSTANCEOF", priority)
                    .addClassAndMethod(methodGen, sourceFile).addFoundAndExpectedType(refType, castType)
                    .addSourceLine(sourceLineAnnotation));
                }
                continue;
            }

            if (!operandTypeIsExact && refSig2.equals("Ljava/lang/Object;")) {
                continue;
            }
            /*
            if (false && isCast && haveMultipleCast.contains(sourceLineAnnotation) || !isCast
                    && haveMultipleInstanceOf.contains(sourceLineAnnotation)) {
                // skip; might be due to JSR inlining
                continue;
            }*/
            String castName = castSig2.substring(1, castSig2.length() - 1).replace('/', '.');
            String refName = refSig2.substring(1, refSig2.length() - 1).replace('/', '.');

            if (vnaDataflow == null) {
                vnaDataflow = classContext.getValueNumberDataflow(method);
            }
            ValueNumberFrame vFrame = vnaDataflow.getFactAtLocation(location);
            if (paramValueNumberSet == null) {
                paramValueNumberSet = getParameterValueNumbers(classContext, method, cfg);
            }
            ValueNumber valueNumber = vFrame.getTopValue();
            BugAnnotation valueSource = ValueNumberSourceInfo.findAnnotationFromValueNumber(method, location, valueNumber, vFrame,
                    "VALUE_OF");
            // XXX call below causes 86% of all OpcodeStackDetector.EarlyExitException (getPC() == targetPC) thrown (13000 on java* JDK7 classes)
            BugAnnotation source = BugInstance.getSourceForTopStackValue(classContext, method, location);
            boolean isParameter = paramValueNumberSet.contains(valueNumber) && source instanceof LocalVariableAnnotation;

            try {
                JavaClass castJavaClass = Repository.lookupClass(castName);
                JavaClass refJavaClass = Repository.lookupClass(refName);

                boolean upcast = Repository.instanceOf(refJavaClass, castJavaClass);
                if (upcast || typesAreEqual) {
                    if (!isCast) {
                        accumulator.accumulateBug(new BugInstance(this, "BC_VACUOUS_INSTANCEOF", NORMAL_PRIORITY)
                        .addClassAndMethod(methodGen, sourceFile).addFoundAndExpectedType(refType, castType),
                        sourceLineAnnotation);
                    }
                } else {
                    boolean castMayThrow = !Repository.instanceOf(refJavaClass, castJavaClass);
                    boolean downCast = Repository.instanceOf(castJavaClass, refJavaClass);

                    if (!operandTypeIsExact && refName.equals("java.lang.Object")) {
                        continue;
                    }
                    double rank = 0.0;
                    boolean castToConcreteCollection = concreteCollectionClasses.contains(castName)
                            && abstractCollectionClasses.contains(refName);
                    boolean castToAbstractCollection = abstractCollectionClasses.contains(castName)
                            && veryAbstractCollectionClasses.contains(refName);
                    int position = location.getHandle().getPosition();
                    int catchSize = Util.getSizeOfSurroundingTryBlock(classContext.getJavaClass().getConstantPool(), method.getCode(),
                            "java/lang/ClassCastException", position);



                    if (!operandTypeIsExact) {
                        rank = Analyze.deepInstanceOf(refJavaClass, castJavaClass);
                        if (castToConcreteCollection && rank > 0.6) {
                            rank = (rank + 0.6) / 2;
                        } else if (castToAbstractCollection && rank > 0.3) {
                            rank = (rank + 0.3) / 2;
                        }
                    }
                    /*
                    if (false) {
                        System.out.println("Rank:\t" + rank + "\t" + refName + "\t" + castName);
                    }
                     */
                    boolean completeInformation = (!castJavaClass.isInterface() && !refJavaClass.isInterface())
                            || refJavaClass.isFinal() || castJavaClass.isFinal();
                    if (DEBUG) {
                        System.out.println(" In " + classContext.getFullyQualifiedMethodName(method));
                        System.out.println("At pc: " + handle.getPosition());
                        System.out.println("cast from " + refName + " to " + castName);
                        System.out.println("  cast may throw: " + castMayThrow);
                        System.out.println("  is downcast: " + downCast);
                        System.out.println("  operand type is exact: " + operandTypeIsExact);

                        System.out.println("  complete information: " + completeInformation);
                        System.out.println("  isParameter: " + valueNumber);
                        System.out.println("  score: " + rank);
                        System.out.println("  source is: " + valueSource);
                        if (catchSize < Integer.MAX_VALUE) {
                            System.out.println("  catch block size is: " + catchSize);
                        }
                        if (constantClass != null) {
                            System.out.println("  constant class " + constantClass + " at " + pcForConstantClass);
                        }
                        if (handle.getPrev() == null) {
                            System.out.println("  prev is null");
                        } else {
                            System.out.println("  prev is " + handle.getPrev());
                        }
                    }
                    if (!isCast && castMayThrow && valueSource != null) {
                        String oldCheck = instanceOfChecks.get(valueSource);
                        if (oldCheck == null) {
                            instanceOfChecks.put(valueSource, castName);
                        } else if (!oldCheck.equals(castName)) {
                            instanceOfChecks.put(valueSource, "");
                        }
                    }
                    if (!downCast && completeInformation || operandTypeIsExact) {
                        String bugPattern;
                        if (isCast) {
                            if (downCast && operandTypeIsExact) {
                                if (refSig.equals("[Ljava/lang/Object;") && source instanceof MethodAnnotation
                                        && ((MethodAnnotation) source).getMethodName().equals("toArray")
                                        && ((MethodAnnotation) source).getMethodSignature().equals("()[Ljava/lang/Object;")) {
                                    bugPattern = "BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY";
                                } else {
                                    bugPattern = "BC_IMPOSSIBLE_DOWNCAST";
                                }
                            } else {
                                bugPattern = "BC_IMPOSSIBLE_CAST";
                            }
                        } else {
                            bugPattern = "BC_IMPOSSIBLE_INSTANCEOF";
                        }

                        bugReporter.reportBug(new BugInstance(this, bugPattern, isCast ? HIGH_PRIORITY : NORMAL_PRIORITY)
                        .addClassAndMethod(methodGen, sourceFile)
                        .addFoundAndExpectedType(refType, castType).addOptionalUniqueAnnotations(valueSource, source)
                        .addSourceLine(sourceLineAnnotation));
                    } else if (isCast && rank < 0.9
                            && !valueNumber.hasFlag(ValueNumber.ARRAY_VALUE)) {

                        int priority = NORMAL_PRIORITY;

                        @CheckForNull String oldCheck = instanceOfChecks.get(valueSource);
                        if (DEBUG) {
                            System.out.println("Old check: " + oldCheck);
                        }
                        if (castName.equals(oldCheck)) {
                            priority += 1;
                        } else if ("".equals(oldCheck)) {
                            priority += 1;
                            if (!(source instanceof LocalVariableAnnotation)) {
                                continue;
                            }
                        }

                        if (rank > 0.75) {
                            priority += 2;
                        } else if (rank > 0.5) {
                            priority += 1;
                        } else if (rank > 0.25) {
                            priority += 0;
                        } else {
                            priority--;
                        }



                        if (DEBUG) {
                            System.out.println(" priority a: " + priority);
                        }
                        if (methodGen.getClassName().startsWith(refName) || methodGen.getClassName().startsWith(castName)) {
                            priority += 1;
                        }
                        if (DEBUG) {
                            System.out.println(" priority b: " + priority);
                        }
                        if (castJavaClass.isInterface() && !castToAbstractCollection) {
                            priority++;
                        }
                        if (DEBUG) {
                            System.out.println(" priority c: " + priority);
                        }
                        if (castToConcreteCollection && veryAbstractCollectionClasses.contains(refName)) {
                            priority--;
                        }
                        if (DEBUG) {
                            System.out.println(" priority d: " + priority);
                        }
                        if (priority <= LOW_PRIORITY && !castToAbstractCollection && !castToConcreteCollection
                                && (refJavaClass.isInterface() || refJavaClass.isAbstract())) {
                            priority++;
                        }
                        if (DEBUG) {
                            System.out.println(" priority e: " + priority);
                        }
                        if (DEBUG) {
                            System.out.println(" ref name: " + refName);
                        }
                        if (methodGen.getName().equals("compareTo")) {
                            priority++;
                        } else if (methodGen.isPublic() && isParameter && !castName.equals(oldCheck)) {
                            priority--;
                        }
                        if (wasMethodInvocationWasGeneric && valueNumber.hasFlag(ValueNumber.RETURN_VALUE)) {
                            continue;
                        }
                        if (constantClass != null && pcForConstantClass +20 >= pc && valueNumber.hasFlag(ValueNumber.RETURN_VALUE)
                                && ClassName.toDottedClassName(constantClass).equals(castName)) {
                            priority += 2;
                        }
                        if (DEBUG) {
                            System.out.println(" priority f: " + priority);
                        }
                        if (source instanceof MethodAnnotation) {
                            MethodAnnotation m = (MethodAnnotation) source;
                            XMethod xm = m.toXMethod();
                            if (xm != null && (xm.isPrivate() || xm.isStatic()) && priority == Priorities.LOW_PRIORITY) {
                                continue;
                            }
                        }

                        if (valueNumber.hasFlag(ValueNumber.RETURN_VALUE) &&  priority < Priorities.LOW_PRIORITY) {
View Full Code Here

                        }
                        if (!classDescriptor.getClassName().startsWith("java/util/concurrent")) {
                            continue;
                        }
                        XClass c = Lookup.getXClass(classDescriptor);
                        XMethod m;
                        int priority = NORMAL_PRIORITY;
                        if (methodName.equals("wait")) {
                            m = c.findMethod("await", "()V", false);
                            priority = HIGH_PRIORITY;
                        } else if (methodName.equals("notify")) {
                            m = c.findMethod("signal", "()V", false);
                            if (m == null) {
                                m = c.findMethod("countDown", "()V", false);
                            }
                        } else if (methodName.equals("notifyAll")) {
                            m = c.findMethod("signalAll", "()V", false);
                            if (m == null) {
                                m = c.findMethod("countDown", "()V", false);
                            }
                        } else {
                            throw new IllegalStateException("Unexpected methodName: " + methodName);
                        }

                        if (m != null && m.isPublic() && c.isPublic()) {
                            bugReporter.reportBug(new BugInstance(this, "JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT", priority)
                            .addClassAndMethod(classContext.getJavaClass(), method).addCalledMethod(cpg, iv).addMethod(m)
                            .describe(MethodAnnotation.METHOD_ALTERNATIVE_TARGET).addType(classDescriptor)
                            .describe(TypeAnnotation.FOUND_ROLE).addSourceLine(classContext, method, location));
                        }
View Full Code Here

    public MethodVisitor visitMethod(int methodAccess, String methodName, String desc, String methodSignature, String[] exceptions) {
        if ((methodAccess & ACC_STATIC) != 0) {
            // skip static methods
            return null;
        }
        final XMethod xmethod = xclass.findMethod(methodName, desc, false);
        if (xmethod == null) {
            // unable to continue the analysis
            bugReporter.reportSkippedAnalysis(new MethodDescriptor(xclass.getClassDescriptor().getClassName(), methodName, desc,
                    false));
            return null;
View Full Code Here

            // 2 look in the hierarchy if we have relaxed contract
            HierarchyIterator hierarchy = new HierarchyIterator(xclass);
            XClass superClass;
            boolean done = false;
            while (!done && (superClass = hierarchy.next()) != null) {
                XMethod method = superClass.findMethod(name, desc, false);
                if (method != null) {
                    done = checkMethod(method);
                } else {
                    for (XMethod superMethod : superClass.getXMethods()) {
                        if (name.equals(superMethod.getName()) && compatibleParameters(desc, superMethod.getSignature())) {
View Full Code Here

                    if (DEBUG_FP && produced == null) {
                        System.out.println("Produced type  " + producedType + " not an obligation type");
                    }

                    if (produced != null) {
                        XMethod calledMethod = XFactory.createXMethod(inv, cpg);
                        Obligation[] params = database.getFactory().getParameterObligationTypes(calledMethod);

                        for (int i = 0; i < params.length; i++) {
                            Obligation consumed = params[i];
View Full Code Here

TOP

Related Classes of edu.umd.cs.findbugs.ba.XMethod

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.