org.apache.bcel.classfile.CodeException Java Examples

The following examples show how to use org.apache.bcel.classfile.CodeException. 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: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Set<String> getSurroundingCaughtExceptions(int pc, int maxTryBlockSize) {
    HashSet<String> result = new HashSet<>();
    if (code == null) {
        throw new IllegalStateException("Not visiting Code");
    }
    int size = maxTryBlockSize;
    if (code.getExceptionTable() == null) {
        return result;
    }
    for (CodeException catchBlock : code.getExceptionTable()) {
        int startPC = catchBlock.getStartPC();
        int endPC = catchBlock.getEndPC();
        if (pc >= startPC && pc <= endPC) {
            int thisSize = endPC - startPC;
            if (size > thisSize) {
                result.clear();
                size = thisSize;
                result.add("C" + catchBlock.getCatchType());
            } else if (size == thisSize) {
                result.add("C" + catchBlock.getCatchType());
            }
        }
    }
    return result;
}
 
Example #2
Source File: DontCatchIllegalMonitorStateException.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(CodeException obj) {
    int type = obj.getCatchType();
    if (type == 0) {
        return;
    }
    String name = getConstantPool().constantToString(getConstantPool().getConstant(type));
    if (DEBUG) {
        String msg = "Catching " + name + " in " + getFullyQualifiedMethodName();
        if (msgs.add(msg)) {
            System.out.println(msg);
        }
    }
    if ("java.lang.IllegalMonitorStateException".equals(name)) {
        bugReporter.reportBug(new BugInstance(this, "IMSE_DONT_CATCH_IMSE", HIGH_PRIORITY).addClassAndMethod(this)
                .addSourceLine(this.classContext, this, obj.getHandlerPC()));
    }

}
 
Example #3
Source File: DismantleBytecode.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean atCatchBlock() {
    for (CodeException e : getCode().getExceptionTable()) {
        if (e.getHandlerPC() == getPC()) {
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: StringCodeAnalysis.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int[] getExceptionScope(){
        try {
            CodeException[] exceptionTable = this.code.getExceptionTable();
            int[] exception_scop = new int[exceptionTable.length * 2];
            for (int i = 0; i < exceptionTable.length; i++) {
                exception_scop[i * 2] = exceptionTable[i].getStartPC();
                exception_scop[i * 2 + 1] = exceptionTable[i].getEndPC();
            }
            return exception_scop;
        }catch (Exception e){
//            e.printStackTrace();
        }
        return new int[0];
    }
 
Example #5
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitCode(Code obj) {
    code = obj;
    super.visitCode(obj);
    CodeException[] exceptions = obj.getExceptionTable();
    for (CodeException exception : exceptions) {
        exception.accept(this);
    }
    Attribute[] attributes = obj.getAttributes();
    for (Attribute attribute : attributes) {
        attribute.accept(this);
    }
    visitAfter(obj);
    code = null;
}
 
Example #6
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitCodeException(final CodeException obj) {
    // Code constraints are checked in Pass3 (3a and 3b).
    // This does not represent an Attribute but is only
    // related to internal BCEL data representation.

    // see visitCode(Code)
}
 
Example #7
Source File: MethodGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @return code exceptions for `Code' attribute
 */
private CodeException[] getCodeExceptions() {
    final int size = exceptionList.size();
    final CodeException[] c_exc = new CodeException[size];
    for (int i = 0; i < size; i++) {
        final CodeExceptionGen c =  exceptionList.get(i);
        c_exc[i] = c.getCodeException(super.getConstantPool());
    }
    return c_exc;
}
 
Example #8
Source File: Util.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull CodeException getSurroundingTryBlock(ConstantPool constantPool, Code code,
        @CheckForNull String vmNameOfExceptionClass, int pc) {
    int size = Integer.MAX_VALUE;
    if (code.getExceptionTable() == null) {
        return null;
    }
    CodeException result = null;
    for (CodeException catchBlock : code.getExceptionTable()) {
        if (vmNameOfExceptionClass != null) {
            Constant catchType = constantPool.getConstant(catchBlock.getCatchType());
            if (catchType == null && !vmNameOfExceptionClass.isEmpty() || catchType instanceof ConstantClass
                    && !((ConstantClass) catchType).getBytes(constantPool).equals(vmNameOfExceptionClass)) {
                continue;
            }
        }
        int startPC = catchBlock.getStartPC();
        int endPC = catchBlock.getEndPC();
        if (pc >= startPC && pc <= endPC) {
            int thisSize = endPC - startPC;
            if (size > thisSize) {
                size = thisSize;
                result = catchBlock;
            }
        }
    }
    return result;
}
 
Example #9
Source File: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Method method) {
    String cName = getDottedClassName();

    for (SubDetector subDetector : subDetectors) {
        subDetector.initMethod(method);
    }

    // System.out.println(getFullyQualifiedMethodName());
    isPublicStaticVoidMain = method.isPublic() && method.isStatic() && "main".equals(getMethodName())
            || cName.toLowerCase().indexOf("benchmark") >= 0;
    prevOpcodeWasReadLine = false;
    Code code = method.getCode();
    if (code != null) {
        this.exceptionTable = code.getExceptionTable();
    }
    if (this.exceptionTable == null) {
        this.exceptionTable = new CodeException[0];
    }
    primitiveObjCtorSeen = null;
    ctorSeen = false;
    randomNextIntState = 0;
    checkForBitIorofSignedByte = false;
    sinceBufferedInputStreamReady = 100000;
    sawCheckForNonNegativeSignedByte = -1000;
    sawLoadOfMinValue = false;
    previousMethodCall = null;

}
 
Example #10
Source File: OpcodeStack.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
    if (e.getCatchType() == 0) {
        return "Ljava/lang/Throwable;";
    }
    Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
    if (c instanceof ConstantClass) {
        return "L" + ((ConstantClass) c).getBytes(dbc.getConstantPool()) + ";";
    }
    return "Ljava/lang/Throwable;";
}
 
Example #11
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean uniqueLocations(Collection<Location> derefLocationSet) {
    boolean uniqueDereferenceLocations = false;
    CodeException[] exceptionTable = method.getCode().getExceptionTable();
    if (exceptionTable == null) {
        return true;
    }
    checkForCatchAll: {
        for (CodeException e : exceptionTable) {
            if (e.getCatchType() == 0) {
                break checkForCatchAll;
            }
        }
        return true;
    }

    LineNumberTable table = method.getLineNumberTable();
    if (table == null) {
        uniqueDereferenceLocations = true;
    } else {
        BitSet linesMentionedMultipleTimes = classContext.linesMentionedMultipleTimes(method);
        for (Location loc : derefLocationSet) {
            int lineNumber = table.getSourceLine(loc.getHandle().getPosition());
            if (lineNumber > 0 && !linesMentionedMultipleTimes.get(lineNumber)) {
                uniqueDereferenceLocations = true;
            }
        }
    }
    return uniqueDereferenceLocations;
}
 
Example #12
Source File: CounterVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCodeException(final CodeException obj)
{
    codeExceptionCount++;
}
 
Example #13
Source File: StringRepresentation.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
@Override
public void visitCodeException(final CodeException obj) {
    tostring = toString(obj);
}
 
Example #14
Source File: MethodGen.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Instantiate from existing method.
 *
 * @param method method
 * @param className class name containing this method
 * @param cp constant pool
 */
public MethodGen(final Method method, final String className, final ConstantPoolGen cp) {
    this(method.getAccessFlags(), Type.getReturnType(method.getSignature()),
        Type.getArgumentTypes(method.getSignature()), null /* may be overridden anyway */
        , method.getName(), className,
        ((method.getAccessFlags() & (Const.ACC_ABSTRACT | Const.ACC_NATIVE)) == 0)
            ? new InstructionList(getByteCodes(method))
            : null,
        cp);
    final Attribute[] attributes = method.getAttributes();
    for (final Attribute attribute : attributes) {
        Attribute a = attribute;
        if (a instanceof Code) {
            final Code c = (Code) a;
            setMaxStack(c.getMaxStack());
            setMaxLocals(c.getMaxLocals());
            final CodeException[] ces = c.getExceptionTable();
            if (ces != null) {
                for (final CodeException ce : ces) {
                    final int type = ce.getCatchType();
                    ObjectType c_type = null;
                    if (type > 0) {
                        final String cen = method.getConstantPool().getConstantString(type, Const.CONSTANT_Class);
                        c_type = ObjectType.getInstance(cen);
                    }
                    final int end_pc = ce.getEndPC();
                    final int length = getByteCodes(method).length;
                    InstructionHandle end;
                    if (length == end_pc) { // May happen, because end_pc is exclusive
                        end = il.getEnd();
                    } else {
                        end = il.findHandle(end_pc);
                        end = end.getPrev(); // Make it inclusive
                    }
                    addExceptionHandler(il.findHandle(ce.getStartPC()), end, il.findHandle(ce.getHandlerPC()),
                        c_type);
                }
            }
            final Attribute[] c_attributes = c.getAttributes();
            for (final Attribute c_attribute : c_attributes) {
                a = c_attribute;
                if (a instanceof LineNumberTable) {
                    final LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable();
                    for (final LineNumber l : ln) {
                        final InstructionHandle ih = il.findHandle(l.getStartPC());
                        if (ih != null) {
                            addLineNumber(ih, l.getLineNumber());
                        }
                    }
                } else if (a instanceof LocalVariableTable) {
                    updateLocalVariableTable((LocalVariableTable) a);
                } else if (a instanceof LocalVariableTypeTable) {
                    this.localVariableTypeTable = (LocalVariableTypeTable) a.copy(cp.getConstantPool());
                } else {
                    addCodeAttribute(a);
                }
            }
        } else if (a instanceof ExceptionTable) {
            final String[] names = ((ExceptionTable) a).getExceptionNames();
            for (final String name2 : names) {
                addException(name2);
            }
        } else if (a instanceof Annotations) {
            final Annotations runtimeAnnotations = (Annotations) a;
            final AnnotationEntry[] aes = runtimeAnnotations.getAnnotationEntries();
            for (final AnnotationEntry element : aes) {
                addAnnotationEntry(new AnnotationEntryGen(element, cp, false));
            }
        } else {
            addAttribute(a);
        }
    }
}
 
Example #15
Source File: NullDerefAndRedundantComparisonFinder.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Examine redundant branches.
 */
private void examineRedundantBranches() {
    for (RedundantBranch redundantBranch : redundantBranchList) {
        if (DEBUG) {
            System.out.println("Redundant branch: " + redundantBranch);
        }
        int lineNumber = redundantBranch.lineNumber;

        // The source to bytecode compiler may sometimes duplicate blocks of
        // code along different control paths. So, to report the bug,
        // we check to ensure that the branch is REALLY determined each
        // place it is duplicated, and that it is determined in the same
        // way.

        boolean confused = undeterminedBranchSet.get(lineNumber)
                || (definitelySameBranchSet.get(lineNumber) && definitelyDifferentBranchSet.get(lineNumber));

        // confused if there is JSR confusion or multiple null checks with
        // different results on the same line

        boolean reportIt = true;

        if (lineMentionedMultipleTimes.get(lineNumber) && confused) {
            reportIt = false;
        } else if (redundantBranch.location.getBasicBlock().isInJSRSubroutine() /*
                                                                                * occurs
                                                                                * in
                                                                                * a
                                                                                * JSR
                                                                                */
                && confused) {
            reportIt = false;
        } else {
            int pc = redundantBranch.location.getHandle().getPosition();
            for (CodeException e : method.getCode().getExceptionTable()) {
                if (e.getCatchType() == 0 && e.getStartPC() != e.getHandlerPC() && e.getEndPC() <= pc
                        && pc <= e.getEndPC() + 5) {
                    reportIt = false;
                }
            }
        }

        if (reportIt) {
            collector.foundRedundantNullCheck(redundantBranch.location, redundantBranch);
        }
    }
}
 
Example #16
Source File: FindNoSideEffectMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Code obj) {
    uselessVoidCandidate = !classInit && !constructor && !getXMethod().isSynthetic() && Type.getReturnType(getMethodSig()) == Type.VOID;
    byte[] code = obj.getCode();
    if (code.length == 4 && (code[0] & 0xFF) == Const.GETSTATIC && (code[3] & 0xFF) == Const.ARETURN) {
        getStaticMethods.add(getMethodDescriptor());
        handleStatus();
        return;
    }

    if (code.length <= 2 && !getXMethod().isStatic() && (getXMethod().isPublic() || getXMethod().isProtected())
            && !getXMethod().isFinal() && (getXClass().isPublic() || getXClass().isProtected())) {
        for (byte[] stubMethod : STUB_METHODS) {
            if (Arrays.equals(stubMethod, code)
                    && (getClassName().endsWith("Visitor") || getClassName().endsWith("Listener") || !hasOtherImplementations(getXMethod()))) {
                // stub method which can be extended: assume it can be extended with possible side-effect
                status = SideEffectStatus.SIDE_EFFECT;
                handleStatus();
                return;
            }
        }
    }
    if (statusMap.containsKey(getMethodDescriptor())) {
        return;
    }
    finallyTargets = new HashSet<>();
    for (CodeException ex : getCode().getExceptionTable()) {
        if (ex.getCatchType() == 0) {
            finallyTargets.add(ex.getHandlerPC());
        }
    }
    finallyExceptionRegisters = new HashSet<>();
    try {
        super.visit(obj);
    } catch (EarlyExitException e) {
        // Ignore
    }
    if (uselessVoidCandidate && code.length > 1
            && (status == SideEffectStatus.UNSURE || status == SideEffectStatus.NO_SIDE_EFFECT)) {
        uselessVoidCandidates.add(getMethodDescriptor());
    }
    handleStatus();
}
 
Example #17
Source File: SynchronizingOnContentsOfFieldToProtectField.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    // System.out.println(state + " " + getPC() + " " + Const.getOpcodeName(seen));
    if (countDown == 2 && seen == Const.GOTO) {
        CodeException tryBlock = getSurroundingTryBlock(getPC());
        if (tryBlock != null && tryBlock.getEndPC() == getPC()) {
            pendingBug.lowerPriority();
        }
    }
    if (countDown > 0) {
        countDown--;
        if (countDown == 0) {
            if (seen == Const.MONITOREXIT) {
                pendingBug.lowerPriority();
            }

            bugReporter.reportBug(pendingBug);
            pendingBug = null;
        }
    }
    if (seen == Const.PUTFIELD) {

        if (syncField != null && getPrevOpcode(1) != Const.ALOAD_0 && syncField.equals(getXFieldOperand())) {
            OpcodeStack.Item value = stack.getStackItem(0);
            int priority = Priorities.HIGH_PRIORITY;
            if (value.isNull()) {
                priority = Priorities.NORMAL_PRIORITY;
            }
            pendingBug = new BugInstance(this, "ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD", priority)
                    .addClassAndMethod(this).addField(syncField).addSourceLine(this);
            countDown = 2;

        }

    }
    if (seen == Const.MONITOREXIT) {
        pendingBug = null;
        countDown = 0;
    }

    if (seen == Const.MONITORENTER) {
        syncField = null;
    }

    switch (state) {
    case 0:
        if (seen == Const.ALOAD_0) {
            state = 1;
        }
        break;
    case 1:
        if (seen == Const.GETFIELD) {
            state = 2;
            field = getXFieldOperand();
        } else {
            state = 0;
        }
        break;
    case 2:
        if (seen == Const.DUP) {
            state = 3;
        } else {
            state = 0;
        }
        break;
    case 3:
        if (isRegisterStore()) {
            state = 4;
        } else {
            state = 0;
        }
        break;
    case 4:
        if (seen == Const.MONITORENTER) {
            state = 0;
            syncField = field;
        } else {
            state = 0;
        }
        break;
    default:
        break;
    }

}
 
Example #18
Source File: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Flush out cached state at the end of a method.
 */
private void flush() {

    if (pendingAbsoluteValueBug != null) {
        absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine);
        pendingAbsoluteValueBug = null;
        pendingAbsoluteValueBugSourceLine = null;
    }
    accumulator.reportAccumulatedBugs();
    if (sawLoadOfMinValue) {
        absoluteValueAccumulator.clearBugs();
    } else {
        absoluteValueAccumulator.reportAccumulatedBugs();
    }
    if (gcInvocationBugReport != null && !sawCurrentTimeMillis) {
        // Make sure the GC invocation is not in an exception handler
        // for OutOfMemoryError.
        boolean outOfMemoryHandler = false;
        for (CodeException handler : exceptionTable) {
            if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) {
                continue;
            }
            int catchTypeIndex = handler.getCatchType();
            if (catchTypeIndex > 0) {
                ConstantPool cp = getThisClass().getConstantPool();
                Constant constant = cp.getConstant(catchTypeIndex);
                if (constant instanceof ConstantClass) {
                    String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp);
                    if ("java/lang/OutOfMemoryError".equals(exClassName)) {
                        outOfMemoryHandler = true;
                        break;
                    }
                }
            }
        }

        if (!outOfMemoryHandler) {
            bugReporter.reportBug(gcInvocationBugReport);
        }
    }

    sawCurrentTimeMillis = false;
    gcInvocationBugReport = null;

    exceptionTable = null;
}
 
Example #19
Source File: Util.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static int getSizeOfSurroundingTryBlock(ConstantPool constantPool, Code code,
        @CheckForNull @SlashedClassName String vmNameOfExceptionClass, int pc) {
    int size = Integer.MAX_VALUE;
    int tightStartPC = 0;
    int tightEndPC = Integer.MAX_VALUE;
    if (code.getExceptionTable() == null) {
        return size;
    }
    for (CodeException catchBlock : code.getExceptionTable()) {
        if (vmNameOfExceptionClass != null) {
            Constant catchType = constantPool.getConstant(catchBlock.getCatchType());
            if (catchType == null && !vmNameOfExceptionClass.isEmpty() || catchType instanceof ConstantClass
                    && !((ConstantClass) catchType).getBytes(constantPool).equals(vmNameOfExceptionClass)) {
                continue;
            }
        }
        int startPC = catchBlock.getStartPC();
        int endPC = catchBlock.getEndPC();
        if (pc >= startPC && pc <= endPC) {
            int thisSize = endPC - startPC;
            if (size > thisSize) {
                size = thisSize;
                tightStartPC = startPC;
                tightEndPC = endPC;
            }
        }
    }
    if (size == Integer.MAX_VALUE) {
        return size;
    }

    // try to guestimate number of lines that correspond
    size = (size + 7) / 8;
    LineNumberTable lineNumberTable = code.getLineNumberTable();
    if (lineNumberTable == null) {
        return size;
    }

    int count = 0;
    for (LineNumber line : lineNumberTable.getLineNumberTable()) {
        if (line.getStartPC() > tightEndPC) {
            break;
        }
        if (line.getStartPC() >= tightStartPC) {
            count++;
        }
    }
    return count;

}
 
Example #20
Source File: BetterVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visitCodeException(CodeException obj) {
    visit(obj);
}
 
Example #21
Source File: BetterVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void visit(CodeException obj) {
}
 
Example #22
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public CodeException getSurroundingTryBlock(String vmNameOfExceptionClass, int pc) {
    if (code == null) {
        throw new IllegalStateException("Not visiting Code");
    }
    return Util.getSurroundingTryBlock(constantPool, code, vmNameOfExceptionClass, pc);
}
 
Example #23
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public CodeException getSurroundingTryBlock(int pc) {
    return getSurroundingTryBlock(null, pc);
}
 
Example #24
Source File: CodeExceptionGen.java    From commons-bcel with Apache License 2.0 2 votes vote down vote up
/**
 * Get CodeException object.<BR>
 *
 * This relies on that the instruction list has already been dumped
 * to byte code or or that the `setPositions' methods has been
 * called for the instruction list.
 *
 * @param cp constant pool
 */
public CodeException getCodeException( final ConstantPoolGen cp ) {
    return new CodeException(startPc.getPosition(), endPc.getPosition()
            + endPc.getInstruction().getLength(), handlerPc.getPosition(),
            (catchType == null) ? 0 : cp.addClass(catchType));
}