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

The following examples show how to use org.apache.bcel.generic.InvokeInstruction. 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 static String getInstanceClassName(ConstantPoolGen cpg, InvokeInstruction invoke, TaintFrame frame) {
    try {
        int instanceIndex = frame.getNumArgumentsIncludingObjectInstance(invoke, cpg) - 1;
        if (instanceIndex != -1) {
            assert instanceIndex < frame.getStackDepth();
            Taint instanceTaint = frame.getStackValue(instanceIndex);
            String className = instanceTaint.getRealInstanceClassName();
            if (className != null) {
                return className;
            }
        }
    } catch (DataflowAnalysisException ex) {
        assert false : ex.getMessage();
    }
    String dottedClassName = invoke.getReferenceType(cpg).toString();
    return ClassName.toSlashedClassName(dottedClassName);
}
 
Example 2
private String getInstanceClassName(InvokeInstruction invoke) {
    try {
        int instanceIndex = getFrame().getNumArgumentsIncludingObjectInstance(invoke, cpg) - 1;
        if (instanceIndex != -1) {
            assert instanceIndex < getFrame().getStackDepth();
            Taint instanceTaint = getFrame().getStackValue(instanceIndex);
            String className = instanceTaint.getRealInstanceClassName();
            if (className != null) {
                return className;
            }
        }
    } catch (DataflowAnalysisException ex) {
        assert false : ex.getMessage();
    }
    String dottedClassName = invoke.getReferenceType(cpg).toString();
    return ClassName.toSlashedClassName(dottedClassName);
}
 
Example 3
private void taintMutableArguments(TaintMethodConfig methodConfig, InvokeInstruction obj) {
    if (methodConfig != null && methodConfig.isConfigured()) {
        return;
    }
    Collection<Integer> mutableStackIndices = getMutableStackIndices(obj.getSignature(cpg));
    for (Integer index : mutableStackIndices) {
        assert index >= 0 && index < getFrame().getStackDepth();
        try {
            Taint stackValue = getFrame().getStackValue(index);
            Taint taint = Taint.merge(stackValue, getDefaultValue());
            if (stackValue.hasValidVariableIndex()) {
                // set back the index removed during merging
                taint.setVariableIndex(stackValue.getVariableIndex());
            }
            taint.setRealInstanceClass(stackValue.getRealInstanceClass());
            taint.addLocation(getTaintLocation(), false);
            getFrame().setValue(getFrame().getStackLocation(index), taint);
            setLocalVariableTaint(taint, taint);
        } catch (DataflowAnalysisException ex) {
            throw new InvalidBytecodeException("Not enough values on the stack", ex);
        }
    }
}
 
Example 4
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
                                           InstructionHandle handle) {
    assert invoke != null && cpg != null;

    String method = invoke.getMethodName(cpg);
    String sig    = invoke.getSignature(cpg);
    if(sig.startsWith("(Ljava/lang/String;)")) {
        if(method.startsWith("set")) { // Targeting : x.setPassword("abc123")
            String methodLowerCase = method.toLowerCase();
            for (String password : PASSWORD_WORDS) {
                if (methodLowerCase.contains(password)) {
                    return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE);
                }
            }
        } else if(PASSWORD_WORDS.contains(method.toLowerCase())) { // Targeting : DSL().user("").password(String x)
            return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE);
        }
    }
    return InjectionPoint.NONE;
}
 
Example 5
/**
 * 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 6
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 7
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
                                           InstructionHandle handle) {
    assert invoke != null && cpg != null;

    String method = invoke.getMethodName(cpg);
    String sig    = invoke.getSignature(cpg);

    if(method.equals("registerReceiver")){
        if(sig.contains("Ljava/lang/String;")){
            if(sig.contains(";I)")){
                return new InjectionPoint(new int[]{2}, ANDROID_REGISTER_RECEIVER_TYPE);
            }else{
                return new InjectionPoint(new int[]{1}, ANDROID_REGISTER_RECEIVER_TYPE);
            }
        }
    }
    return InjectionPoint.NONE;
}
 
Example 8
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 9
Source Project: spotbugs   Source File: Hierarchy2.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Find the declared exceptions for the method called by given instruction.
 *
 * @param inv
 *            the InvokeInstruction
 * @param cpg
 *            the ConstantPoolGen used by the class the InvokeInstruction
 *            belongs to
 * @return array of ObjectTypes of thrown exceptions, or null if we can't
 *         find the method implementation
 */
public static @CheckForNull ObjectType[] findDeclaredExceptions(InvokeInstruction inv, ConstantPoolGen cpg) {
    XMethod method = findInvocationLeastUpperBound(inv, cpg, inv instanceof INVOKESTATIC ? STATIC_METHOD : INSTANCE_METHOD);

    if (method == null) {
        return null;
    }
    String[] exceptions = method.getThrownExceptions();

    if (exceptions == null) {
        return new ObjectType[0];
    }

    ObjectType[] result = new ObjectType[exceptions.length];
    for (int i = 0; i < exceptions.length; ++i) {
        result[i] = ObjectTypeFactory.getInstance(ClassName.toDottedClassName(exceptions[i]));
    }
    return result;
}
 
Example 10
@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 11
@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 12
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 13
@Override
public boolean mightCloseResource(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg)
        throws DataflowAnalysisException {
    InvokeInstruction inv = toInvokeInstruction(handle.getInstruction());
    if (inv == null) {
        return false;
    }

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

    try {
        if ("unlock".equals(methodName) && "()V".equals(methodSig)
                && Hierarchy.isSubtype(className, "java.util.concurrent.locks.Lock")) {

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

    return false;
}
 
Example 14
Source Project: commons-bcel   Source File: PLSETestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-262:
 */
public void testB262() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    // get the values() method
    final Method m = gen.getMethodAt(0);
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final InstructionList il = mg.getInstructionList();
    // get the invokevirtual instruction
    final InstructionHandle ih = il.findHandle(3);
    final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());
    // without fix, the getClassName() will throw:
    //   java.lang.IllegalArgumentException: Cannot be used on an array type
    final String cn = ii.getClassName(pool);
    assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}
 
Example 15
/**
 * 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 16
private void handleInvoke(InvokeInstruction inv) {
    ResourceValueFrame frame = getFrame();
    int numSlots = frame.getNumSlots();
    int numConsumed = getNumWordsConsumed(inv);

    // See if the resource instance is passed as an argument
    int instanceArgNum = -1;
    for (int i = numSlots - numConsumed, argCount = 0; i < numSlots; ++i, ++argCount) {
        ResourceValue value = frame.getValue(i);
        if (value.equals(ResourceValue.instance())) {
            instanceArgNum = argCount;
            break;
        }
    }

    if (instanceArgNum >= 0 && instanceEscapes(inv, instanceArgNum)) {
        frame.setStatus(ResourceValueFrame.ESCAPED);
    }

    handleNormalInstruction(inv);
}
 
Example 17
@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 18
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
        InstructionHandle handle) {
    assert invoke != null && cpg != null;

    //1. Verify if the class used has a known sink
    String fullMethodName = getFullMethodName(invoke, cpg);
    //This will skip the most common lookup
    if ("java/lang/Object.<init>()V".equals(fullMethodName)) {
        return InjectionPoint.NONE;
    }

    InjectionPoint injectionPoint = injectionMap.get(fullMethodName);
    if (injectionPoint != null) {
        return injectionPoint;
    }

    try {
        //2. Verify if the super classes match a known sink
        JavaClass classDef = Repository.lookupClass(invoke.getClassName(cpg));
        for (JavaClass superClass : classDef.getSuperClasses()) {
            if ("java.lang.Object".equals(superClass.getClassName())) {
                continue;
            }
            String superClassFullMethodName = superClass.getClassName().replace('.','/')
                    + "." + invoke.getMethodName(cpg) + invoke.getSignature(cpg);
            injectionPoint = injectionMap.get(superClassFullMethodName);
            if (injectionPoint != null) {
                return injectionPoint;
            }
        }
    } catch (ClassNotFoundException e) {
        AnalysisContext.reportMissingClass(e);
    }
    return InjectionPoint.NONE;
}
 
Example 19
/**
 * @param aInstruction
 * @param aPoolGen
 */
public InvokeReference(
    InvokeInstruction aInstruction,
    ConstantPoolGen aPoolGen)
{
    super(aInstruction, aPoolGen);
}
 
Example 20
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
        InstructionHandle handle) {
    InjectionPoint injectionPoint = null;
    for (InjectionSource source : getInjectionSource()) {
        injectionPoint = source.getInjectableParameters(invoke, cpg, handle);
        if (injectionPoint != InjectionPoint.NONE) {
            break;
        }
    }
    if (injectionPoint == null || injectionPoint == InjectionPoint.NONE) {
        injectionPoint = super.getInjectionPoint(invoke, cpg, handle);
    }
    return injectionPoint;
}
 
Example 21
@Override
public void analyzeInstruction(Instruction ins) throws DataflowAnalysisException {
    //Print the bytecode instruction if it is globally configured
    if (FindSecBugsGlobalConfig.getInstance().isDebugPrintInvocationVisited()
            && ins instanceof InvokeInstruction) {
        ByteCode.printOpCode(ins, cpg);
    } else if (FindSecBugsGlobalConfig.getInstance().isDebugPrintInstructionVisited()) {
        ByteCode.printOpCode(ins, cpg);
    }
    super.analyzeInstruction(ins);
}
 
Example 22
/**
 * Regroup the method invocations (INVOKEINTERFACE, INVOKESPECIAL,
 * INVOKESTATIC, INVOKEVIRTUAL)
 *
 * @param obj one of the invoke instructions
 */
private void visitInvoke(InvokeInstruction obj) {
    assert obj != null;
    try {
        TaintMethodConfig methodConfig = getMethodConfig(obj);
        ObjectType realInstanceClass = (methodConfig == null) ?
                null : methodConfig.getOutputTaint().getRealInstanceClass();
        Taint taint = getMethodTaint(methodConfig);
        assert taint != null;
        if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) {
            taint.setDebugInfo(obj.getMethodName(cpg) + "()");
        }
        if (taint.isUnknown()) {
            taint.addLocation(getTaintLocation(), false);
        }
        taintMutableArguments(methodConfig, obj);
        transferTaintToMutables(methodConfig, taint); // adds variable index to taint too
        Taint taintCopy = new Taint(taint);
        // return type is not always the instance type
        taintCopy.setRealInstanceClass(realInstanceClass);
        modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy);
    } catch (Exception e) {
        String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString());
        String methodName = obj.getMethodName(cpg);
        String signature = obj.getSignature(cpg);

        throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e);
    }
}
 
Example 23
private TaintMethodConfig getMethodConfig(InvokeInstruction obj) {
    String signature = obj.getSignature(cpg);
    String returnType = getReturnType(signature);
    String className = getInstanceClassName(obj);
    String methodName = obj.getMethodName(cpg);
    String methodId = "." + methodName + signature;
    TaintMethodConfig config = taintConfig.getMethodConfig(getFrame(), methodDescriptor, className, methodId);
    if (config != null) {
        config = getConfigWithReplaceTags(config, className, methodName);
    }
    if (config != null && config.isConfigured()) {
        return config;
    }
    if (taintConfig.isClassTaintSafe(returnType)) {
        return TaintMethodConfig.SAFE_CONFIG;
    }
    if (config != null) {
        return config;
    }
    if (Constants.CONSTRUCTOR_NAME.equals(methodName)
            && !taintConfig.isClassTaintSafe("L" + className + ";")) {
        try {
            int stackSize = getFrame().getNumArgumentsIncludingObjectInstance(obj, cpg);
            return TaintMethodConfig.getDefaultConstructorConfig(stackSize);
        } catch (DataflowAnalysisException ex) {
            throw new InvalidBytecodeException(ex.getMessage(), ex);
        }
    }
    return null;
}
 
Example 24
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 25
@Override
protected InjectionPoint getInjectionPoint(InvokeInstruction invoke, ConstantPoolGen cpg,
                                           InstructionHandle handle) {
    assert invoke != null && cpg != null;

    if(HASHTABLE_PUT_METHOD.matches(invoke,cpg) || HASHTABLE_SET_PROPERTY.matches(invoke,cpg)) {
        return new InjectionPoint(new int[]{0}, HARD_CODE_PASSWORD_TYPE); //Only the value is
    }
    return InjectionPoint.NONE;
}
 
Example 26
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 27
Source Project: spotbugs   Source File: Hierarchy.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine if given Instruction is a monitor wait.
 *
 * @param ins
 *            the Instruction
 * @param cpg
 *            the ConstantPoolGen for the Instruction
 *
 * @return true if the instruction is a monitor wait, false if not
 */
public static boolean isMonitorNotify(Instruction ins, ConstantPoolGen cpg) {
    if (!(ins instanceof InvokeInstruction)) {
        return false;
    }
    if (ins.getOpcode() == Const.INVOKESTATIC) {
        return false;
    }

    InvokeInstruction inv = (InvokeInstruction) ins;
    String methodName = inv.getMethodName(cpg);
    String methodSig = inv.getSignature(cpg);

    return isMonitorNotify(methodName, methodSig);
}
 
Example 28
/**
 * For test coverage mostly .. not that useful.
 */
@Test
public void probeByteCodeDebug() {
    PrintStream sysOut = mock(PrintStream.class);

    System.out.println("Sysout hijack!");
    PrintStream oldPrintStream = System.out;

    try {
        System.setOut(sysOut);

        InvokeInstruction ins = mock(InvokeInstruction.class);
        ConstantPoolGen cpg = mock(ConstantPoolGen.class);

        when(ins.getClassName(Matchers.<ConstantPoolGen>any())).thenReturn("ClassTest");
        when(ins.getMethodName(Matchers.<ConstantPoolGen>any())).thenReturn("method");
        when(ins.getSignature(Matchers.<ConstantPoolGen>any())).thenReturn("(Lsignature)Lblah");

        //Print invocation
        ByteCode.printOpCode(ins, cpg);

        verify(sysOut, atLeastOnce()).println(contains("ClassTest.method"));
    } finally {
        System.setOut(oldPrintStream);
        System.out.println("Sysout is back!");
    }

}
 
Example 29
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;
            }
        }
    }
}
 
Example 30
Source Project: spotbugs   Source File: Hierarchy2.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Resolve possible instance method call targets.
 *
 * @param receiverType
 *            type of the receiver object
 * @param invokeInstruction
 *            the InvokeInstruction
 * @param cpg
 *            the ConstantPoolGen
 * @param receiverTypeIsExact
 *            if true, the receiver type is known exactly, which should
 *            allow a precise result
 * @return Set of methods which might be called
 * @throws ClassNotFoundException
 */
public static Set<XMethod> resolveMethodCallTargets(ReferenceType receiverType, InvokeInstruction invokeInstruction,
        ConstantPoolGen cpg, boolean receiverTypeIsExact) throws ClassNotFoundException {

    if (invokeInstruction.getOpcode() == Const.INVOKESTATIC) {
        throw new IllegalArgumentException();
    }

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

    // Array method calls aren't virtual.
    // They should just resolve to Object methods.
    if (receiverType instanceof ArrayType) {
        try {
            return Util.emptyOrNonnullSingleton(getXClass(objectDescriptor).findMethod(methodName, methodSig, false));
        } catch (CheckedAnalysisException e) {
            return Collections.<XMethod>emptySet();
        }
    }

    if (receiverType instanceof ObjectType) {
        // Get the receiver class.
        String receiverClassName = ((ObjectType) receiverType).getClassName();

        return resolveVirtualMethodCallTargets(receiverClassName, methodName, methodSig, receiverTypeIsExact,
                invokeInstruction instanceof INVOKESPECIAL);
    }
    assert receiverType instanceof NullType;
    return Collections.<XMethod>emptySet();

}