org.apache.bcel.generic.InvokeInstruction Java Examples

The following examples show how to use org.apache.bcel.generic.InvokeInstruction. 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: PLSETestCase.java    From commons-bcel with 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 #2
Source File: RegisterReceiverPermissionDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: UnsafeJacksonDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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
Source File: DeserializationGadgetDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #5
Source File: ResourceValueFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #6
Source File: AssertionMethods.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #7
Source File: IntuitiveHardcodePasswordDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #8
Source File: InvokeMatcherBuilder.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #10
Source File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #11
Source File: Hierarchy2.java    From spotbugs with 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 #12
Source File: FindUseOfNonSerializableValue.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #13
Source File: AnyMethodReturnValueStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #14
Source File: AbstractInjectionDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #15
Source File: BackwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #16
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #17
Source File: ValueNumberAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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
Source File: LegacyInjectionDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #19
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Looks for the method referenced by the given invoke instruction in the given class.
 * @param jc the class that defines the referenced method
 * @param invoke the instruction that references the method
 * @return the referenced method or null if not found.
 */
private Method getMethod(final JavaClass jc, final InvokeInstruction invoke) {
    final Method[] ms = jc.getMethods();
    for (final Method element : ms) {
        if ( (element.getName().equals(invoke.getMethodName(constantPoolGen))) &&
             (Type.getReturnType(element.getSignature()).equals(invoke.getReturnType(constantPoolGen))) &&
             (objarrayequals(Type.getArgumentTypes(element.getSignature()), invoke.getArgumentTypes(constantPoolGen))) ) {
            return element;
        }
    }

    return null;
}
 
Example #20
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void killLoadsOfObjectsPassed(InvokeInstruction ins) {
    try {

        XMethod called = Hierarchy2.findExactMethod(ins, methodGen.getConstantPool(), Hierarchy.ANY_METHOD);
        if (called != null) {
            NoSideEffectMethodsDatabase nse = Global.getAnalysisCache().getOptionalDatabase(NoSideEffectMethodsDatabase.class);
            if (nse != null && !nse.is(called.getMethodDescriptor(), MethodSideEffectStatus.SE, MethodSideEffectStatus.OBJ)) {
                return;
            }
        }
        FieldSummary fieldSummary = AnalysisContext.currentAnalysisContext().getFieldSummary();
        Set<XField> touched = fieldSummary.getFieldsWritten(called);
        if (!touched.isEmpty()) {
            getFrame().killLoadsOf(touched);
        }


        int passed = getNumWordsConsumed(ins);
        ValueNumber[] arguments = allocateValueNumberArray(passed);
        getFrame().killLoadsWithSimilarName(ins.getClassName(cpg), ins.getMethodName(cpg));
        getFrame().getTopStackWords(arguments);
        for (ValueNumber v : arguments) {
            getFrame().killAllLoadsOf(v);
        }

        // Too many false-positives for primitives without transitive FieldSummary analysis,
        // so currently we simply kill any writable primitive on any method call
        // TODO: implement transitive FieldSummary
        getFrame().killAllLoads(true);

    } catch (DataflowAnalysisException e) {
        AnalysisContext.logError("Error in killLoadsOfObjectsPassed", e);
    }
}
 
Example #21
Source File: ByteCodeTest.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #22
Source File: Hierarchy.java    From spotbugs with 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 #23
Source File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #24
Source File: SelfCalls.java    From spotbugs with 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 #25
Source File: Hierarchy2.java    From spotbugs with 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();

}
 
Example #26
Source File: Stream.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean isStreamClose(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame,
        RepositoryLookupFailureCallback lookupFailureCallback) {
    if (!mightCloseStream(basicBlock, handle, cpg)) {
        return false;
    }

    Instruction ins = handle.getInstruction();

    if ((ins instanceof INVOKEVIRTUAL) || (ins instanceof INVOKEINTERFACE)) {
        // Does this instruction close the stream?
        InvokeInstruction inv = (InvokeInstruction) ins;

        if (!frame.isValid() || !getInstanceValue(frame, inv, cpg).isInstance()) {
            return false;
        }

        // It's a close if the invoked class is any subtype of the stream
        // base class.
        // (Basically, we may not see the exact original stream class,
        // even though it's the same instance.)
        try {
            String classClosed = inv.getClassName(cpg);

            if (relatedType(classClosed)) {
                return true;
            }
            if ("java.io.ObjectOutput".equals(classClosed)) {
                return relatedType("java.io.ObjectOutputStream");
            } else if ("java.io.ObjectInput".equals(classClosed)) {
                return relatedType("java.io.ObjectInputStream");
            }
            return false;
        } catch (ClassNotFoundException e) {
            lookupFailureCallback.reportMissingClass(e);
            return false;
        }
    }

    return false;
}
 
Example #27
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isSafeValue(Location location, ConstantPoolGen cpg) throws CFGBuilderException {
    Instruction prevIns = location.getHandle().getInstruction();
    if (prevIns instanceof LDC || prevIns instanceof GETSTATIC) {
        return true;
    }
    if (prevIns instanceof InvokeInstruction) {
        String methodName = ((InvokeInstruction) prevIns).getMethodName(cpg);
        if (methodName.startsWith("to") && methodName.endsWith("String") && methodName.length() > 8) {
            return true;
        }
    }
    if (prevIns instanceof AALOAD) {
        CFG cfg = classContext.getCFG(method);

        Location prev = getPreviousLocation(cfg, location, true);
        if (prev != null) {
            Location prev2 = getPreviousLocation(cfg, prev, true);
            if (prev2 != null && prev2.getHandle().getInstruction() instanceof GETSTATIC) {
                GETSTATIC getStatic = (GETSTATIC) prev2.getHandle().getInstruction();
                if ("[Ljava/lang/String;".equals(getStatic.getSignature(cpg))) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #28
Source File: StreamFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected boolean instanceEscapes(InvokeInstruction inv, int instanceArgNum) {
    ConstantPoolGen cpg = getCPG();
    String className = inv.getClassName(cpg);

    // System.out.print("[Passed as arg="+instanceArgNum+" at " + inv +
    // "]");

    boolean escapes = (inv.getOpcode() == Const.INVOKESTATIC || instanceArgNum != 0);
    String methodName = inv.getMethodName(cpg);
    String methodSig = inv.getSignature(cpg);
    if (inv.getOpcode() == Const.INVOKEVIRTUAL
            && ("load".equals(methodName) || "loadFromXml".equals(methodName) || "store".equals(methodName) || "save".equals(methodName))
            && "java.util.Properties".equals(className)) {
        escapes = false;
    }
    if (inv.getOpcode() == Const.INVOKEVIRTUAL && ("load".equals(methodName) || "store".equals(methodName))
            && "java.security.KeyStore".equals(className)) {
        escapes = false;
    }
    if (inv.getOpcode() == Const.INVOKEVIRTUAL && "getChannel".equals(methodName)
            && "()Ljava/nio/channels/FileChannel;".equals(methodSig)) {
        escapes = true;
    }

    if (FindOpenStream.DEBUG && escapes) {
        System.out.println("ESCAPE at " + location + " at call to " + className + "." + methodName + ":" + methodSig);
    }

    // Record the fact that this might be a stream escape
    if (stream.getOpenLocation() != null) {
        resourceTracker.addStreamEscape(stream, location);
    }

    return escapes;
}
 
Example #29
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public MethodDescriptor getInvokedMethod(ConstantPoolGen cpg, InvokeInstruction inv) {
    String invoked = inv.getClassName(cpg);
    String methodName = inv.getMethodName(cpg);
    String methodSig = inv.getSignature(cpg);
    MethodDescriptor invokedMethod =
            DescriptorFactory.instance().getMethodDescriptor(ClassName.toSlashedClassName(invoked), methodName, methodSig,
                    inv instanceof INVOKESTATIC);
    return invokedMethod;
}
 
Example #30
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private InvokeInstruction toInvokeInstruction(Instruction ins) {
    short opcode = ins.getOpcode();
    if (opcode != Const.INVOKEVIRTUAL && opcode != Const.INVOKEINTERFACE) {
        return null;
    }
    return (InvokeInstruction) ins;
}