Java Code Examples for org.apache.bcel.classfile.Method#getCode()

The following examples show how to use org.apache.bcel.classfile.Method#getCode() . 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: CFGDetector.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visitClass(ClassDescriptor classDescriptor) throws CheckedAnalysisException {
    IAnalysisCache analysisCache = Global.getAnalysisCache();

    JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, classDescriptor);
    classContext = analysisCache.getClassAnalysis(ClassContext.class, classDescriptor);

    for (Method m : classContext.getMethodsInCallOrder()) {
        if (m.getCode() == null) {
            continue;
        }
        method = m;

        MethodDescriptor methodDescriptor = BCELUtil.getMethodDescriptor(jclass, method);

        // Try to get MethodGen. If we can't get one,
        // then this method should be skipped.
        MethodGen methodGen = analysisCache.getMethodAnalysis(MethodGen.class, methodDescriptor);
        if (methodGen == null) {
            continue;
        }

        CFG cfg = analysisCache.getMethodAnalysis(CFG.class, methodDescriptor);
        visitMethodCFG(methodDescriptor, cfg);
    }
}
 
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: FindJSR166LockMonitorenter.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass jclass = classContext.getJavaClass();
    if (jclass.getClassName().startsWith("java.util.concurrent.")) {
        return;
    }
    Method[] methodList = jclass.getMethods();

    for (Method method : methodList) {
        if (method.getCode() == null) {
            continue;
        }

        // We can ignore methods that don't contain a monitorenter
        BitSet bytecodeSet = classContext.getBytecodeSet(method);
        if (bytecodeSet == null) {
            continue;
        }
        if (false && !bytecodeSet.get(Const.MONITORENTER)) {
            continue;
        }

        analyzeMethod(classContext, method);

    }
}
 
Example 4
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 5
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 6
Source File: listclass.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Dump the disassembled code of all methods in the class.
 */
public static void printCode(final Method[] methods, final boolean verbose) {
    for (final Method method : methods) {
        System.out.println(method);

        final Code code = method.getCode();
        if (code != null) {
            System.out.println(code.toString(verbose));
        }
    }
}
 
Example 7
Source File: ClassContext.java    From spotbugs with 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 8
Source File: OpcodeStack.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public @CheckForNull JumpInfo analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);
    JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
    Code code = method.getCode();
    if (code == null) {
        return null;
    }

    JumpStackComputation branchAnalysis = new JumpStackComputation(descriptor);

    return computeJumpInfo(jclass, method, branchAnalysis);
}
 
Example 9
Source File: TypeAnalysis.java    From spotbugs with 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 10
Source File: MethodGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private static byte[] getByteCodes(final Method method) {
    final Code code = method.getCode();
    if (code == null) {
        throw new IllegalStateException(String.format("The method '%s' has no code.", method));
    }
    return code.getCode();
}
 
Example 11
Source File: CompactLocationNumberingFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public CompactLocationNumbering analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
        throws CheckedAnalysisException {
    Method method = analysisCache.getMethodAnalysis(Method.class, descriptor);

    if (method.getCode() == null) {
        return null;
    }

    CFG cfg = getCFG(analysisCache, descriptor);
    return new CompactLocationNumbering(cfg);
}
 
Example 12
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 13
Source File: DuplicateBranches.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitMethod(Method method) {
    try {
        if (method.getCode() == null) {
            return;
        }

        CFG cfg = classContext.getCFG(method);

        Iterator<BasicBlock> bbi = cfg.blockIterator();
        while (bbi.hasNext()) {
            BasicBlock bb = bbi.next();

            int numOutgoing = cfg.getNumOutgoingEdges(bb);
            if (numOutgoing == 2) {
                findIfElseDuplicates(cfg, method, bb);
            } else if (numOutgoing > 2) {
                findSwitchDuplicates(cfg, method, bb);
            }
        }
    } catch (MethodUnprofitableException mue) {
        if (SystemProperties.getBoolean("unprofitable.debug")) {
            // don't
            // report
            bugReporter.logError("skipping unprofitable method in " + getClass().getName());
        }
    } catch (Exception e) {
        bugReporter.logError("Failure examining basic blocks in Duplicate Branches detector", e);
    }
    if (pendingBugs.size() <= 2) {
        for (BugInstance b : pendingBugs) {
            bugReporter.reportBug(b);
        }
    }
    pendingBugs.clear();

}
 
Example 14
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 15
Source File: SourceLineAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 16
Source File: SourceLineAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
static SourceLineAnnotation getSourceAnnotationForMethod(String className, String methodName, String methodSig) {
    JavaClassAndMethod targetMethod = null;
    Code code = null;

    try {
        JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(className);
        targetMethod = Hierarchy.findMethod(targetClass, methodName, methodSig);
        if (targetMethod != null) {
            Method method = targetMethod.getMethod();
            if (method != null) {
                code = method.getCode();
            }
        }

    } catch (ClassNotFoundException e) {
        AnalysisContext.reportMissingClass(e);
    }
    SourceInfoMap sourceInfoMap = AnalysisContext.currentAnalysisContext().getSourceInfoMap();
    SourceInfoMap.SourceLineRange range = sourceInfoMap.getMethodLine(className, methodName, methodSig);

    if (range != null) {
        return new SourceLineAnnotation(className, AnalysisContext.currentAnalysisContext().lookupSourceFile(className),
                range.getStart(), range.getEnd(), 0, code == null ? -1 : code.getLength());
    }

    if (sourceInfoMap.fallBackToClassfile() && targetMethod != null) {
        return forEntireMethod(targetMethod.getJavaClass(), targetMethod.getMethod());
    }

    // If we couldn't find the source lines,
    // create an unknown source line annotation referencing
    // the class and source file.

    return createUnknown(className);
}
 
Example 17
Source File: SourceLineAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create a SourceLineAnnotation covering an entire method.
 *
 * @param javaClass
 *            JavaClass containing the method
 * @param method
 *            the method
 * @return a SourceLineAnnotation for the entire method
 */
public static SourceLineAnnotation forEntireMethod(JavaClass javaClass, @CheckForNull Method method) {
    String sourceFile = javaClass.getSourceFileName();
    if (method == null) {
        return createUnknown(javaClass.getClassName(), sourceFile);
    }
    Code code = method.getCode();
    LineNumberTable lineNumberTable = method.getLineNumberTable();
    if (code == null || lineNumberTable == null) {
        return createUnknown(javaClass.getClassName(), sourceFile);
    }

    return forEntireMethod(javaClass.getClassName(), sourceFile, lineNumberTable, code.getLength());
}
 
Example 18
Source File: PrintClass.java    From spotbugs with 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 19
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the linkage errors for unimplemented methods in {@code classFile}. Such unimplemented
 * methods manifest as {@link AbstractMethodError} in runtime.
 */
private ImmutableList<SymbolProblem> findInterfaceProblems(
    ClassFile classFile, InterfaceSymbol interfaceSymbol) {
  String interfaceName = interfaceSymbol.getClassBinaryName();
  if (classDumper.isSystemClass(interfaceName)) {
    return ImmutableList.of();
  }

  ImmutableList.Builder<SymbolProblem> builder = ImmutableList.builder();
  try {
    JavaClass implementingClass = classDumper.loadJavaClass(classFile.getBinaryName());
    if (implementingClass.isAbstract()) {
      // Abstract class does not need to implement methods in an interface.
      return ImmutableList.of();
    }
    JavaClass interfaceDefinition = classDumper.loadJavaClass(interfaceName);
    for (Method interfaceMethod : interfaceDefinition.getMethods()) {
      if (interfaceMethod.getCode() != null) {
        // This interface method has default implementation. Subclass does not have to implement
        // it.
        continue;
      }
      String interfaceMethodName = interfaceMethod.getName();
      String interfaceMethodDescriptor = interfaceMethod.getSignature();
      boolean methodFound = false;

      Iterable<JavaClass> typesToCheck = Iterables.concat(getClassHierarchy(implementingClass));
      for (JavaClass javaClass : typesToCheck) {
        for (Method method : javaClass.getMethods()) {
          if (method.getName().equals(interfaceMethodName)
              && method.getSignature().equals(interfaceMethodDescriptor)) {
            methodFound = true;
            break;
          }
        }
      }
      if (!methodFound) {
        MethodSymbol missingMethodOnClass =
            new MethodSymbol(
                classFile.getBinaryName(), interfaceMethodName, interfaceMethodDescriptor, false);
        builder.add(
            new SymbolProblem(missingMethodOnClass, ErrorType.ABSTRACT_METHOD, classFile));
      }
    }
  } catch (ClassNotFoundException ex) {
    // Missing classes are reported by findSymbolProblem method.
  }
  return builder.build();
}
 
Example 20
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {
    String mName = getMethodName();
    if (mName.length() == 1) {
        return;
    }
    if ("isRequestedSessionIdFromURL".equals(mName) || "isRequestedSessionIdFromUrl".equals(mName)) {
        return;
    }
    String sig = getMethodSig();
    if (mName.equals(baseClassName) && "()V".equals(sig)) {
        Code code = obj.getCode();
        Method realVoidConstructor = findVoidConstructor(getThisClass());
        if (code != null && !markedAsNotUsable(obj)) {
            int priority = NORMAL_PRIORITY;
            if (codeDoesSomething(code)) {
                priority--;
            } else if (!obj.isPublic() && getThisClass().isPublic()) {
                priority--;
            }
            boolean instanceMembers = false;
            for (Method m : this.getThisClass().getMethods()) {
                if (!m.isStatic() && m != obj && !isVoidConstructor(getThisClass(), m)) {
                    instanceMembers = true;
                }
            }
            for (Field f : this.getThisClass().getFields()) {
                if (!f.isStatic()) {
                    instanceMembers = true;
                }
            }
            if (!codeDoesSomething(code) && !instanceMembers && "java/lang/Object".equals(getSuperclassName())) {
                priority += 2;
            }
            if (hasBadMethodNames) {
                priority++;
            }
            if (!getXClass().getAnnotations().isEmpty()) {
                priority++;
            }
            if (realVoidConstructor != null) {
                priority = LOW_PRIORITY;
            }

            bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this)
                    .lowerPriorityIfDeprecated());
            return;
        }
    } else if (badMethodName(mName)) {
        bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadMethodNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClassAndMethod(this));
    }

    if (obj.isAbstract()) {
        return;
    }
    if (obj.isPrivate()) {
        return;
    }

    if ("equal".equals(mName) && "(Ljava/lang/Object;)Z".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("hashcode".equals(mName) && "()I".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("tostring".equals(mName) && "()Ljava/lang/String;".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }

    if (obj.isPrivate() || obj.isStatic() || Const.CONSTRUCTOR_NAME.equals(mName)) {
        return;
    }

    String sig2 = removePackageNamesFromSignature(sig);
    String allSmall = mName.toLowerCase() + sig2;

    XMethod xm = getXMethod();
    {
        TreeSet<XMethod> s = canonicalToXMethod.computeIfAbsent(allSmall, k -> new TreeSet<>());
        s.add(xm);
    }

}