Java Code Examples for org.apache.bcel.generic.InvokeInstruction#getSignature()

The following examples show how to use org.apache.bcel.generic.InvokeInstruction#getSignature() . 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: XFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Create an XMethod object from an InvokeInstruction.
 *
 * @param invokeInstruction
 *            the InvokeInstruction
 * @param cpg
 *            ConstantPoolGen from the class containing the instruction
 * @return XMethod representing the method called by the InvokeInstruction
 */
public static XMethod createXMethod(InvokeInstruction invokeInstruction, ConstantPoolGen cpg) {
    String className = invokeInstruction.getClassName(cpg);
    String methodName = invokeInstruction.getName(cpg);
    String methodSig = invokeInstruction.getSignature(cpg);
    if (invokeInstruction instanceof INVOKEDYNAMIC) {
        // XXX the lambda representation makes no sense for XMethod
        // "classical" instruction attributes are filled with garbage, causing
        // the code later to produce crazy errors (looking for non existing types etc)
        // We should NOT be called here from our code, but 3rd party code still may
        // use this method. So *at least* provide a valid class name, which is
        // (don't ask me why) is encoded in the first argument type of the lambda
        // className = invokeInstruction.getArgumentTypes(cpg)[0].toString();
        className = Values.DOTTED_JAVA_LANG_OBJECT;
    }
    return createXMethod(className, methodName, methodSig, invokeInstruction.getOpcode() == Const.INVOKESTATIC);
}
 
Example 2
Source File: CallListAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 3
Source File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 4
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerReturnValueSource(Location location) throws DataflowAnalysisException {
    // Nothing to do if called method does not return a value
    InvokeInstruction inv = (InvokeInstruction) location.getHandle().getInstruction();
    if (inv instanceof INVOKEDYNAMIC) {
        return;
    }
    String calledMethodSig = inv.getSignature(cpg);
    if (calledMethodSig.endsWith(")V")) {
        return;
    }

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

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

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

        When when = (tqa != null) ? tqa.when : When.UNKNOWN;
        registerTopOfStackSource(SourceSinkType.RETURN_VALUE_OF_CALLED_METHOD, location, when, interproc, null);
    }
}
 
Example 5
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 6
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 7
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 8
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Lock isResourceCreation(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg)
        throws DataflowAnalysisException {

    InvokeInstruction inv = toInvokeInstruction(handle.getInstruction());
    if (inv == null) {
        return null;
    }

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

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

            Location location = new Location(handle, basicBlock);
            ValueNumberFrame frame = vnaDataflow.getFactAtLocation(location);
            ValueNumber lockValue = frame.getTopValue();
            if (DEBUG) {
                System.out.println("Lock value is " + lockValue.getNumber() + ", frame=" + frame.toString());
            }
            if (DEBUG) {
                ++numAcquires;
            }
            return new Lock(location, className, lockValue);
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }
    return null;
}
 
Example 9
Source File: TaintFrameModelingVisitor.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 10
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 isMonitorWait(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 isMonitorWait(methodName, methodSig);
}
 
Example 11
Source File: CallToUnconditionalThrower.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 {
    if (BCELUtil.isSynthetic(method) || (method.getAccessFlags() & Const.ACC_BRIDGE) == Const.ACC_BRIDGE) {
        return;
    }
    CFG cfg = classContext.getCFG(method);

    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);

    for (Iterator<BasicBlock> i = cfg.blockIterator(); i.hasNext();) {
        BasicBlock basicBlock = i.next();

        // Check if it's a method invocation.
        if (!basicBlock.isExceptionThrower()) {
            continue;
        }
        InstructionHandle thrower = basicBlock.getExceptionThrower();
        Instruction ins = thrower.getInstruction();
        if (!(ins instanceof InvokeInstruction)) {
            continue;
        }

        InvokeInstruction inv = (InvokeInstruction) ins;
        boolean foundThrower = false;
        boolean foundNonThrower = false;

        if (inv instanceof INVOKEINTERFACE || inv instanceof INVOKEDYNAMIC) {
            continue;
        }

        String className = inv.getClassName(cpg);

        Location loc = new Location(thrower, basicBlock);
        TypeFrame typeFrame = typeDataflow.getFactAtLocation(loc);
        XMethod primaryXMethod = XFactory.createXMethod(inv, cpg);
        // if (primaryXMethod.isAbstract()) continue;
        Set<XMethod> targetSet = null;
        try {

            if (className.startsWith("[")) {
                continue;
            }
            String methodSig = inv.getSignature(cpg);
            if (!methodSig.endsWith("V")) {
                continue;
            }

            targetSet = Hierarchy2.resolveMethodCallTargets(inv, typeFrame, cpg);

            for (XMethod xMethod : targetSet) {
                if (DEBUG) {
                    System.out.println("\tFound " + xMethod);
                }

                boolean isUnconditionalThrower = xMethod.isUnconditionalThrower() && !xMethod.isUnsupported()
                        && !xMethod.isSynthetic();
                if (isUnconditionalThrower) {
                    foundThrower = true;
                    if (DEBUG) {
                        System.out.println("Found thrower");
                    }
                } else {
                    foundNonThrower = true;
                    if (DEBUG) {
                        System.out.println("Found non thrower");
                    }
                }

            }
        } catch (ClassNotFoundException e) {
            analysisContext.getLookupFailureCallback().reportMissingClass(e);
        }
        boolean newResult = foundThrower && !foundNonThrower;
        if (newResult) {
            bugReporter.reportBug(new BugInstance(this, "TESTING", Priorities.NORMAL_PRIORITY)
                    .addClassAndMethod(classContext.getJavaClass(), method)
                    .addString("Call to method that always throws Exception").addMethod(primaryXMethod)
                    .describe(MethodAnnotation.METHOD_CALLED).addSourceLine(classContext, method, loc));
        }

    }

}
 
Example 12
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean returnsString(InvokeInstruction inv) {
    String methodSig = inv.getSignature(getCPG());
    return methodSig.endsWith(")Ljava/lang/String;");
}
 
Example 13
Source File: MethodReturnValueStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

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

        // For now, just support instance methods
        short opcode = ins.getOpcode();
        if (!invokeOpcodeSet.get(opcode)) {
            return null;
        }

        // Is invoked class a subtype of the base class we want
        // FIXME: should test be different for INVOKESPECIAL and
        // INVOKESTATIC?
        InvokeInstruction inv = (InvokeInstruction) ins;
        ReferenceType classType = inv.getReferenceType(cpg);
        if (!Hierarchy.isSubtype(classType, baseClassType)) {
            return null;
        }

        // See if method name and signature match
        String methodName = inv.getMethodName(cpg);
        String methodSig = inv.getSignature(cpg);
        if (!this.methodName.equals(methodName) || !this.methodSig.equals(methodSig)) {
            return null;
        }

        String streamClass = type.getClassName();
        if ("java.sql.CallableStatement".equals(streamClass)) {
            streamClass = "java.sql.PreparedStatement";
        }
        Stream result = new Stream(location, streamClass, streamClass).setIgnoreImplicitExceptions(true).setIsOpenOnCreation(
                true);
        if (!isUninteresting) {
            result.setInteresting(bugType);
        }
        return result;
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 14
Source File: FindSelfComparison2.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 {
    CFG cfg = classContext.getCFG(method);
    ValueNumberDataflow valueNumberDataflow = classContext.getValueNumberDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    MethodGen methodGen = classContext.getMethodGen(method);
    String sourceFile = classContext.getJavaClass().getSourceFileName();

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

        Instruction ins = location.getHandle().getInstruction();
        switch (ins.getOpcode()) {
        case INVOKEVIRTUAL:
        case INVOKEINTERFACE:
            InvokeInstruction iins = (InvokeInstruction) ins;
            String invoking = iins.getName(cpg);
            if (comparatorMethod(invoking) || booleanComparisonMethod(invoking)) {
                if (methodGen.getName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (methodGen.getClassName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (classContext.getJavaClass().getSuperclassName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (location.getHandle().getNext().getInstruction().getOpcode() == POP) {
                    break;
                }
                String sig = iins.getSignature(cpg);

                SignatureParser parser = new SignatureParser(sig);
                if (parser.getNumParameters() == 1
                        && (booleanComparisonMethod(invoking) && sig.endsWith(";)Z") || comparatorMethod(invoking) && sig.endsWith(";)I"))) {
                    checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen,
                            sourceFile);
                }

            }
            break;

        case LOR:
        case LAND:
        case LXOR:
        case LSUB:
        case IOR:
        case IAND:
        case IXOR:
        case ISUB:
            checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPUTATION", method, methodGen, sourceFile);
            break;
        case FCMPG:
        case DCMPG:
        case DCMPL:
        case FCMPL:
            break;
        case LCMP:
        case IF_ACMPEQ:
        case IF_ACMPNE:
        case IF_ICMPNE:
        case IF_ICMPEQ:
        case IF_ICMPGT:
        case IF_ICMPLE:
        case IF_ICMPLT:
        case IF_ICMPGE:
            checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen, sourceFile);
            break;
        default:
            break;
        }

    }
}
 
Example 15
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 16
Source File: Hierarchy.java    From spotbugs with GNU Lesser General Public License v2.1 4 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<JavaClassAndMethod> resolveMethodCallTargets(ReferenceType receiverType,
        InvokeInstruction invokeInstruction, ConstantPoolGen cpg, boolean receiverTypeIsExact) throws ClassNotFoundException {
    HashSet<JavaClassAndMethod> result = new HashSet<>();

    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) {
        JavaClass javaLangObject = AnalysisContext.currentAnalysisContext().lookupClass(Values.DOTTED_JAVA_LANG_OBJECT);
        JavaClassAndMethod classAndMethod = findMethod(javaLangObject, methodName, methodSig, INSTANCE_METHOD);
        if (classAndMethod != null) {
            result.add(classAndMethod);
        }
        return result;
    }

    if (receiverType instanceof NullType) {
        return Collections.<JavaClassAndMethod>emptySet();
    }
    AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();

    // Get the receiver class.
    String receiverClassName = ((ObjectType) receiverType).getClassName();
    JavaClass receiverClass = analysisContext.lookupClass(receiverClassName);
    ClassDescriptor receiverDesc = DescriptorFactory.createClassDescriptorFromDottedClassName(receiverClassName);

    // Figure out the upper bound for the method.
    // This is what will be called if this is not a virtual call site.
    JavaClassAndMethod upperBound = findMethod(receiverClass, methodName, methodSig, CONCRETE_METHOD);
    if (upperBound == null) {
        upperBound = findInvocationLeastUpperBound(receiverClass, methodName, methodSig, CONCRETE_METHOD, false);
    }
    if (upperBound != null) {
        if (DEBUG_METHOD_LOOKUP) {
            System.out.println("Adding upper bound: "
                    + SignatureConverter.convertMethodSignature(upperBound.getJavaClass(), upperBound.getMethod()));
        }
        result.add(upperBound);
    }

    // Is this a virtual call site?
    boolean virtualCall = (invokeInstruction.getOpcode() == Const.INVOKEVIRTUAL || invokeInstruction.getOpcode() == Const.INVOKEINTERFACE)
            && (upperBound == null || !upperBound.getJavaClass().isFinal() && !upperBound.getMethod().isFinal())
            && !receiverTypeIsExact;

    if (virtualCall) {
        if (!Values.DOTTED_JAVA_LANG_OBJECT.equals(receiverClassName)) {

            // This is a true virtual call: assume that any concrete
            // subtype method may be called.
            Set<ClassDescriptor> subTypeSet = analysisContext.getSubtypes2().getSubtypes(receiverDesc);
            for (ClassDescriptor subtype : subTypeSet) {
                XMethod concreteSubtypeMethod = findMethod(subtype, methodName, methodSig, false);
                if (concreteSubtypeMethod != null && (concreteSubtypeMethod.getAccessFlags() & Const.ACC_ABSTRACT) == 0) {
                    result.add(new JavaClassAndMethod(concreteSubtypeMethod));
                }
            }
            if (false && subTypeSet.size() > 500) {
                new RuntimeException(receiverClassName + " has " + subTypeSet.size() + " subclasses, " + result.size()
                        + " of which implement " + methodName + methodSig + " " + invokeInstruction)
                                .printStackTrace(System.out);
            }

        }
    }
    return result;
}
 
Example 17
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Add a method annotation for the method which is called by given
 * instruction.
 *
 * @param cpg
 *            the constant pool for the method containing the call
 * @param inv
 *            the InvokeInstruction
 * @return this object
 */
@Nonnull
public BugInstance addCalledMethod(ConstantPoolGen cpg, InvokeInstruction inv) {
    String className = inv.getClassName(cpg);
    String methodName = inv.getMethodName(cpg);
    String methodSig = inv.getSignature(cpg);
    addMethod(className, methodName, methodSig, inv.getOpcode() == Const.INVOKESTATIC);
    describe(MethodAnnotation.METHOD_CALLED);
    return this;
}
 
Example 18
Source File: Hierarchy.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Look up the method referenced by given InvokeInstruction. This method
 * does <em>not</em> look for implementations in super or subclasses
 * according to the virtual dispatch rules.
 *
 * @param inv
 *            the InvokeInstruction
 * @param cpg
 *            the ConstantPoolGen used by the class the InvokeInstruction
 *            belongs to
 * @param chooser
 *            JavaClassAndMethodChooser to use to pick the method from among
 *            the candidates
 * @return the JavaClassAndMethod, or null if no such method is defined in
 *         the class
 */
public static JavaClassAndMethod findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg, JavaClassAndMethodChooser chooser)
        throws ClassNotFoundException {
    String className = inv.getClassName(cpg);
    String methodName = inv.getName(cpg);
    String methodSig = inv.getSignature(cpg);

    JavaClass jclass = Repository.lookupClass(className);
    return findMethod(jclass, methodName, methodSig, chooser);
}
 
Example 19
Source File: SignatureParser.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Get the number of parameters passed to method invocation.
 *
 * @param inv
 * @param cpg
 * @return int number of parameters
 */
public static int getNumParametersForInvocation(InvokeInstruction inv, ConstantPoolGen cpg) {
    SignatureParser sigParser = new SignatureParser(inv.getSignature(cpg));
    return sigParser.getNumParameters();
}
 
Example 20
Source File: GenericSignatureParser.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Get the number of parameters passed to method invocation.
 *
 * @param inv
 * @param cpg
 * @return int number of parameters
 */
public static int getNumParametersForInvocation(InvokeInstruction inv, ConstantPoolGen cpg) {
    GenericSignatureParser sigParser = new GenericSignatureParser(inv.getSignature(cpg));
    return sigParser.getNumParameters();
}