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

The following examples show how to use org.apache.bcel.generic.InvokeInstruction#getClassName() . 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: 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 3
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 4
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 5
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 6
Source File: SelfCalls.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Is the given instruction a self-call?
 */
private Method isSelfCall(InvokeInstruction inv) {
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    JavaClass jclass = classContext.getJavaClass();

    String calledClassName = inv.getClassName(cpg);

    // FIXME: is it possible we would see a superclass name here?
    // Not a big deal for now, as we are mostly just interested in calls
    // to private methods, for which we will definitely see the right
    // called class name.
    if (!calledClassName.equals(jclass.getClassName())) {
        return null;
    }

    String calledMethodName = inv.getMethodName(cpg);
    String calledMethodSignature = inv.getSignature(cpg);
    boolean isStaticCall = (inv instanceof INVOKESTATIC);

    // Scan methods for one that matches.
    Method[] methods = jclass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        String signature = method.getSignature();
        boolean isStatic = method.isStatic();

        if (methodName.equals(calledMethodName) && signature.equals(calledMethodSignature) && isStatic == isStaticCall) {
            // This method looks like a match.
            return wantCallsFor(method) ? method : null;
        }
    }

    // Hmm...no matching method found.
    // This is almost certainly because the named method
    // was inherited from a superclass.
    LOG.debug("No method found for {}.{} : {}", calledClassName, calledMethodName, calledMethodSignature);
    return null;
}
 
Example 7
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitInvokeInstruction( final InvokeInstruction i ) {
    final short opcode = i.getOpcode();
    final String class_name = i.getClassName(_cp);
    final String method_name = i.getMethodName(_cp);
    final Type type = i.getReturnType(_cp);
    final Type[] arg_types = i.getArgumentTypes(_cp);
    _out.println("il.append(_factory.createInvoke(\"" + class_name + "\", \"" + method_name
            + "\", " + BCELifier.printType(type) + ", "
            + BCELifier.printArgumentTypes(arg_types) + ", " + CONSTANT_PREFIX
            + Const.getOpcodeName(opcode).toUpperCase(Locale.ENGLISH) + "));");
}
 
Example 8
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 9
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 10
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 11
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 12
Source File: ObjectDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 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) {
//                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 13
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void inspectLocation(JavaClass jclass, ConstantPoolGen cpg, Method method, MethodGen methodGen,
        LinkedList<WarningWithProperties> refComparisonList, LinkedList<WarningWithProperties> stringComparisonList,
        RefComparisonTypeFrameModelingVisitor visitor, TypeDataflow typeDataflow, Location location)
        throws DataflowAnalysisException {
    Instruction ins = location.getHandle().getInstruction();
    short opcode = ins.getOpcode();
    if (opcode == Const.IF_ACMPEQ || opcode == Const.IF_ACMPNE) {
        checkRefComparison(location, jclass, method, methodGen, visitor, typeDataflow, stringComparisonList,
                refComparisonList);
    } else if (ins instanceof InvokeInstruction) {
        InvokeInstruction inv = (InvokeInstruction) ins;
        boolean isStatic = inv instanceof INVOKESTATIC;
        @DottedClassName
        String className = inv.getClassName(cpg);
        String methodName = inv.getMethodName(cpg);
        String methodSig = inv.getSignature(cpg);
        if ("assertSame".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)V".equals(methodSig)) {
            checkRefComparison(location, jclass, method, methodGen, visitor, typeDataflow, stringComparisonList,
                    refComparisonList);
        } else if ("assertFalse".equals(methodName) && "(Z)V".equals(methodSig)) {
            SourceLineAnnotation lastLocation = bugAccumulator.getLastBugLocation();
            InstructionHandle prevHandle = location.getHandle().getPrev();
            if (lastLocation != null && prevHandle != null && lastLocation.getEndBytecode() == prevHandle.getPosition()) {
                bugAccumulator.forgetLastBug();
                if (DEBUG) {
                    System.out.println("Forgetting last bug due to call to " + className + "." + methodName);
                }
            }

        } else {
            boolean equalsMethod = !isStatic && "equals".equals(methodName) && "(Ljava/lang/Object;)Z".equals(methodSig)
                    || isStatic && "assertEquals".equals(methodName)
                            && "(Ljava/lang/Object;Ljava/lang/Object;)V".equals(methodSig)
                    || isStatic && "equal".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)Z".equals(methodSig)
                            && "com.google.common.base.Objects".equals(className)
                    || isStatic && "equals".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)Z".equals(methodSig)
                            && "java.util.Objects".equals(className);

            if (equalsMethod) {
                checkEqualsComparison(location, jclass, method, methodGen, cpg, typeDataflow);
            }
        }
    }

}
 
Example 14
Source File: FindNonSerializableValuePassedToWriteObject.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

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

        if (!(ins instanceof InvokeInstruction)) {
            continue;
        }

        InvokeInstruction invoke = (InvokeInstruction) ins;
        String mName = invoke.getMethodName(cpg);
        if (!"writeObject".equals(mName)) {
            continue;
        }
        String cName = invoke.getClassName(cpg);
        if (!"java.io.ObjectOutput".equals(cName) && !"java.io.ObjectOutputStream".equals(cName)) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable >= 0.9) {
                continue;
            }

            ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

            double isRemote = DeepSubtypeAnalysis.isDeepRemote(refType);
            if (isRemote >= 0.9) {
                continue;
            }
            if (isSerializable < isRemote) {
                isSerializable = isRemote;
            }


            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                    methodGen, sourceFile, handle);

            bugReporter.reportBug(new BugInstance(this, "DMI_NONSERIALIZABLE_OBJECT_WRITTEN",
                    isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                            .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE)
                            .addSourceLine(sourceLineAnnotation));

        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 15
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 16
Source File: Hierarchy.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static @CheckForNull JavaClassAndMethod findInvocationLeastUpperBound(InvokeInstruction inv, ConstantPoolGen cpg,
        JavaClassAndMethodChooser methodChooser) throws ClassNotFoundException {

    if (DEBUG_METHOD_LOOKUP) {
        System.out.println("Find prototype method for " + SignatureConverter.convertMethodSignature(inv, cpg));
    }

    short opcode = inv.getOpcode();

    if (opcode == Const.INVOKESTATIC) {
        if (methodChooser == INSTANCE_METHOD) {
            return null;
        }
    } else {
        if (methodChooser == STATIC_METHOD) {
            return null;
        }
    }

    // Find the method
    if (opcode == Const.INVOKESPECIAL) {
        // Non-virtual dispatch
        return findExactMethod(inv, cpg, methodChooser);
    }
    if (opcode == Const.INVOKEDYNAMIC) {
        return null;
    }
    String className = inv.getClassName(cpg);
    String methodName = inv.getName(cpg);
    String methodSig = inv.getSignature(cpg);
    if (DEBUG_METHOD_LOOKUP) {
        System.out.println("[Class name is " + className + "]");
        System.out.println("[Method name is " + methodName + "]");
        System.out.println("[Method signature is " + methodSig + "]");
    }

    if (className.startsWith(Values.SIG_ARRAY_PREFIX)) {
        // Java 1.5 allows array classes to appear as the class name
        className = Values.DOTTED_JAVA_LANG_OBJECT;
    }

    JavaClass jClass = Repository.lookupClass(className);
    return findInvocationLeastUpperBound(jClass, methodName, methodSig, methodChooser,
            opcode == Const.INVOKEINTERFACE);
}
 
Example 17
Source File: Hierarchy2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static @CheckForNull XMethod findInvocationLeastUpperBound(InvokeInstruction inv, ConstantPoolGen cpg,
        JavaClassAndMethodChooser methodChooser) {

    if (DEBUG_METHOD_LOOKUP) {
        System.out.println("Find prototype method for " + SignatureConverter.convertMethodSignature(inv, cpg));
    }

    short opcode = inv.getOpcode();

    if (opcode == Const.INVOKESTATIC) {
        if (methodChooser == INSTANCE_METHOD) {
            return null;
        }
    } else {
        if (methodChooser == STATIC_METHOD) {
            return null;
        }
    }

    // Find the method
    if (opcode == Const.INVOKESPECIAL) {
        // Non-virtual dispatch
        return findExactMethod(inv, cpg, methodChooser);
    } else {
        String className = inv.getClassName(cpg);
        String methodName = inv.getName(cpg);
        String methodSig = inv.getSignature(cpg);
        if (DEBUG_METHOD_LOOKUP) {
            System.out.println("[Class name is " + className + "]");
            System.out.println("[Method name is " + methodName + "]");
            System.out.println("[Method signature is " + methodSig + "]");
        }

        if (className.startsWith(Values.SIG_ARRAY_PREFIX)) {
            // Java 1.5 allows array classes to appear as the class name
            className = Values.DOTTED_JAVA_LANG_OBJECT;
        }

        try {
            return thisOrNothing(
                    findInvocationLeastUpperBound(getXClassFromDottedClassName(className), methodName, methodSig,
                            opcode == Const.INVOKESTATIC, opcode == Const.INVOKEINTERFACE), methodChooser);
        } catch (CheckedAnalysisException e) {
            return null;
        }

    }
}
 
Example 18
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 19
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 20
Source File: Hierarchy2.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 XMethod findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg, JavaClassAndMethodChooser chooser) {
    String className = inv.getClassName(cpg);
    String methodName = inv.getName(cpg);
    String methodSig = inv.getSignature(cpg);

    XMethod result = findMethod(DescriptorFactory.createClassDescriptorFromDottedClassName(className), methodName, methodSig,
            inv instanceof INVOKESTATIC);

    return thisOrNothing(result, chooser);
}