org.apache.bcel.classfile.Code Java Examples

The following examples show how to use org.apache.bcel.classfile.Code. 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: UnpackedCodeFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public UnpackedCode analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = getMethod(analysisCache, descriptor);
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    byte[] instructionList = code.getCode();

    // Create callback
    UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);

    // Scan the method.
    BytecodeScanner scanner = new BytecodeScanner();
    scanner.scan(instructionList, callback);

    return callback.getUnpackedCode();

}
 
Example #2
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void compare(final String name, final Method method) {
    // System.out.println("Method: " + m);
    final Code code = method.getCode();
    if (code == null) {
        return; // e.g. abstract method
    }
    final byte[] src = code.getCode();
    final InstructionList instructionList = new InstructionList(src);
    final byte[] out = instructionList.getByteCode();
    if (src.length == out.length) {
        assertArrayEquals(name + ": " + method.toString(), src, out);
    } else {
        System.out.println(name + ": " + method.toString() + " " + src.length + " " + out.length);
        System.out.println(bytesToHex(src));
        System.out.println(bytesToHex(out));
        for (final InstructionHandle instructionHandle : instructionList) {
            System.out.println(instructionHandle.toString(false));
        }
        fail("Array comparison failure");
    }
}
 
Example #3
Source File: UnreadFields.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {

    count_aload_1 = 0;
    previousOpcode = -1;
    previousPreviousOpcode = -1;
    data.nullTested.clear();
    seenInvokeStatic = false;
    seenMonitorEnter = getMethod().isSynchronized();
    data.staticFieldsReadInThisMethod.clear();
    super.visit(obj);
    if (Const.CONSTRUCTOR_NAME.equals(getMethodName()) && count_aload_1 > 1
            && (getClassName().indexOf('$') >= 0 || getClassName().indexOf('+') >= 0)) {
        data.needsOuterObjectInConstructor.add(getDottedClassName());
        // System.out.println(betterClassName +
        // " needs outer object in constructor");
    }
    bugAccumulator.reportAccumulatedBugs();
}
 
Example #4
Source File: OverridingMethodsMustInvokeSuperDetector.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code code) {
    if (getMethod().isStatic() || getMethod().isPrivate() || getMethod().isSynthetic()) {
        return;
    }

    XMethod overrides = Lookup.findSuperImplementorAsXMethod(getThisClass(), getMethodName(), getEffectiveMethodSig(), bugReporter);

    if (overrides == null) {
        return;
    }

    AnnotationValue annotation = overrides.getAnnotation(mustOverrideAnnotation);

    if (annotation == null) {
        return;
    }

    sawCallToSuper = false;
    super.visit(code);

    if (!sawCallToSuper) {
        bugReporter.reportBug(new BugInstance(this, "OVERRIDING_METHODS_MUST_INVOKE_SUPER", NORMAL_PRIORITY)
                .addClassAndMethod(this).addString("Method must invoke override method in superclass"));
    }
}
 
Example #5
Source File: FindSelfComparison.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    if (DEBUG) {
        System.out.println(getFullyQualifiedMethodName());
    }
    whichRegister = -1;
    registerLoadCount = 0;
    lastMethodCall = -1;
    resetDoubleAssignmentState();
    super.visit(obj);
    resetDoubleAssignmentState();
    bugAccumulator.reportAccumulatedBugs();
    if (DEBUG) {
        System.out.println();
    }
}
 
Example #6
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean markedAsNotUsable(Method obj) {
    for (Attribute a : obj.getAttributes()) {
        if (a instanceof Deprecated) {
            return true;
        }
    }
    Code code = obj.getCode();
    if (code == null) {
        return false;
    }
    byte[] codeBytes = code.getCode();
    if (codeBytes.length > 1 && codeBytes.length < 10) {
        int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff;
        if (lastOpcode != Const.ATHROW) {
            return false;
        }
        for (int b : codeBytes) {
            if ((b & 0xff) == Const.RETURN) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #7
Source File: InitializationChain.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    fieldsReadInThisConstructor = new HashSet<>();
    super.visit(obj);
    staticFieldsRead.put(getXMethod(), fieldsReadInThisConstructor);
    requires.remove(getDottedClassName());
    if ("java.lang.System".equals(getDottedClassName())) {
        requires.add("java.io.FileInputStream");
        requires.add("java.io.FileOutputStream");
        requires.add("java.io.BufferedInputStream");
        requires.add("java.io.BufferedOutputStream");
        requires.add("java.io.PrintStream");
    }
    if (!requires.isEmpty()) {
        classRequires.put(getDottedClassName(), requires);
        requires = new TreeSet<>();
    }
}
 
Example #8
Source File: WaitInLoop.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    sawWait = false;
    sawAwait = false;
    waitHasTimeout = false;
    sawNotify = false;
    earliestJump = 9999999;
    super.visit(obj);
    if ((sawWait || sawAwait) && waitAt < earliestJump) {
        String bugType = sawWait ? "WA_NOT_IN_LOOP" : "WA_AWAIT_NOT_IN_LOOP";
        bugReporter.reportBug(new BugInstance(this, bugType, waitHasTimeout ? LOW_PRIORITY : NORMAL_PRIORITY)
                .addClassAndMethod(this).addSourceLine(this, waitAt));
    }
    if (sawNotify) {
        bugReporter.reportBug(new BugInstance(this, "NO_NOTIFY_NOT_NOTIFYALL", LOW_PRIORITY).addClassAndMethod(this)
                .addSourceLine(this, notifyPC));
    }
}
 
Example #9
Source File: TypeReturnNull.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code code) {
    SignatureParser sp = new SignatureParser(getMethodSig());
    // Check to see if the method has expected return type
    String returnSignature = sp.getReturnTypeSignature();
    if (!matchesReturnSignature(returnSignature)) {
        return;
    }

    if (isExplicitlyNullable()) {
        return;
    }

    super.visit(code); // make callbacks to sawOpcode for all opcodes
    bugAccumulator.reportAccumulatedBugs();
}
 
Example #10
Source File: MethodBytecodeSetFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public MethodBytecodeSet analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    byte[] instructionList = code.getCode();

    // Create callback
    UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback(instructionList.length);

    // Scan the method.
    BytecodeScanner scanner = new BytecodeScanner();
    scanner.scan(instructionList, callback);

    UnpackedCode unpackedCode = callback.getUnpackedCode();
    MethodBytecodeSet result = null;
    if (unpackedCode != null) {
        result = unpackedCode.getBytecodeSet();
    }

    return result;
}
 
Example #11
Source File: MethodGen.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Return string representation close to declaration format,
 * `public static void main(String[]) throws IOException', e.g.
 *
 * @return String representation of the method.
 */
@Override
public final String toString() {
    final String access = Utility.accessToString(super.getAccessFlags());
    String signature = Type.getMethodSignature(super.getType(), argTypes);
    signature = Utility.methodSignatureToString(signature, super.getName(), access, true,
            getLocalVariableTable(super.getConstantPool()));
    final StringBuilder buf = new StringBuilder(signature);
    for (final Attribute a : getAttributes()) {
        if (!((a instanceof Code) || (a instanceof ExceptionTable))) {
            buf.append(" [").append(a).append("]");
        }
    }

    if (throwsList.size() > 0) {
        for (final String throwsDescriptor : throwsList) {
            buf.append("\n\t\tthrows ").append(throwsDescriptor);
        }
    }
    return buf.toString();
}
 
Example #12
Source File: PreferZeroLengthArrays.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    // Solution to sourceforge bug 1765925; returning null is the
    // convention used by java.io.File.listFiles()
    if ("listFiles".equals(getMethodName())) {
        return;
    }
    String returnType = getMethodSig().substring(getMethodSig().indexOf(')') + 1);
    if (returnType.startsWith("[")) {
        nullOnTOS = false;
        super.visit(obj);
        if (!found.isEmpty()) {
            BugInstance bug = new BugInstance(this, "PZLA_PREFER_ZERO_LENGTH_ARRAYS", LOW_PRIORITY).addClassAndMethod(this);
            for (SourceLineAnnotation s : found) {
                bug.add(s);
            }
            bugReporter.reportBug(bug);
            found.clear();
        }
    }
}
 
Example #13
Source File: CheckAnalysisContextContainedAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code code) {
    boolean interesting = testingEnabled;
    if (interesting) {
        // initialize any variables we want to initialize for the method
        super.visit(code); // make callbacks to sawOpcode for all opcodes
    }
    accumulator.reportAccumulatedBugs();
}
 
Example #14
Source File: BuildStringPassthruGraph.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitAfter(Code obj) {
    super.visitAfter(obj);
    for (int i = 0; i < nArgs; i++) {
        List<MethodParameter> list = passedParameters[i];
        if (list != null) {
            MethodParameter cur = new MethodParameter(getMethodDescriptor(), i);
            for (MethodParameter mp : list) {
                cache.addEdge(mp, cur);
            }
        }
    }
}
 
Example #15
Source File: ClassFeatureSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Initialize from given JavaClass.
 *
 * @param javaClass
 *            the JavaClass
 * @return this object
 */
public ClassFeatureSet initialize(JavaClass javaClass) {
    this.className = javaClass.getClassName();
    this.isInterface = javaClass.isInterface();

    addFeature(CLASS_NAME_KEY + transformClassName(javaClass.getClassName()));

    for (Method method : javaClass.getMethods()) {
        if (!isSynthetic(method)) {
            String transformedMethodSignature = transformMethodSignature(method.getSignature());

            if (method.isStatic() || !overridesSuperclassMethod(javaClass, method)) {
                addFeature(METHOD_NAME_KEY + method.getName() + ":" + transformedMethodSignature);
            }

            Code code = method.getCode();
            if (code != null && code.getCode() != null && code.getCode().length >= MIN_CODE_LENGTH) {
                addFeature(CODE_LENGTH_KEY + method.getName() + ":" + transformedMethodSignature + ":"
                        + code.getCode().length);
            }
        }
    }

    for (Field field : javaClass.getFields()) {
        if (!isSynthetic(field)) {
            addFeature(FIELD_NAME_KEY + field.getName() + ":" + transformSignature(field.getSignature()));
        }
    }

    return this;
}
 
Example #16
Source File: FindPuzzlers.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    prevOpcodeIncrementedRegister = -1;
    best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = LOW_PRIORITY + 1;
    prevOpCode = Const.NOP;
    previousMethodInvocation = null;
    badlyComputingOddState = 0;
    resetIMulCastLong();
    imul_distance = 10000;
    ternaryConversionState = 0;
    becameTop = -1;
    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    pendingUnreachableBranch = null;
}
 
Example #17
Source File: TestingGround2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code code) {
    boolean interesting = true;
    if (interesting) {
        // initialize any variables we want to initialize for the method
        super.visit(code); // make callbacks to sawOpcode for all opcodes
    }
}
 
Example #18
Source File: FinalizerNullsFields.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    state = 0;
    sawAnythingElse = false;
    sawFieldNulling = false;
    if (inFinalize) {
        super.visit(obj);
        bugAccumulator.reportAccumulatedBugs();
        if (!sawAnythingElse && sawFieldNulling) {
            BugInstance bug = new BugInstance(this, "FI_FINALIZER_ONLY_NULLS_FIELDS", HIGH_PRIORITY).addClassAndMethod(this);
            bugReporter.reportBug(bug);
        }
    }
}
 
Example #19
Source File: StartInConstructor.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    if (Const.CONSTRUCTOR_NAME.equals(getMethodName()) && (getMethod().isPublic() || getMethod().isProtected())) {
        super.visit(obj);
        bugAccumulator.reportAccumulatedBugs();
    }
}
 
Example #20
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean safeCallToPrimateParseMethod(XMethod calledMethod, Location location) {
    int position = location.getHandle().getPosition();

    if (Values.DOTTED_JAVA_LANG_INTEGER.equals(calledMethod.getClassName())) {

        ConstantPool constantPool = classContext.getJavaClass().getConstantPool();
        Code code = method.getCode();

        int catchSize;

        catchSize = Util.getSizeOfSurroundingTryBlock(constantPool, code, "java/lang/NumberFormatException", position);
        if (catchSize < Integer.MAX_VALUE) {
            return true;
        }
        catchSize = Util.getSizeOfSurroundingTryBlock(constantPool, code, "java/lang/IllegalArgumentException", position);
        if (catchSize < Integer.MAX_VALUE) {
            return true;
        }

        catchSize = Util.getSizeOfSurroundingTryBlock(constantPool, code, "java/lang/RuntimeException", position);
        if (catchSize < Integer.MAX_VALUE) {
            return true;
        }
        catchSize = Util.getSizeOfSurroundingTryBlock(constantPool, code, "java/lang/Exception", position);
        if (catchSize < Integer.MAX_VALUE) {
            return true;
        }
    }
    return false;
}
 
Example #21
Source File: AtomicityProblem.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    if (DEBUG) {
        System.out.println("Checking " + obj);
    }
    lastQuestionableCheckTarget = -1;
    super.visit(obj);
}
 
Example #22
Source File: ReadReturnShouldBeChecked.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    sawAvailable = 0;
    sawRead = false;
    sawSkip = false;
    super.visit(obj);
    accumulator.reportAccumulatedBugs();
}
 
Example #23
Source File: OpcodeStack.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public final void visitCode(Code obj) {
    if (!getMethodDescriptor().equals(descriptor)) {
        throw new IllegalStateException();
    }
    if (DEBUG1) {
        System.out.println(descriptor);
    }
    stack.resetForMethodEntry0(this);
    super.visitCode(obj);
    if (DEBUG1) {
        System.out.println();
    }
}
 
Example #24
Source File: EqualsOperandShouldHaveClassCompatibleWithThis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    if ("equals".equals(getMethodName()) && "(Ljava/lang/Object;)Z".equals(getMethodSig())) {
        super.visit(obj);
        if (AnalysisContext.currentAnalysisContext().isApplicationClass(getThisClass())) {
            bugAccumulator.reportAccumulatedBugs();
        }
        bugAccumulator.clearBugs();
    }

}
 
Example #25
Source File: FindFloatEquality.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    priority = LOW_PRIORITY;

    state = SAW_NOTHING;

    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    if (!found.isEmpty()) {
        BugInstance bug = new BugInstance(this, "FE_FLOATING_POINT_EQUALITY", priority).addClassAndMethod(this);

        boolean first = true;
        for (SourceLineAnnotation s : found) {
            bug.add(s);
            if (first) {
                first = false;
            } else {
                bug.describe(SourceLineAnnotation.ROLE_ANOTHER_INSTANCE);
            }
        }

        bugReporter.reportBug(bug);

        found.clear();
    }
}
 
Example #26
Source File: SynchronizingOnContentsOfFieldToProtectField.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code code) {
    // System.out.println(getMethodName());

    state = 0;
    countDown = 0;
    super.visit(code); // make callbacks to sawOpcode for all opcodes
    syncField = field = null;
    pendingBug = null;

}
 
Example #27
Source File: FindFinalizeInvocations.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    sawSuperFinalize = false;
    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    if (!"finalize".equals(getMethodName()) || !"()V".equals(getMethodSig())) {
        return;
    }
    String overridesFinalizeIn = Lookup.findSuperImplementor(getDottedClassName(), "finalize", "()V", bugReporter);
    boolean superHasNoFinalizer = Values.DOTTED_JAVA_LANG_OBJECT.equals(overridesFinalizeIn);
    // System.out.println("superclass: " + superclassName);
    if (obj.getCode().length == 1) {
        if (superHasNoFinalizer) {
            if (!getMethod().isFinal()) {
                bugReporter.reportBug(new BugInstance(this, "FI_EMPTY", NORMAL_PRIORITY).addClassAndMethod(this));
            }
        } else {
            bugReporter.reportBug(new BugInstance(this, "FI_NULLIFY_SUPER", NORMAL_PRIORITY).addClassAndMethod(this)
                    .addClass(overridesFinalizeIn));
        }
    } else if (obj.getCode().length == 5 && sawSuperFinalize) {
        bugReporter.reportBug(new BugInstance(this, "FI_USELESS", NORMAL_PRIORITY).addClassAndMethod(this));
    } else if (!sawSuperFinalize && !superHasNoFinalizer) {
        bugReporter.reportBug(new BugInstance(this, "FI_MISSING_SUPER_CALL", NORMAL_PRIORITY).addClassAndMethod(this)
                .addClass(overridesFinalizeIn));
    }
}
 
Example #28
Source File: PublicSemaphores.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    Method m = getMethod();
    if (m.isStatic() || alreadyReported) {
        return;
    }

    state = SEEN_NOTHING;
    super.visit(obj);
}
 
Example #29
Source File: FindNullDerefsInvolvingNonShortCircuitEvaluation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code code) {
    boolean interesting = true;
    if (interesting) {
        // initialize any variables we want to initialize for the method
        super.visit(code); // make callbacks to sawOpcode for all opcodes
    }
}
 
Example #30
Source File: DoInsideDoPrivileged.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    if (isDoPrivileged && "run".equals(getMethodName())) {
        return;
    }
    if (getMethod().isPrivate()) {
        return;
    }
    if (DumbMethods.isTestMethod(getMethod())) {
        return;
    }
    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
}