org.apache.bcel.generic.Instruction Java Examples

The following examples show how to use org.apache.bcel.generic.Instruction. 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: 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 #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: FindTwoLockWait.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean preScreen(MethodGen mg) {
    ConstantPoolGen cpg = mg.getConstantPool();

    int lockCount = mg.isSynchronized() ? 1 : 0;
    boolean sawWaitOrNotify = false;

    InstructionHandle handle = mg.getInstructionList().getStart();
    while (handle != null && !(lockCount >= 2 && sawWaitOrNotify)) {
        Instruction ins = handle.getInstruction();
        if (ins instanceof MONITORENTER) {
            ++lockCount;
        } else if (ins instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL inv = (INVOKEVIRTUAL) ins;
            String methodName = inv.getMethodName(cpg);
            if ("wait".equals(methodName) || methodName.startsWith("notify")) {
                sawWaitOrNotify = true;
            }
        }

        handle = handle.getNext();
    }

    return lockCount >= 2 && sawWaitOrNotify;
}
 
Example #4
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 #5
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean hasManyPreceedingNullTests(int pc) {
    int ifNullTests = 0;
    BitSet seen = new BitSet();
    try {
        for (Iterator<Location> i = classContext.getCFG(method).locationIterator(); i.hasNext();) {
            Location loc = i.next();
            int pc2 = loc.getHandle().getPosition();
            if (pc2 >= pc || pc2 < pc - 30) {
                continue;
            }
            Instruction ins = loc.getHandle().getInstruction();
            if ((ins instanceof IFNONNULL || ins instanceof IFNULL || ins instanceof NullnessConversationInstruction)
                    && !seen.get(pc2)) {
                ifNullTests++;
                seen.set(pc2);
            }
        }
        boolean result = ifNullTests > 2;

        // System.out.println("Preceding null tests " + ifNullTests + " " +
        // ifNonnullTests + " " + result);
        return result;
    } catch (CFGBuilderException e) {
        return false;
    }
}
 
Example #6
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example #7
Source File: Stream.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean isStreamOpen(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, ResourceValueFrame frame) {
    if (isOpenOnCreation) {
        return false;
    }

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

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

    return frame.isValid() && getInstanceValue(frame, inv, cpg).isInstance()
            && matchMethod(inv, cpg, this.getResourceClass(), Const.CONSTRUCTOR_NAME);
}
 
Example #8
Source File: ValueRangeAnalysisFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Condition extractCondition(BackIterator iterator) throws DataflowAnalysisException {
    Instruction comparisonInstruction = iterator.next().getInstruction();
    if (!(comparisonInstruction instanceof IfInstruction)) {
        return null;
    }
    short cmpOpcode = comparisonInstruction.getOpcode();
    int nargs = ((IfInstruction) comparisonInstruction).consumeStack(null);
    if (nargs == 2) {
        return extractTwoArgCondition(iterator, cmpOpcode, "I");
    } else if (nargs == 1) {
        Object val = extractValue(iterator, "I");
        if (val instanceof Value) {
            return new Condition(cmpOpcode, (Value) val, 0);
        } else if (val instanceof LCMP) {
            return extractTwoArgCondition(iterator, cmpOpcode, "J");
        }
    }
    return null;
}
 
Example #9
Source File: NoiseNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example #10
Source File: ValueRangeAnalysisFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Condition extractTwoArgCondition(BackIterator iterator, short cmpOpcode, String signature) throws DataflowAnalysisException {
    Object val2 = extractValue(iterator, signature);
    if (val2 instanceof Instruction) {
        return null;
    }
    Object val1 = extractValue(iterator, signature);
    if (val1 instanceof Instruction) {
        return null;
    }
    if (!(val1 instanceof Value) && !(val2 instanceof Value)) {
        return null;
    }
    if (!(val1 instanceof Value)) {
        Object tmp = val1;
        val1 = val2;
        val2 = tmp;
        cmpOpcode = revertOpcode(cmpOpcode);
    }
    if (!(val2 instanceof Number)) {
        return null;
    }
    return new Condition(cmpOpcode, (Value) val1, (Number) val2);
}
 
Example #11
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 #12
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 #13
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 #14
Source File: UnconditionalValueDerefAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isNullCheck(InstructionHandle h, ConstantPoolGen cpg) {
    if (!(h.getInstruction() instanceof IFNONNULL)) {
        return false;
    }
    h = h.getNext();
    final Instruction newInstruction = h.getInstruction();
    if (!(newInstruction instanceof NEW)) {
        return false;
    }
    final ObjectType loadClassType = ((NEW) newInstruction).getLoadClassType(cpg);
    if (!"java.lang.NullPointerException".equals(loadClassType.getClassName())) {
        return false;
    }
    h = h.getNext();
    return check(h, NULLCHECK1) || check(h, NULLCHECK2);

}
 
Example #15
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 #16
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 #17
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void checkConsumedAndProducedValues(Instruction ins, ValueNumber[] consumedValueList, ValueNumber[] producedValueList) {
    int numConsumed = ins.consumeStack(getCPG());
    int numProduced = ins.produceStack(getCPG());

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

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

    if (producedValueList.length != numProduced) {
        throw new IllegalStateException("Wrong number of values produced for " + ins + ": expected " + numProduced + ", got "
                + producedValueList.length);
    }
}
 
Example #18
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public void start() {
    if (!_mg.isAbstract() && !_mg.isNative()) {
        for (InstructionHandle ih = _mg.getInstructionList().getStart(); ih != null; ih = ih
                .getNext()) {
            final Instruction i = ih.getInstruction();
            if (i instanceof BranchInstruction) {
                branch_map.put(i, ih); // memorize container
            }
            if (ih.hasTargeters()) {
                if (i instanceof BranchInstruction) {
                    _out.println("    InstructionHandle ih_" + ih.getPosition() + ";");
                } else {
                    _out.print("    InstructionHandle ih_" + ih.getPosition() + " = ");
                }
            } else {
                _out.print("    ");
            }
            if (!visitInstruction(i)) {
                i.accept(this);
            }
        }
        updateBranchTargets();
        updateExceptionHandlers();
    }
}
 
Example #19
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param handle instruction handle which loads the object for further GETFIELD/PUTFIELD operation
 * @return true if this object is known to be non-null
 */
private boolean isSafeFieldSource(InstructionHandle handle) {
    while (handle != null && handle.getInstruction().getOpcode() == Const.DUP) {
        // Some compilers generate DUP for field increment code like
        // ALOAD_0 / DUP / GETFIELD x / ICONST_1 / IADD / PUTFIELD x
        handle = handle.getPrev();
    }
    if (handle == null) {
        return false;
    }
    Instruction inst = handle.getInstruction();
    if (inst.getOpcode() == Const.ALOAD_0) {
        return true;
    }
    return inst instanceof GETFIELD && ((GETFIELD) inst).getFieldName(cpg).startsWith("this$");
}
 
Example #20
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 #21
Source File: IsNullValueFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Check given Instruction to see if it produces a known value. If so, model
 * the instruction and return true. Otherwise, do nothing and return false.
 * Should only be used for instructions that produce a single value on the
 * top of the stack.
 *
 * @param obj
 *            the Instruction the instruction
 * @return true if the instruction produced a known value and was modeled,
 *         false otherwise
 */
private boolean checkForKnownValue(Instruction obj) {
    if (trackValueNumbers) {
        try {
            // See if the value number loaded here is a known value
            ValueNumberFrame vnaFrameAfter = vnaDataflow.getFactAfterLocation(getLocation());
            if (vnaFrameAfter.isValid()) {
                ValueNumber tosVN = vnaFrameAfter.getTopValue();
                IsNullValue knownValue = getFrame().getKnownValue(tosVN);
                if (knownValue != null) {
                    // System.out.println("Produce known value!");
                    // The value produced by this instruction is known.
                    // Push the known value.
                    modelNormalInstruction(obj, getNumWordsConsumed(obj), 0);
                    produce(knownValue);
                    return true;
                }
            }
        } catch (DataflowAnalysisException e) {
            // Ignore...
        }
    }
    return false;
}
 
Example #22
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void visitInvokeOnException(Instruction obj) {
    if (!REDUNDANT_LOAD_ELIMINATION || !getFrame().hasAvailableLoads()) {
        return;
    }
    if (obj instanceof INVOKEDYNAMIC) {
        killLoadsOfObjectsPassed((INVOKEDYNAMIC) obj);
        return;
    }
    InvokeInstruction inv = (InvokeInstruction) obj;
    if ((inv instanceof INVOKEINTERFACE || inv instanceof INVOKEVIRTUAL)
            && inv.getMethodName(cpg).toLowerCase().indexOf("lock") >= 0) {
        // Don't know what this method invocation is doing.
        // Kill all loads.
        getFrame().killAllLoads();
        return;
    }
    if (inv instanceof INVOKEVIRTUAL && "cast".equals(inv.getMethodName(cpg)) && "java.lang.Class".equals(inv.getClassName(cpg))) {
        // No-op
        return;
    }
    if (inv instanceof INVOKESTATIC) {
        String methodName = inv.getName(cpg);
        if (("forName".equals(methodName) && "java.lang.Class".equals(inv.getClassName(cpg)) || "class$".equals(methodName))
                && "(Ljava/lang/String;)Ljava/lang/Class;".equals(inv.getSignature(cpg))
                || (Hierarchy.isInnerClassAccess((INVOKESTATIC) inv, cpg) && loadedFieldSet.getField(handle) != null)) {
            return;
        }
    }

    killLoadsOfObjectsPassed(inv);
    if (inv instanceof INVOKESTATIC) {
        getFrame().killAllLoadsOf(null);
    }
}
 
Example #23
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Store an instance field.
 *
 * @param instanceField
 *            the field
 * @param obj
 *            the instruction which stores the field
 * @param pushStoredValue
 *            push the stored value onto the stack (because we are modeling
 *            an inner-class field access method)
 */
private void storeInstanceField(XField instanceField, Instruction obj, boolean pushStoredValue) {
    if (RLE_DEBUG) {
        System.out.println("[storeInstanceField for field " + instanceField + " in instruction " + handle);
    }

    ValueNumberFrame frame = getFrame();

    int numWordsConsumed = getNumWordsConsumed(obj);
    /*
     * System.out.println("Instruction is " + handle);
     * System.out.println("numWordsConsumed="+numWordsConsumed);
     */
    ValueNumber[] inputValueList = popInputValues(numWordsConsumed);
    ValueNumber reference = inputValueList[0];
    ValueNumber[] storedValue = allocateValueNumberArray(inputValueList.length - 1);
    System.arraycopy(inputValueList, 1, storedValue, 0, inputValueList.length - 1);

    if (pushStoredValue) {
        pushOutputValues(storedValue);
    }

    // Kill all previous loads of the same field,
    // in case there is aliasing we don't know about
    frame.killLoadsOfField(instanceField);

    // Forward substitution
    frame.addAvailableLoad(new AvailableLoad(reference, instanceField), storedValue);

    if (RLE_DEBUG) {
        System.out.println("[making store of " + instanceField + " available]");
    }

    if (VERIFY_INTEGRITY) {
        /*
         * System.out.println("pushStoredValue="+pushStoredValue);
         */
        checkConsumedAndProducedValues(obj, inputValueList, pushStoredValue ? storedValue : EMPTY_INPUT_VALUE_LIST);
    }
}
 
Example #24
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;
}
 
Example #25
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Assures the generic preconditions of a LoadClass instance.
 * The referenced class is loaded and pass2-verified.
 */
@Override
public void visitLoadClass(final LoadClass loadClass) {
    final ObjectType t = loadClass.getLoadClassType(constantPoolGen);
    if (t != null) {// null means "no class is loaded"
        final Verifier v = VerifierFactory.getVerifier(t.getClassName());
        final VerificationResult vr = v.doPass1();
        if (vr.getStatus() != VerificationResult.VERIFIED_OK) {
            constraintViolated((Instruction) loadClass,
                "Class '"+loadClass.getLoadClassType(constantPoolGen).getClassName()+"' is referenced, but cannot be loaded: '"+vr+"'.");
        }
    }
}
 
Example #26
Source File: Frame.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the slot the object instance referred to by given instruction is
 * located in.
 *
 * @param ins
 *            the Instruction
 * @param cpg
 *            the ConstantPoolGen for the method
 * @return stack slot the object instance is in
 * @throws DataflowAnalysisException
 */
public int getInstanceSlot(Instruction ins, ConstantPoolGen cpg) throws DataflowAnalysisException {
    if (!isValid()) {
        throw new DataflowAnalysisException("Accessing invalid frame at " + ins);
    }
    int numConsumed = ins.consumeStack(cpg);
    if (numConsumed == Const.UNPREDICTABLE) {
        throw new DataflowAnalysisException("Unpredictable stack consumption in " + ins);
    }
    if (numConsumed > getStackDepth()) {
        throw new DataflowAnalysisException("Stack underflow " + ins);
    }
    return getNumSlots() - numConsumed;
}
 
Example #27
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int getIntValue(InstructionHandle handle) {
    Instruction instruction = handle.getInstruction();
    if (instruction instanceof ICONST) {
        return ((ICONST) instruction).getValue().intValue();
    }
    return -1;
}
 
Example #28
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitAllocationInstruction( final AllocationInstruction i ) {
    Type type;
    if (i instanceof CPInstruction) {
        type = ((CPInstruction) i).getType(_cp);
    } else {
        type = ((NEWARRAY) i).getType();
    }
    final short opcode = ((Instruction) i).getOpcode();
    int dim = 1;
    switch (opcode) {
        case Const.NEW:
            _out.println("il.append(_factory.createNew(\"" + ((ObjectType) type).getClassName()
                    + "\"));");
            break;
        case Const.MULTIANEWARRAY:
            dim = ((MULTIANEWARRAY) i).getDimensions();
            //$FALL-THROUGH$
        case Const.ANEWARRAY:
        case Const.NEWARRAY:
            if (type instanceof ArrayType) {
                type = ((ArrayType) type).getBasicType();
            }
            _out.println("il.append(_factory.createNewArray(" + BCELifier.printType(type)
                    + ", (short) " + dim + "));");
            break;
        default:
            throw new IllegalArgumentException("Unhandled opcode: " + opcode);
    }
}
 
Example #29
Source File: StreamResourceTracker.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Stream isResourceCreation(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg) {

    // Use precomputed map of Locations to Stream creations,
    // if present. Note that we don't care about preexisting
    // resources here.
    if (resourceCollection != null) {
        return resourceCollection.getCreatedResource(new Location(handle, basicBlock));
    }

    Instruction ins = handle.getInstruction();
    if (!(ins instanceof TypedInstruction)) {
        return null;
    }

    Type type = ((TypedInstruction) ins).getType(cpg);
    if (!(type instanceof ObjectType)) {
        return null;
    }

    Location location = new Location(handle, basicBlock);

    // All StreamFactories are given an opportunity to
    // look at the location and possibly identify a created stream.
    for (StreamFactory aStreamFactoryList : streamFactoryList) {
        Stream stream = aStreamFactoryList.createStream(location, (ObjectType) type, cpg, lookupFailureCallback);
        if (stream != null) {
            return stream;
        }
    }

    return null;
}
 
Example #30
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);
}