Java Code Examples for org.apache.bcel.classfile.Code

The following examples show how to use org.apache.bcel.classfile.Code. These examples are extracted from open source projects. 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
@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 2
Source Project: commons-bcel   Source File: MethodGen.java    License: 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 3
Source Project: spotbugs   Source File: WaitInLoop.java    License: 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 4
Source Project: commons-bcel   Source File: JdkGenericDumpTestCase.java    License: 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 5
@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 6
Source Project: spotbugs   Source File: UnreadFields.java    License: 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 7
@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 8
@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 9
@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 Project: spotbugs   Source File: Naming.java    License: 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 11
@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 12
@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 13
@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 14
Source Project: spotbugs   Source File: ClassContext.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get a BitSet representing the bytecodes that are used in the given
 * method. This is useful for prescreening a method for the existence of
 * particular instructions. Because this step doesn't require building a
 * MethodGen, it is very fast and memory-efficient. It may allow a Detector
 * to avoid some very expensive analysis, which is a Big Win for the user.
 *
 * @param method
 *            the method
 * @return the BitSet containing the opcodes which appear in the method, or
 *         null if the method has no code
 */
@CheckForNull
static public BitSet getBytecodeSet(JavaClass clazz, Method method) {

    XMethod xmethod = XFactory.createXMethod(clazz, method);
    if (cachedBitsets().containsKey(xmethod)) {
        return cachedBitsets().get(xmethod);
    }
    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();
    BitSet result = null;
    if (unpackedCode != null) {
        result = unpackedCode.getBytecodeSet();
    }
    cachedBitsets().put(xmethod, result);
    return result;
}
 
Example 15
Source Project: spotbugs   Source File: PrintClass.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Dump the disassembled code of all methods in the class.
 */
public static void printCode(Method[] methods) {
    for (Method m : methods) {
        System.out.println(m);
        Code code = m.getCode();
        if (code != null) {
            System.out.println(code);
        }

    }
}
 
Example 16
Source Project: spotbugs   Source File: TypeAnalysis.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param method
 *            TODO
 * @param methodGen
 *            the MethodGen whose CFG we'll be analyzing
 * @param cfg
 *            the control flow graph
 * @param dfs
 *            DepthFirstSearch of the method
 * @param typeMerger
 *            object to merge types
 * @param visitor
 *            a TypeFrameModelingVisitor to use to model the effect of
 *            instructions
 * @param lookupFailureCallback
 *            lookup failure callback
 * @param exceptionSetFactory
 *            factory for creating ExceptionSet objects
 */
public TypeAnalysis(Method method, MethodGen methodGen, CFG cfg, DepthFirstSearch dfs, TypeMerger typeMerger,
        TypeFrameModelingVisitor visitor, RepositoryLookupFailureCallback lookupFailureCallback,
        ExceptionSetFactory exceptionSetFactory) {
    super(dfs);
    this.method = method;
    Code code = method.getCode();
    if (code == null) {
        throw new IllegalArgumentException(method.getName() + " has no code");
    }
    for (Attribute a : code.getAttributes()) {
        if (a instanceof LocalVariableTypeTable) {
            visitor.setLocalTypeTable((LocalVariableTypeTable) a);
        }
    }
    this.methodGen = methodGen;
    this.cfg = cfg;
    this.typeMerger = typeMerger;
    this.visitor = visitor;
    this.thrownExceptionSetMap = new HashMap<>();
    this.lookupFailureCallback = lookupFailureCallback;
    this.exceptionSetFactory = exceptionSetFactory;
    this.instanceOfCheckMap = new HashMap<>();
    if (DEBUG) {
        System.out.println("\n\nAnalyzing " + methodGen);
    }
}
 
Example 17
static @CheckForNull StackMap getStackMapTable(Code code) {
    for (Attribute a : code.getAttributes()) {
        if (a instanceof StackMap) {
            return (StackMap) a;
        }
    }
    return null;
}
 
Example 18
static SourceLineAnnotation getSourceAnnotationForClass(String className, String sourceFileName) {

        int lastLine = -1;
        int firstLine = Integer.MAX_VALUE;

        try {
            JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(className);
            for (Method m : targetClass.getMethods()) {
                Code c = m.getCode();
                if (c != null) {
                    LineNumberTable table = c.getLineNumberTable();
                    if (table != null) {
                        for (LineNumber line : table.getLineNumberTable()) {
                            lastLine = Math.max(lastLine, line.getLineNumber());
                            firstLine = Math.min(firstLine, line.getLineNumber());
                        }
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            AnalysisContext.reportMissingClass(e);
        }
        if (firstLine < Integer.MAX_VALUE) {
            return new SourceLineAnnotation(className, sourceFileName, firstLine, lastLine, -1, -1);
        }
        return SourceLineAnnotation.createUnknown(className, sourceFileName);
    }
 
Example 19
@Override
public void visit(Code obj) {
    if (sawDateClass) {
        super.visit(obj);
        bugAccumulator.reportAccumulatedBugs();
    }
}
 
Example 20
Source Project: spotbugs   Source File: LazyInit.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean prescreen(Method method, ClassContext classContext) {
    if (Const.STATIC_INITIALIZER_NAME.equals(method.getName())) {
        return false;
    }

    Code code = method.getCode();
    if (code.getCode().length > 5000) {
        return false;
    }

    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return false;
    }

    // The pattern requires a get/put pair accessing the same field.
    boolean hasGetStatic = bytecodeSet.get(Const.GETSTATIC);
    boolean hasPutStatic = bytecodeSet.get(Const.PUTSTATIC);
    if (!hasGetStatic || !hasPutStatic) {
        return false;
    }

    // If the method is synchronized, then we'll assume that
    // things are properly synchronized
    if (method.isSynchronized()) {
        return false;
    }

    reported.clear();
    return true;
}
 
Example 21
@Override
public void visit(Code obj) {
    if (!inConstructor) {
        return;
    }
    uninitializedFieldReadAndCheckedForNonnull = null;
    super.visit(obj);
    for (BugInstance bug : pendingBugs) {
        bugReporter.reportBug(bug);
    }
    pendingBugs.clear();
}
 
Example 22
@Override
public void visit(Code obj) {

    if (!getMethod().isPublic() && !getMethod().isProtected()) {
        return;
    }
    SignatureParser p = new SignatureParser(getMethodSig());
    LocalVariableTable t = obj.getLocalVariableTable();

    if (t == null) {
        return;
    }
    ParameterProperty property = new ParameterProperty();

    int index = getMethod().isStatic() ? 0 : 1;
    int parameterNumber = 0;
    for (Iterator<String> i = p.parameterSignatureIterator(); i.hasNext();) {
        String s = i.next();
        LocalVariable localVariable = t.getLocalVariable(index, 0);
        if (localVariable != null) {
            String name = localVariable.getName();
            if ("J".equals(s) && (name.toLowerCase().indexOf("instant") >= 0 || name.startsWith("date"))) {

                // System.out.println(getFullyQualifiedMethodName() + " " + s + " " + index + " " + name);
                property.setParamWithProperty(parameterNumber, true);
            }
        }
        if ("J".equals(s) || "D".equals(s)) {
            index += 2;
        } else {
            index += 1;
        }
        parameterNumber++;
    }
    if (!property.isEmpty()) {
        // System.out.println(getFullyQualifiedMethodName() + " " + property);
        database.setProperty(getMethodDescriptor(), property);
    }
}
 
Example 23
@Override
public void visit(Code obj) {
    if (isInnerClass && !BCELUtil.isSynthetic(getMethod())) {
        super.visit(obj);
        iteratorBug = null;
    }
}
 
Example 24
Source Project: spotbugs   Source File: DumbMethods.java    License: 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 25
@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();
}
 
Example 26
@Override
public void visit(Code obj) {
    if (!shouldVisitCode) {
        return;
    }
    sawNoSuchElement = false;
    sawCall = false;
    super.visit(obj);
    if (!sawNoSuchElement) {
        BugInstance bug = new BugInstance(this, "IT_NO_SUCH_ELEMENT", sawCall ? LOW_PRIORITY : NORMAL_PRIORITY);
        bug.addClassAndMethod(this);
        bugReporter.reportBug(bug);
    }
}
 
Example 27
@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 28
@Override
public void visit(Code obj) {
    Method m = getMethod();
    if (m.isStatic() || alreadyReported) {
        return;
    }

    state = SEEN_NOTHING;
    super.visit(obj);
}
 
Example 29
@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 30
@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);
        }
    }
}