Java Code Examples for org.apache.bcel.generic.MethodGen#getConstantPool()

The following examples show how to use org.apache.bcel.generic.MethodGen#getConstantPool() . 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: FindTwoLockWait.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean preScreen(MethodGen mg) {
    ConstantPoolGen cpg = mg.getConstantPool();

    int lockCount = mg.isSynchronized() ? 1 : 0;
    boolean sawWaitOrNotify = false;

    InstructionHandle handle = mg.getInstructionList().getStart();
    while (handle != null && !(lockCount >= 2 && sawWaitOrNotify)) {
        Instruction ins = handle.getInstruction();
        if (ins instanceof MONITORENTER) {
            ++lockCount;
        } else if (ins instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL inv = (INVOKEVIRTUAL) ins;
            String methodName = inv.getMethodName(cpg);
            if ("wait".equals(methodName) || methodName.startsWith("notify")) {
                sawWaitOrNotify = true;
            }
        }

        handle = handle.getNext();
    }

    return lockCount >= 2 && sawWaitOrNotify;
}
 
Example 2
Source File: IsNullValueAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public IsNullValueAnalysis(MethodDescriptor descriptor, MethodGen methodGen, CFG cfg, ValueNumberDataflow vnaDataflow,
        TypeDataflow typeDataflow, DepthFirstSearch dfs, AssertionMethods assertionMethods) {
    super(dfs);

    this.trackValueNumbers = AnalysisContext.currentAnalysisContext().getBoolProperty(
            AnalysisFeatures.TRACK_VALUE_NUMBERS_IN_NULL_POINTER_ANALYSIS);

    this.methodGen = methodGen;
    this.visitor = new IsNullValueFrameModelingVisitor(methodGen.getConstantPool(), assertionMethods, vnaDataflow,
            typeDataflow, trackValueNumbers);
    this.vnaDataflow = vnaDataflow;
    this.cfg = cfg;
    this.locationWhereValueBecomesNullSet = new HashSet<>();
    this.pointerEqualityCheck = getForPointerEqualityCheck(cfg, vnaDataflow);

    if (DEBUG) {
        System.out.println("IsNullValueAnalysis for " + methodGen.getClassName() + "." + methodGen.getName() + " : "
                + methodGen.getSignature());
    }
}
 
Example 3
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param methodGen
 *            the method to build a CFG for
 */
public BetterCFGBuilder2(@Nonnull MethodDescriptor descriptor, @Nonnull MethodGen methodGen) {
    this.methodGen = methodGen;
    this.cpg = methodGen.getConstantPool();
    IAnalysisCache analysisCache = Global.getAnalysisCache();
    StandardTypeMerger merger = null;
    ExceptionSetFactory exceptionSetFactory;
    try {
        exceptionSetFactory = analysisCache.getMethodAnalysis(ExceptionSetFactory.class, descriptor);
        merger = new StandardTypeMerger(AnalysisContext.currentAnalysisContext()
                .getLookupFailureCallback(), exceptionSetFactory);
    } catch (CheckedAnalysisException e) {
        AnalysisContext.logError("Unable to generate exceptionSetFactory for " + descriptor, e);
    }


    this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen, merger);
    this.usedInstructionSet = new BitSet();
    this.jsrSubroutineMap = new IdentityHashMap<>();
    this.subroutineWorkList = new LinkedList<>();
}
 
Example 4
Source File: TaintAnalysis.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructs analysis for the given method
 * 
 * @param methodGen method to analyze
 * @param dfs DFS algorithm
 * @param descriptor descriptor of the method to analyze
 * @param taintConfig configured and derived taint summaries
 */
public TaintAnalysis(MethodGen methodGen, DepthFirstSearch dfs,
        MethodDescriptor descriptor, TaintConfig taintConfig) {
    super(dfs);
    this.methodGen = methodGen;
    this.methodDescriptor = (MethodInfo) descriptor;
    this.visitor = new TaintFrameModelingVisitor(methodGen.getConstantPool(), descriptor, taintConfig);
    computeParametersInfo(descriptor.getSignature(), descriptor.isStatic());
}
 
Example 5
Source File: FindMismatchedWaitOrNotify.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {

        MethodGen methodGen = classContext.getMethodGen(method);
        if (methodGen == null) {
            return;
        }
        ConstantPoolGen cpg = methodGen.getConstantPool();
        CFG cfg = classContext.getCFG(method);
        ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
        LockDataflow dataflow = classContext.getLockDataflow(method);

        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
            Location location = i.next();

            InstructionHandle handle = location.getHandle();

            Instruction ins = handle.getInstruction();
            if (!(ins instanceof INVOKEVIRTUAL)) {
                continue;
            }
            INVOKEVIRTUAL inv = (INVOKEVIRTUAL) ins;

            String methodName = inv.getName(cpg);
            String methodSig = inv.getSignature(cpg);

            if (Hierarchy.isMonitorWait(methodName, methodSig) || Hierarchy.isMonitorNotify(methodName, methodSig)) {
                int numConsumed = inv.consumeStack(cpg);
                if (numConsumed == Const.UNPREDICTABLE) {
                    throw new DataflowAnalysisException("Unpredictable stack consumption", methodGen, handle);
                }

                ValueNumberFrame frame = vnaDataflow.getFactAtLocation(location);
                if (!frame.isValid()) {
                    // Probably dead code
                    continue;
                }
                if (frame.getStackDepth() - numConsumed < 0) {
                    throw new DataflowAnalysisException("Stack underflow", methodGen, handle);
                }
                ValueNumber ref = frame.getValue(frame.getNumSlots() - numConsumed);
                LockSet lockSet = dataflow.getFactAtLocation(location);
                int lockCount = lockSet.getLockCount(ref.getNumber());

                if (lockCount == 0) {
                    Collection<ValueNumber> lockedValueNumbers = lockSet.getLockedValueNumbers(frame);
                    boolean foundMatch = false;
                    for (ValueNumber v : lockedValueNumbers) {
                        if (frame.veryFuzzyMatch(ref, v)) {
                            foundMatch = true;
                            break;
                        }
                    }

                    if (!foundMatch) {

                        String type = "wait".equals(methodName) ? "MWN_MISMATCHED_WAIT" : "MWN_MISMATCHED_NOTIFY";
                        String sourceFile = classContext.getJavaClass().getSourceFileName();
                        // Report as medium priority only if the method is
                        // public.
                        // Non-public methods may be properly locked in a
                        // calling context.
                        int priority = method.isPublic() ? NORMAL_PRIORITY : LOW_PRIORITY;

                        bugAccumulator.accumulateBug(
                                new BugInstance(this, type, priority).addClassAndMethod(methodGen, sourceFile),
                                SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
                    }
                }
            }
        }
        bugAccumulator.reportAccumulatedBugs();
    }
 
Example 6
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private int getPriority(MethodDescriptor methodDescriptor, RedundantCondition condition) {
    if (condition.isByType()) {
        // Skip reports which should be reported by another detector
        long number = condition.getNumber().longValue();
        switch (condition.getSignature()) {
        case "I":
            if (number == Integer.MIN_VALUE || number == Integer.MAX_VALUE) {
                // Will be reported as INT_VACUOUS_COMPARISON
                return IGNORE_PRIORITY;
            }
            break;
        case "C":
            if (number <= 0) {
                // Will be reported as INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE
                return IGNORE_PRIORITY;
            }
            break;
        case "B":
            if (number < Byte.MIN_VALUE || number >= Byte.MAX_VALUE) {
                // Will be reported as INT_BAD_COMPARISON_WITH_SIGNED_BYTE
                return IGNORE_PRIORITY;
            }
            break;
        default:
            break;
        }
    }
    int priority = condition.isDeadCodeUnreachable() ? HIGH_PRIORITY
            : condition.isBorder()
                    || condition.getSignature().equals("Z") ? LOW_PRIORITY : NORMAL_PRIORITY;
    // check for boolean conversion
    if (condition.getDeadCodeLocation() != null && condition.getLiveCodeLocation() != null && condition.isDeadCodeUnreachable()) {
        InstructionHandle deadHandle = condition.getDeadCodeLocation().getHandle();
        InstructionHandle liveHandle = condition.getLiveCodeLocation().getHandle();
        int deadValue = getIntValue(deadHandle);
        int liveValue = getIntValue(liveHandle);
        if ((deadValue == 0 && liveValue == 1) || (deadValue == 1 && liveValue == 0)) {
            InstructionHandle deadNext = deadHandle.getNext();
            InstructionHandle liveNext = liveHandle.getNext();
            if (deadNext != null && liveNext != null) {
                InstructionHandle middle, after;
                if (deadNext.getNext() == liveHandle) {
                    middle = deadNext;
                    after = liveNext;
                } else if (liveNext.getNext() == deadHandle) {
                    middle = liveNext;
                    after = deadNext;
                } else {
                    return priority;
                }
                if (!(middle.getInstruction() instanceof GOTO) || ((GOTO) middle.getInstruction()).getTarget() != after) {
                    return priority;
                }
                MethodGen methodGen;
                try {
                    methodGen = Global.getAnalysisCache().getMethodAnalysis(MethodGen.class, methodDescriptor);
                } catch (CheckedAnalysisException e) {
                    return priority;
                }
                InstructionHandle consumer = getConsumer(methodGen, after);
                Instruction consumerInst = consumer == null ? null : consumer.getInstruction();
                if (consumerInst != null) {
                    short opcode = consumerInst.getOpcode();
                    if (opcode == Const.IADD || opcode == Const.ISUB || opcode == Const.IMUL
                            || opcode == Const.ISHR || opcode == Const.ISHL || opcode == Const.IUSHR) {
                        // It's actually integer expression with explicit ? 1 : 0 or ? 0 : 1 operation
                        return priority;
                    }
                }
                if (condition.getSignature().equals("Z")) {
                    // Ignore !flag when flag value is known
                    return IGNORE_PRIORITY;
                }
                priority = condition.isBorder() ? LOW_PRIORITY : NORMAL_PRIORITY;
                if (consumerInst instanceof InvokeInstruction) {
                    ConstantPoolGen constantPool = methodGen.getConstantPool();
                    String methodName = ((InvokeInstruction) consumerInst).getMethodName(constantPool);
                    // Ignore values conditions used in assertion methods
                    if ((methodName.equals("assertTrue") || methodName.equals("checkArgument") || methodName.equals("isLegal")
                            || methodName.equals("isTrue"))) {
                        return liveValue == 1 ? condition.isBorder() ? IGNORE_PRIORITY : LOW_PRIORITY : HIGH_PRIORITY;
                    }
                    if ((methodName.equals("assertFalse") || methodName.equals("isFalse"))) {
                        return liveValue == 0 ? condition.isBorder() ? IGNORE_PRIORITY : LOW_PRIORITY : HIGH_PRIORITY;
                    }
                }
            }
        }
    }
    return priority;
}
 
Example 7
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, final Method method) throws CFGBuilderException,
        DataflowAnalysisException {

    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }

    JavaClass jclass = classContext.getJavaClass();
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    // Enqueue all of the potential violations we find in the method.
    // Normally we'll only report the first highest-priority warning,
    // but if in relaxed mode or if REPORT_ALL_REF_COMPARISONS is set,
    // then we'll report everything.
    LinkedList<WarningWithProperties> refComparisonList = new LinkedList<>();
    LinkedList<WarningWithProperties> stringComparisonList = new LinkedList<>();


    comparedForEqualityInThisMethod = new HashMap<>();
    CFG cfg = classContext.getCFG(method);
    DepthFirstSearch dfs = classContext.getDepthFirstSearch(method);
    ExceptionSetFactory exceptionSetFactory = classContext.getExceptionSetFactory(method);

    // Perform type analysis using our special type merger
    // (which handles String types specially, keeping track of
    // which ones appear to be dynamically created)
    RefComparisonTypeMerger typeMerger = new RefComparisonTypeMerger(bugReporter, exceptionSetFactory);
    RefComparisonTypeFrameModelingVisitor visitor = new RefComparisonTypeFrameModelingVisitor(methodGen.getConstantPool(),
            typeMerger, bugReporter);
    TypeAnalysis typeAnalysis = new SpecialTypeAnalysis(method, methodGen, cfg, dfs, typeMerger, visitor, bugReporter,
            exceptionSetFactory);
    TypeDataflow typeDataflow = new TypeDataflow(cfg, typeAnalysis);
    Profiler profiler = Global.getAnalysisCache().getProfiler();
    profiler.start(SpecialTypeAnalysis.class);
    try {
        typeDataflow.execute();
    } finally {
        profiler.end(SpecialTypeAnalysis.class);
    }

    // Inspect Locations in the method for suspicious ref comparisons and
    // calls to equals()
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();

        inspectLocation(jclass, cpg, method, methodGen, refComparisonList, stringComparisonList, visitor, typeDataflow,
                location);
    }

    if (stringComparisonList.isEmpty() && refComparisonList.isEmpty()) {
        return;
    }
    // Add method-wide properties to BugInstances
    final boolean likelyTestcase = TestCaseDetector.likelyTestCase(XFactory.createXMethod(jclass, method));

    decorateWarnings(stringComparisonList, warn -> {
        if (mightBeLaterCheckedUsingEquals(warn)) {
            warn.propertySet.addProperty(RefComparisonWarningProperty.SAW_CALL_TO_EQUALS);
        }

        if (likelyTestcase) {
            warn.propertySet.addProperty(RefComparisonWarningProperty.COMPARE_IN_TEST_CASE);
        }
        /*
        if (false && !(method.isPublic() || method.isProtected())) {
            warn.propertySet.addProperty(RefComparisonWarningProperty.PRIVATE_METHOD);
        }
         */
    });
    decorateWarnings(refComparisonList, warn -> {
        if (likelyTestcase) {
            warn.propertySet.addProperty(RefComparisonWarningProperty.COMPARE_IN_TEST_CASE);
        }

        if (mightBeLaterCheckedUsingEquals(warn)) {
            warn.propertySet.addProperty(RefComparisonWarningProperty.SAW_CALL_TO_EQUALS);
        }
    });

    // Report violations
    boolean relaxed = FindBugsAnalysisFeatures.isRelaxedMode();
    reportBest(classContext, method, stringComparisonList, relaxed);
    reportBest(classContext, method, refComparisonList, relaxed);
}
 
Example 8
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws DataflowAnalysisException, CFGBuilderException {
    JavaClass javaClass = classContext.getJavaClass();
    ValueNumberDataflow vnd = classContext.getValueNumberDataflow(method);

    Set<ValueNumber> passthruParams = getPassthruParams(vnd, method, javaClass);

    this.method = method;
    this.classContext = classContext;
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }

    ConstantPoolGen cpg = methodGen.getConstantPool();
    CFG cfg = classContext.getCFG(method);

    StringAppendState stringAppendState = getStringAppendState(cfg, cpg);

    ConstantDataflow dataflow = classContext.getConstantDataflow(method);
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();
        Instruction ins = location.getHandle().getInstruction();
        if (!(ins instanceof InvokeInstruction)) {
            continue;
        }
        InvokeInstruction invoke = (InvokeInstruction) ins;
        MethodDescriptor md = new MethodDescriptor(invoke, cpg);
        boolean executeMethod;
        int[] params = preparedStatementMethods.get(md);
        int paramNumber;
        // Currently only one method parameter is checked, though it's the most common case
        // TODO: support methods which take several SQL statements
        if (params != null) {
            executeMethod = false;
            paramNumber = params[0];
        } else {
            params = executeMethods.get(md);
            if (params != null) {
                executeMethod = true;
                paramNumber = params[0];
            } else {
                continue;
            }
        }
        ConstantFrame frame = dataflow.getFactAtLocation(location);
        SignatureParser parser = new SignatureParser(invoke.getSignature(cpg));
        Constant value = frame.getArgument(invoke, cpg, paramNumber, parser);
        ValueNumber vn = vnd.getFactAtLocation(location).getArgument(invoke, cpg, paramNumber, parser);

        if (!value.isConstantString() && !passthruParams.contains(vn)) {
            // TODO: verify it's the same string represented by
            // stringAppendState
            // FIXME: will false positive on const/static strings
            // returns by methods
            Location prev = getValueNumberCreationLocation(vnd, vn);
            if (prev == null || !isSafeValue(prev, cpg)) {
                BugInstance bug = generateBugInstance(javaClass, methodGen, location.getHandle(), stringAppendState,
                        executeMethod);
                bugAccumulator.accumulateBug(
                        bug,
                        SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
                                javaClass.getSourceFileName(), location.getHandle()));
            }
        }
    }
    bugAccumulator.reportAccumulatedBugs();
}
 
Example 9
Source File: ConstantAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ConstantAnalysis(MethodGen methodGen, DepthFirstSearch dfs) {
    super(dfs);
    this.methodGen = methodGen;
    this.visitor = new ConstantFrameModelingVisitor(methodGen.getConstantPool());
}
 
Example 10
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
BCELFactory(final MethodGen mg, final PrintWriter out) {
    _mg = mg;
    _cp = mg.getConstantPool();
    _out = out;
}
 
Example 11
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Constructor.
 *
 * @param methodGen
 *            the method being analyzed
 * @param factory
 *            factory for ValueNumbers for the method
 * @param cache
 *            cache of input/output transformations for each instruction
 * @param loadedFieldSet
 *            fields loaded/stored by each instruction and entire method
 * @param lookupFailureCallback
 *            callback to use to report class lookup failures
 */
public ValueNumberFrameModelingVisitor(MethodGen methodGen, ValueNumberFactory factory, ValueNumberCache cache,
        LoadedFieldSet loadedFieldSet, RepositoryLookupFailureCallback lookupFailureCallback) {

    super(methodGen.getConstantPool());
    this.methodGen = methodGen;
    this.factory = factory;
    this.cache = cache;
    this.loadedFieldSet = loadedFieldSet;
    this.constantValueMap = new HashMap<>();
    this.stringConstantMap = new HashMap<>();
}
 
Example 12
Source File: TypeAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Constructor.
 *
 * @param method
 *            TODO
 * @param methodGen
 *            the MethodGen whose CFG we'll be analyzing
 * @param cfg
 *            the control flow graph
 * @param dfs
 *            DepthFirstSearch of the method
 * @param typeMerger
 *            object to merge types
 * @param lookupFailureCallback
 *            lookup failure callback
 * @param exceptionSetFactory
 *            factory for creating ExceptionSet objects
 */
public TypeAnalysis(Method method, MethodGen methodGen, CFG cfg, DepthFirstSearch dfs, TypeMerger typeMerger,
        RepositoryLookupFailureCallback lookupFailureCallback, ExceptionSetFactory exceptionSetFactory) {
    this(method, methodGen, cfg, dfs, typeMerger, new TypeFrameModelingVisitor(methodGen.getConstantPool(), typeMerger),
            lookupFailureCallback, exceptionSetFactory);
    if (TypeFrameModelingVisitor.DEBUG) {
        System.out.println(methodGen.getClassName() + "." + methodGen.getName() + " " + methodGen.getSignature());
    }
}
 
Example 13
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Add a method annotation for the method which is called by given
 * instruction.
 *
 * @param methodGen
 *            the method containing the call
 * @param inv
 *            the InvokeInstruction
 * @return this object
 */
@Nonnull
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
    ConstantPoolGen cpg = methodGen.getConstantPool();
    return addCalledMethod(cpg, inv);
}