Java Code Examples for org.apache.bcel.generic.Instruction

The following examples show how to use org.apache.bcel.generic.Instruction. 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
private void registerInstructionSinks() throws DataflowAnalysisException {
    TypeQualifierAnnotation returnValueAnnotation = null;
    if (!xmethod.getSignature().endsWith(")V")) {
        returnValueAnnotation = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(xmethod, typeQualifierValue);
    }

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

        Instruction ins = location.getHandle().getInstruction();

        if (ins instanceof ReturnInstruction && !(ins instanceof RETURN)) {
            // Return instruction which returns a value
            modelReturn(returnValueAnnotation, location);
        } else {
            short opcode = ins.getOpcode();

            if (opcode == Const.PUTFIELD || opcode == Const.PUTSTATIC) {
                modelFieldStore(location);
            } else if (location.getHandle().getInstruction() instanceof InvokeInstruction) {
                modelArguments(location);
            }
        }
    }
}
 
Example 2
/**
 * Check if the readObject is doing multiple external call beyond the basic readByte, readBoolean, etc..
 * @param m
 * @param classContext
 * @return
 * @throws CFGBuilderException
 * @throws DataflowAnalysisException
 */
private boolean hasCustomReadObject(Method m, ClassContext classContext,List<String> classesToIgnore)
        throws CFGBuilderException, DataflowAnalysisException {
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);
    int count = 0;
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
        Location location = i.next();
        Instruction inst = location.getHandle().getInstruction();
        //ByteCode.printOpCode(inst,cpg);
        if(inst instanceof InvokeInstruction) {
            InvokeInstruction invoke = (InvokeInstruction) inst;
            if (!READ_DESERIALIZATION_METHODS.contains(invoke.getMethodName(cpg))
                    && !classesToIgnore.contains(invoke.getClassName(cpg))) {
                count +=1;
            }
        }
    }
    return count > 3;
}
 
Example 3
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(m);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);

    if (methodGen == null || methodGen.getInstructionList() == null) {
        return; //No instruction .. nothing to do
    }
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
        Location location = i.next();
        Instruction inst = location.getHandle().getInstruction();
        if (inst instanceof InvokeInstruction) {
            InvokeInstruction invoke = (InvokeInstruction) inst;
            String methodName = invoke.getMethodName(cpg);
            if ("enableDefaultTyping".equals(methodName)) {
                JavaClass clz = classContext.getJavaClass();
                bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY)
                        .addClass(clz)
                        .addMethod(clz, m)
                        .addCalledMethod(cpg, invoke)
                        .addSourceLine(classContext, m, location)
                );
            }
        }
    }
}
 
Example 4
public boolean matches(Instruction instruction, ConstantPoolGen cpg) {
    if(instruction != null && instruction instanceof InvokeInstruction) {
        InvokeInstruction invokeInstruction = (InvokeInstruction) instruction;
        if (classesNames.size() != 0 && !classesNames.contains(invokeInstruction.getClassName(cpg))) {
            return false;
        }
        else if (methodNames.size() != 0 && !methodNames.contains(invokeInstruction.getMethodName(cpg))) {
            return false;
        }
        else if (argSignatures.size() != 0 && !argSignatures.contains(invokeInstruction.getSignature(cpg))) {
            return false;
        }
        return true;
    }
    return false;
}
 
Example 5
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example 6
Source Project: spotbugs   Source File: Stream.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean isStreamOpen(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame) {
    if (isOpenOnCreation) {
        return false;
    }

    Instruction ins = handle.getInstruction();
    if (!(ins instanceof INVOKESPECIAL)) {
        return false;
    }

    // Does this instruction open the stream?
    INVOKESPECIAL inv = (INVOKESPECIAL) ins;

    return frame.isValid() && getInstanceValue(frame, inv, cpg).isInstance()
            && matchMethod(inv, cpg, this.getResourceClass(), Const.CONSTRUCTOR_NAME);
}
 
Example 7
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 8
@CheckForNull
Use getUse(ConstantPoolGen cpg, Instruction ins) {
    if (ins instanceof InvokeInstruction) {
        InvokeInstruction invoke = (InvokeInstruction) ins;

        String mName = invoke.getMethodName(cpg);
        String cName = invoke.getClassName(cpg);

        if ("setAttribute".equals(mName) && "javax.servlet.http.HttpSession".equals(cName)) {
            return Use.STORE_INTO_HTTP_SESSION;
        }
        if ("writeObject".equals(mName)
                && ("java.io.ObjectOutput".equals(cName)
                        || "java.io.ObjectOutputStream".equals(cName))) {
            return Use.PASSED_TO_WRITE_OBJECT;
        }
    }
    return null;
}
 
Example 9
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();

    try {
        if (ins instanceof InvokeInstruction) {
            if (!Hierarchy.isSubtype(type, baseClassType)) {
                return null;
            }

            Stream stream = new Stream(location, type.getClassName(), baseClassType.getClassName()).setIsOpenOnCreation(true)
                    .setIgnoreImplicitExceptions(true);
            if (bugType != null) {
                stream.setInteresting(bugType);
            }

            return stream;
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 10
/**
 * @param handle instruction handle which loads the object for further GETFIELD/PUTFIELD operation
 * @return true if this object is known to be non-null
 */
private boolean isSafeFieldSource(InstructionHandle handle) {
    while (handle != null && handle.getInstruction().getOpcode() == Const.DUP) {
        // Some compilers generate DUP for field increment code like
        // ALOAD_0 / DUP / GETFIELD x / ICONST_1 / IADD / PUTFIELD x
        handle = handle.getPrev();
    }
    if (handle == null) {
        return false;
    }
    Instruction inst = handle.getInstruction();
    if (inst.getOpcode() == Const.ALOAD_0) {
        return true;
    }
    return inst instanceof GETFIELD && ((GETFIELD) inst).getFieldName(cpg).startsWith("this$");
}
 
Example 11
Source Project: commons-bcel   Source File: BCELFactory.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {
    if (!_mg.isAbstract() && !_mg.isNative()) {
        for (InstructionHandle ih = _mg.getInstructionList().getStart(); ih != null; ih = ih
                .getNext()) {
            final Instruction i = ih.getInstruction();
            if (i instanceof BranchInstruction) {
                branch_map.put(i, ih); // memorize container
            }
            if (ih.hasTargeters()) {
                if (i instanceof BranchInstruction) {
                    _out.println("    InstructionHandle ih_" + ih.getPosition() + ";");
                } else {
                    _out.print("    InstructionHandle ih_" + ih.getPosition() + " = ");
                }
            } else {
                _out.print("    ");
            }
            if (!visitInstruction(i)) {
                i.accept(this);
            }
        }
        updateBranchTargets();
        updateExceptionHandlers();
    }
}
 
Example 12
private static Map<InstructionHandle, Call> buildCallMap(CFG cfg, ConstantPoolGen cpg) {
    Map<InstructionHandle, Call> callMap = new HashMap<>();

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        InstructionHandle handle = i.next().getHandle();
        Instruction ins = handle.getInstruction();

        if (ins instanceof InvokeInstruction) {
            InvokeInstruction inv = (InvokeInstruction) ins;
            Call call = new Call(inv.getClassName(cpg), inv.getName(cpg), inv.getSignature(cpg));
            callMap.put(handle, call);
        }
    }

    return callMap;
}
 
Example 13
private boolean hasManyPreceedingNullTests(int pc) {
    int ifNullTests = 0;
    BitSet seen = new BitSet();
    try {
        for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) {
            Location loc = i.next();
            int pc2 = loc.getHandle().getPosition();
            if (pc2 >= pc || pc2 < pc - 30) {
                continue;
            }
            Instruction ins = loc.getHandle().getInstruction();
            if ((ins instanceof IFNONNULL || ins instanceof IFNULL || ins instanceof NullnessConversationInstruction)
                    && !seen.get(pc2)) {
                ifNullTests++;
                seen.set(pc2);
            }
        }
        boolean result = ifNullTests > 2;

        // System.out.println("Preceding null tests " + ifNullTests + " " +
        // ifNonnullTests + " " + result);
        return result;
    } catch (CFGBuilderException e) {
        return false;
    }
}
 
Example 14
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example 15
public Condition extractCondition(BackIterator iterator) throws DataflowAnalysisException {
    Instruction comparisonInstruction = iterator.next().getInstruction();
    if (!(comparisonInstruction instanceof IfInstruction)) {
        return null;
    }
    short cmpOpcode = comparisonInstruction.getOpcode();
    int nargs = ((IfInstruction) comparisonInstruction).consumeStack(null);
    if (nargs == 2) {
        return extractTwoArgCondition(iterator, cmpOpcode, "I");
    } else if (nargs == 1) {
        Object val = extractValue(iterator, "I");
        if (val instanceof Value) {
            return new Condition(cmpOpcode, (Value) val, 0);
        } else if (val instanceof LCMP) {
            return extractTwoArgCondition(iterator, cmpOpcode, "J");
        }
    }
    return null;
}
 
Example 16
private Condition extractTwoArgCondition(BackIterator iterator, short cmpOpcode, String signature) throws DataflowAnalysisException {
    Object val2 = extractValue(iterator, signature);
    if (val2 instanceof Instruction) {
        return null;
    }
    Object val1 = extractValue(iterator, signature);
    if (val1 instanceof Instruction) {
        return null;
    }
    if (!(val1 instanceof Value) && !(val2 instanceof Value)) {
        return null;
    }
    if (!(val1 instanceof Value)) {
        Object tmp = val1;
        val1 = val2;
        val2 = tmp;
        cmpOpcode = revertOpcode(cmpOpcode);
    }
    if (!(val2 instanceof Number)) {
        return null;
    }
    return new Condition(cmpOpcode, (Value) val1, (Number) val2);
}
 
Example 17
/**
 * Does the given instruction refer to a likely assertion method?
 *
 * @param ins
 *            the instruction
 * @return true if the instruction likely refers to an assertion, false if
 *         not
 */

public boolean isAssertionInstruction(Instruction ins, ConstantPoolGen cpg) {

    if (ins instanceof InvokeInstruction) {
        return isAssertionCall((InvokeInstruction) ins);
    }
    if (ins instanceof GETSTATIC) {
        GETSTATIC getStatic = (GETSTATIC) ins;
        String className = getStatic.getClassName(cpg);
        String fieldName = getStatic.getFieldName(cpg);
        if ("java.util.logging.Level".equals(className) && "SEVERE".equals(fieldName)) {
            return true;
        }
        return "org.apache.log4j.Level".equals(className)
                && ("ERROR".equals(fieldName) || "FATAL".equals(fieldName));
    }
    return false;
}
 
Example 18
public static boolean isNullCheck(InstructionHandle h, ConstantPoolGen cpg) {
    if (!(h.getInstruction() instanceof IFNONNULL)) {
        return false;
    }
    h = h.getNext();
    final Instruction newInstruction = h.getInstruction();
    if (!(newInstruction instanceof NEW)) {
        return false;
    }
    final ObjectType loadClassType = ((NEW) newInstruction).getLoadClassType(cpg);
    if (!"java.lang.NullPointerException".equals(loadClassType.getClassName())) {
        return false;
    }
    h = h.getNext();
    return check(h, NULLCHECK1) || check(h, NULLCHECK2);

}
 
Example 19
private void checkConsumedAndProducedValues(Instruction ins, ValueNumber[] consumedValueList, ValueNumber[] producedValueList) {
    int numConsumed = ins.consumeStack(getCPG());
    int numProduced = ins.produceStack(getCPG());

    if (numConsumed == Const.UNPREDICTABLE) {
        throw new InvalidBytecodeException("Unpredictable stack consumption for " + ins);
    }
    if (numProduced == Const.UNPREDICTABLE) {
        throw new InvalidBytecodeException("Unpredictable stack production for " + ins);
    }

    if (consumedValueList.length != numConsumed) {
        throw new IllegalStateException("Wrong number of values consumed for " + ins + ": expected " + numConsumed + ", got "
                + consumedValueList.length);
    }

    if (producedValueList.length != numProduced) {
        throw new IllegalStateException("Wrong number of values produced for " + ins + ": expected " + numProduced + ", got "
                + producedValueList.length);
    }
}
 
Example 20
@Override
public void transfer(BasicBlock basicBlock, InstructionHandle end, ValueNumberFrame start, ValueNumberFrame result)
        throws DataflowAnalysisException {
    if (basicBlock.isExceptionThrower() && isFactValid(start)) {
        /* If exceptionThrower is invoke instruction then it's possible that
         * it was partially executed before an exception occurred
         * So we have to kill available loads when control is transferred to the catch block
         */
        InstructionHandle handle = basicBlock.getExceptionThrower();
        Instruction inst = handle.getInstruction();
        if (inst instanceof InvokeInstruction || inst instanceof INVOKEDYNAMIC) {
            copy(start, result);
            visitor.setFrameAndLocation(result, new Location(handle, basicBlock));
            visitor.setHandle(handle);
            visitor.visitInvokeOnException(inst);
            return;
        }
    }
    super.transfer(basicBlock, end, start, result);
}
 
Example 21
/**
 * Check given Instruction to see if it produces a known value. If so, model
 * the instruction and return true. Otherwise, do nothing and return false.
 * Should only be used for instructions that produce a single value on the
 * top of the stack.
 *
 * @param obj
 *            the Instruction the instruction
 * @return true if the instruction produced a known value and was modeled,
 *         false otherwise
 */
private boolean checkForKnownValue(Instruction obj) {
    if (trackValueNumbers) {
        try {
            // See if the value number loaded here is a known value
            ValueNumberFrame vnaFrameAfter = vnaDataflow.getFactAfterLocation(getLocation());
            if (vnaFrameAfter.isValid()) {
                ValueNumber tosVN = vnaFrameAfter.getTopValue();
                IsNullValue knownValue = getFrame().getKnownValue(tosVN);
                if (knownValue != null) {
                    // System.out.println("Produce known value!");
                    // The value produced by this instruction is known.
                    // Push the known value.
                    modelNormalInstruction(obj, getNumWordsConsumed(obj), 0);
                    produce(knownValue);
                    return true;
                }
            }
        } catch (DataflowAnalysisException e) {
            // Ignore...
        }
    }
    return false;
}
 
Example 22
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException{
    JavaClass clazz = classContext.getJavaClass();
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    CFG cfg = classContext.getCFG(m);

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
        Location loc = i.next();
        Instruction inst = loc.getHandle().getInstruction();

        if (inst instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL invoke = (INVOKEVIRTUAL)inst;
            if( "java.lang.StringBuilder".equals(invoke.getClassName(cpg)) && "append".equals(invoke.getMethodName(cpg))) {
                Instruction prev = loc.getHandle().getPrev().getInstruction();

                if (prev instanceof LDC) {
                    LDC ldc = (LDC)prev;
                    Object value = ldc.getValue(cpg);

                    if (value instanceof String) {
                        String v = (String)value;

                        if ("redirect:".equals(v)) {
                            BugInstance bug = new BugInstance(this, SPRING_UNVALIDATED_REDIRECT_TYPE, Priorities.NORMAL_PRIORITY);
                            bug.addClass(clazz).addMethod(clazz,m).addSourceLine(classContext,m,loc);
                            reporter.reportBug(bug);
                        }
                    }
                }
            }
        }
    }
}
 
Example 23
private TaintLocation getTaintLocation() {
    Instruction inst = getLocation().getHandle().getInstruction();
    if(inst instanceof InvokeInstruction) {
        InvokeInstruction invoke = (InvokeInstruction) inst;
        String sig = invoke.getClassName(cpg).replaceAll("\\.","/") + "." + invoke.getMethodName(cpg) + invoke.getSignature(cpg);
        return new TaintLocation(methodDescriptor, getLocation().getHandle().getPosition(), sig);
    }
    return new TaintLocation(methodDescriptor, getLocation().getHandle().getPosition(), "Oups!!");
}
 
Example 24
/**
 * This method is used to track calls made on a specific object. For instance, this could be used to track if "setHttpOnly(true)"
 * was executed on a specific cookie object.
 *
 * This allows the detector to find interchanged calls like this
 *
 * Cookie cookie1 = new Cookie("f", "foo");     <- This cookie is unsafe
 * Cookie cookie2 = new Cookie("b", "bar");     <- This cookie is safe
 * cookie1.setHttpOnly(false);
 * cookie2.setHttpOnly(true);
 *
 * @param cpg ConstantPoolGen
 * @param startLocation The Location of the cookie initialization call.
 * @param objectStackLocation The index of the cookie on the stack.
 * @param invokeInstruction The instruction we want to detect.s
 * @return The location of the invoke instruction provided for the cookie at a specific index on the stack.
 */
private Location getCookieInstructionLocation(ConstantPoolGen cpg, Location startLocation, int objectStackLocation, String invokeInstruction) {
    Location location = startLocation;
    InstructionHandle handle = location.getHandle();

    int loadedStackValue = 0;

    // Loop until we find the setSecure call for this cookie
    while (handle.getNext() != null) {
        handle = handle.getNext();
        Instruction nextInst = handle.getInstruction();

        // We check if the index of the cookie used for this invoke is the same as the one provided
        if (nextInst instanceof ALOAD) {
            ALOAD loadInst = (ALOAD)nextInst;
            loadedStackValue = loadInst.getIndex();
        }

        if (nextInst instanceof INVOKEVIRTUAL
                && loadedStackValue == objectStackLocation) {
            INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) nextInst;

            String methodNameWithSignature = invoke.getClassName(cpg) + "." + invoke.getMethodName(cpg);

            if (methodNameWithSignature.equals(invokeInstruction)) {

                Integer val = ByteCode.getConstantInt(handle.getPrev());

                if (val != null && val == TRUE_INT_VALUE) {
                    return new Location(handle, location.getBasicBlock());
                }
            }
        }
    }

    return null;
}
 
Example 25
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException {

        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = classContext.getCFG(m);
        
        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
            Location location = i.next();

            Instruction inst = location.getHandle().getInstruction();

            if (inst instanceof INVOKEINTERFACE) {
                INVOKEINTERFACE invoke = (INVOKEINTERFACE) inst;
                String methodName = invoke.getMethodName(cpg);
                String className = invoke.getClassName(cpg);

                if (className.equals("javax.servlet.http.HttpServletResponse") &&
                   (methodName.equals("addHeader") || methodName.equals("setHeader"))) {

                    LDC ldc = ByteCode.getPrevInstruction(location.getHandle().getPrev(), LDC.class);
                    if (ldc != null) {
                        String headerValue = ByteCode.getConstantLDC(location.getHandle().getPrev(), cpg, String.class);
                        if ("Access-Control-Allow-Origin".equalsIgnoreCase((String)ldc.getValue(cpg)) &&
                            (headerValue.contains("*") || "null".equalsIgnoreCase(headerValue))) {

                            JavaClass clz = classContext.getJavaClass();
                            bugReporter.reportBug(new BugInstance(this, PERMISSIVE_CORS, Priorities.HIGH_PRIORITY)
                            .addClass(clz)
                            .addMethod(clz, m)
                            .addSourceLine(classContext, m, location));
                        }
                    }
                }
            }
        }         
        
    }
 
Example 26
Source Project: spotbugs   Source File: IfNull.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after,
        BindingSet bindingSet) throws DataflowAnalysisException {

    // Instruction must be IFNULL or IFNONNULL.
    Instruction ins = handle.getInstruction();
    if (!(ins instanceof IFNULL || ins instanceof IFNONNULL)) {
        return null;
    }

    // Ensure reference used is consistent with previous uses of
    // same variable.
    LocalVariable ref = new LocalVariable(before.getTopValue());
    return addOrCheckDefinition(ref, bindingSet);
}
 
Example 27
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException
    {

        MethodGen methodGen = classContext.getMethodGen(m);
        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = classContext.getCFG(m);

        if (methodGen == null || methodGen.getInstructionList() == null) {
            return; //No instruction .. nothing to do
        }

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

            //
            if (inst instanceof InvokeInstruction) {
//                System.out.println(inst.getName());
                InvokeInstruction invoke = (InvokeInstruction) inst;

                String className = invoke.getClassName(cpg);
                if ("java.io.ObjectInputStream".equals(className) || className.contains("InputStream") || InterfaceUtils.isSubtype(className, "java.io.ObjectInputStream")) {

                    String methodName = invoke.getMethodName(cpg);
                    if (OBJECT_INPUTSTREAM_READ_METHODS.contains(methodName)) {

                        JavaClass clz = classContext.getJavaClass();
                        bugReporter.reportBug(new BugInstance(this, OBJECT_DESERIALIZATION_TYPE, HIGH_PRIORITY) //
                                .addClass(clz).addMethod(clz, m).addSourceLine(classContext,m,location));
                    }
                }

            }
        }
    }
 
Example 28
private Map<String, List<Location>> get_line_location(Method m, ClassContext classContext){
        HashMap<String, List<Location>> all_line_location = new HashMap<>();
        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = null;
        try {
            cfg = classContext.getCFG(m);
        } catch (CFGBuilderException e) {
            e.printStackTrace();
            return all_line_location;
        }
        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
            Location loc = i.next();
            Instruction inst = loc.getHandle().getInstruction();
            if(inst instanceof INVOKEVIRTUAL) {
                INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
//                if (classname.equals(invoke.getClassName(cpg)) &&
//                        methodName.equals(invoke.getMethodName(cpg))) {
                    if(all_line_location.containsKey(invoke.getMethodName(cpg))){
                        all_line_location.get(invoke.getMethodName(cpg)).add(loc);
                    }else {
                        LinkedList<Location> loc_list = new LinkedList<>();
                        loc_list.add(loc);
                        all_line_location.put(invoke.getMethodName(cpg), loc_list);
                    }
//                }
            }
        }
        return all_line_location;
    }
 
Example 29
Source Project: spotbugs   Source File: Monitorenter.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public MatchResult match(InstructionHandle handle, ConstantPoolGen cpg, ValueNumberFrame before, ValueNumberFrame after,
        BindingSet bindingSet) throws DataflowAnalysisException {

    // Instruction must be MONITORENTER.
    Instruction ins = handle.getInstruction();
    if (!(ins instanceof MONITORENTER)) {
        return null;
    }

    // Ensure the object being locked matches any previous
    // instructions which bound our variable name to a value.
    Variable lock = new LocalVariable(before.getTopValue());
    return addOrCheckDefinition(lock, bindingSet);
}
 
Example 30
Source Project: spotbugs   Source File: SelfCalls.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Scan a method for self call sites.
 *
 * @param node
 *            the CallGraphNode for the method to be scanned
 */
private void scan(CallGraphNode node) throws CFGBuilderException {
    Method method = node.getMethod();
    CFG cfg = classContext.getCFG(method);

    if (method.isSynchronized()) {
        hasSynchronization = true;
    }

    Iterator<BasicBlock> i = cfg.blockIterator();
    while (i.hasNext()) {
        BasicBlock block = i.next();
        Iterator<InstructionHandle> j = block.instructionIterator();
        while (j.hasNext()) {
            InstructionHandle handle = j.next();

            Instruction ins = handle.getInstruction();
            if (ins instanceof InvokeInstruction) {
                InvokeInstruction inv = (InvokeInstruction) ins;
                Method called = isSelfCall(inv);
                if (called != null) {
                    // Add edge to call graph
                    CallSite callSite = new CallSite(method, block, handle);
                    callGraph.createEdge(node, callGraph.getNodeForMethod(called), callSite);

                    // Add to called method set
                    calledMethodSet.add(called);
                }
            } else if (ins instanceof MONITORENTER || ins instanceof MONITOREXIT) {
                hasSynchronization = true;
            }
        }
    }
}