org.apache.bcel.generic.MethodGen Java Examples

The following examples show how to use org.apache.bcel.generic.MethodGen. 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: PLSETestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-295:
 */
public void testB295() throws Exception
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass2");
    final ClassGen cg = new ClassGen(clazz);
    final ConstantPoolGen pool = cg.getConstantPool();
    final Method m = cg.getMethodAt(1);  // 'main'
    final LocalVariableTable lvt = m.getLocalVariableTable();
    final LocalVariable lv = lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(lv);
    final MethodGen mg = new MethodGen(m, cg.getClassName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    final LocalVariable new_lv = new_lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(new_lv);
    assertEquals("live range length", lv.getLength(), new_lv.getLength());
}
 
Example #2
Source File: ASTIfExpr.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Fifth pass, produce Java byte code.
 */
@Override
public void byte_code(final InstructionList il, final MethodGen method, final ConstantPoolGen cp) {
  if_expr.byte_code(il, method, cp);

  final InstructionList then_code = new InstructionList();
  final InstructionList else_code = new InstructionList();

  then_expr.byte_code(then_code, method, cp);
  else_expr.byte_code(else_code, method, cp);

  BranchHandle i, g;

  i = il.append(new IFEQ(null)); // If POP() == FALSE(i.e. 0) then branch to ELSE
  ASTFunDecl.pop();
  il.append(then_code);
  g = il.append(new GOTO(null));
  i.setTarget(il.append(else_code));
  g.setTarget(il.append(InstructionConstants.NOP)); // May be optimized away later
}
 
Example #3
Source File: IsNullValueAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public IsNullValueAnalysis(MethodDescriptor descriptor, MethodGen methodGen, CFG cfg, ValueNumberDataflow vnaDataflow,
        TypeDataflow typeDataflow, DepthFirstSearch dfs, AssertionMethods assertionMethods) {
    super(dfs);

    this.trackValueNumbers = AnalysisContext.currentAnalysisContext().getBoolProperty(
            AnalysisFeatures.TRACK_VALUE_NUMBERS_IN_NULL_POINTER_ANALYSIS);

    this.methodGen = methodGen;
    this.visitor = new IsNullValueFrameModelingVisitor(methodGen.getConstantPool(), assertionMethods, vnaDataflow,
            typeDataflow, trackValueNumbers);
    this.vnaDataflow = vnaDataflow;
    this.cfg = cfg;
    this.locationWhereValueBecomesNullSet = new HashSet<>();
    this.pointerEqualityCheck = getForPointerEqualityCheck(cfg, vnaDataflow);

    if (DEBUG) {
        System.out.println("IsNullValueAnalysis for " + methodGen.getClassName() + "." + methodGen.getName() + " : "
                + methodGen.getSignature());
    }
}
 
Example #4
Source File: PLSETestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-262:
 */
public void testB262() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    // get the values() method
    final Method m = gen.getMethodAt(0);
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final InstructionList il = mg.getInstructionList();
    // get the invokevirtual instruction
    final InstructionHandle ih = il.findHandle(3);
    final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());
    // without fix, the getClassName() will throw:
    //   java.lang.IllegalArgumentException: Cannot be used on an array type
    final String cn = ii.getClassName(pool);
    assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}
 
Example #5
Source File: id.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example #6
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Add a source line annotation describing a range of instructions.
 *
 * @param classContext
 *            the ClassContext
 * @param methodGen
 *            the method
 * @param sourceFile
 *            source file the method is defined in
 * @param start
 *            the start instruction in the range
 * @param end
 *            the end instruction in the range (inclusive)
 * @return this object
 */
@Nonnull
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start,
        InstructionHandle end) {
    // Make sure start and end are really in the right order.
    if (start.getPosition() > end.getPosition()) {
        InstructionHandle tmp = start;
        start = end;
        end = tmp;
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen,
            sourceFile, start, end);
    if (sourceLineAnnotation != null) {
        add(sourceLineAnnotation);
    }
    return this;
}
 
Example #7
Source File: LiveLocalStoreDataflowFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public LiveLocalStoreDataflow analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
        throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) {
        return null;
    }
    CFG cfg = getCFG(analysisCache, descriptor);

    ReverseDepthFirstSearch rdfs = getReverseDepthFirstSearch(analysisCache, descriptor);

    LiveLocalStoreAnalysis analysis = new LiveLocalStoreAnalysis(methodGen, rdfs, getDepthFirstSearch(analysisCache,
            descriptor));
    LiveLocalStoreDataflow dataflow = new LiveLocalStoreDataflow(cfg, analysis);

    dataflow.execute();
    if (ClassContext.DUMP_DATAFLOW_ANALYSIS) {
        ClassContext.dumpLiveLocalStoreDataflow(descriptor, cfg, dataflow);

    }
    return dataflow;
}
 
Example #8
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param methodGen method
 * @param start instruction to scan
 * @return instruction which consumes value which was on top of stack before start instruction
 * or null if cannot be determined
 */
private InstructionHandle getConsumer(MethodGen methodGen, InstructionHandle start) {
    int depth = 1;
    InstructionHandle cur = start;
    while (cur != null) {
        Instruction inst = cur.getInstruction();
        depth -= inst.consumeStack(methodGen.getConstantPool());
        if (depth <= 0) {
            return cur;
        }
        depth += inst.produceStack(methodGen.getConstantPool());
        if (inst instanceof BranchInstruction) {
            if (inst instanceof GotoInstruction) {
                cur = ((GotoInstruction) inst).getTarget();
                continue;
            }
            if (!(inst instanceof IfInstruction)) {
                return null;
            }
        }
        cur = cur.getNext();
    }
    return null;
}
 
Example #9
Source File: TestReturn01Creator.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void createMethod_1() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS,
          new String[] {  }, "foo", TEST_PACKAGE+".TestReturn01", il, _cp);

  final InstructionHandle ih_0 = il.append(_factory.createNew("java.lang.Object"));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(InstructionConst.DUP);
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  il.append(InstructionConst.NOP);
  final InstructionHandle ih_8 = il.append(InstructionFactory.createReturn(Type.OBJECT));
  Assert.assertNotNull(ih_8); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #10
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 #11
Source File: LockDataflowFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public LockDataflow analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) {
        throw new MethodUnprofitableException(descriptor);
    }
    ValueNumberDataflow vnaDataflow = getValueNumberDataflow(analysisCache, descriptor);
    DepthFirstSearch dfs = getDepthFirstSearch(analysisCache, descriptor);
    CFG cfg = getCFG(analysisCache, descriptor);

    LockAnalysis analysis = new LockAnalysis(methodGen, vnaDataflow, dfs);
    LockDataflow dataflow = new LockDataflow(cfg, analysis);
    dataflow.execute();
    return dataflow;

}
 
Example #12
Source File: ExceptionHandlerMap.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param methodGen
 *            the method to build the map for
 */
public ExceptionHandlerMap(MethodGen methodGen, TypeMerger merger) {
    codeToHandlerMap = new IdentityHashMap<>();
    startInstructionToHandlerMap = new IdentityHashMap<>();
    this.merger = merger;
    build(methodGen);
}
 
Example #13
Source File: StoreDataflowFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public StoreDataflow analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) {
        return null;
    }
    StoreAnalysis analysis = new StoreAnalysis(getDepthFirstSearch(analysisCache, descriptor), getConstantPoolGen(
            analysisCache, descriptor.getClassDescriptor()));
    StoreDataflow dataflow = new StoreDataflow(getCFG(analysisCache, descriptor), analysis);
    dataflow.execute();
    return dataflow;
}
 
Example #14
Source File: BCELBenchmark.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();

        ClassGen cg = new ClassGen(clazz);

        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();

            if (il != null) {
                mg.getInstructionList().setPositions();
                mg.setMaxLocals();
                mg.setMaxStack();
            }
            cg.replaceMethod(m, mg.getMethod());
        }

        bh.consume(cg.getJavaClass().getBytes());
    }

    jar.close();
}
 
Example #15
Source File: TestReturn03Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void createMethod_0() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  },
          "<init>", TEST_PACKAGE+".TestReturn03", il, _cp);

  final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
  Assert.assertNotNull(ih_4); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #16
Source File: ClassContext.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Look up the Method represented by given MethodGen.
 *
 * @param methodGen
 *            a MethodGen
 * @return the Method represented by the MethodGen
 */
public Method getMethod(MethodGen methodGen) {
    Method[] methodList = jclass.getMethods();
    for (Method method : methodList) {
        if (method.getName().equals(methodGen.getName()) && method.getSignature().equals(methodGen.getSignature())
                && method.getAccessFlags() == methodGen.getAccessFlags()) {
            return method;
        }
    }
    return null;
}
 
Example #17
Source File: ResourceValueAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ResourceValueAnalysis(MethodGen methodGen, CFG cfg, DepthFirstSearch dfs, ResourceTracker<Resource> resourceTracker,
        Resource resource) {

    super(dfs);
    this.methodGen = methodGen;
    this.cfg = cfg;
    this.resourceTracker = resourceTracker;
    this.resource = resource;
    this.visitor = resourceTracker.createVisitor(resource, methodGen.getConstantPool());

    this.ignoreImplicitExceptions = resourceTracker.ignoreImplicitExceptions(resource);
}
 
Example #18
Source File: XFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static XMethod createXMethod(MethodGen methodGen) {
    String className = methodGen.getClassName();
    String methodName = methodGen.getName();
    String methodSig = methodGen.getSignature();
    int accessFlags = methodGen.getAccessFlags();
    return createXMethod(className, methodName, methodSig, accessFlags);
}
 
Example #19
Source File: maxstack.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    for (final String class_name : argv) {
        JavaClass java_class = Repository.lookupClass(class_name);

        if (java_class == null) {
            java_class = new ClassParser(class_name).parse();
        }

        final ConstantPoolGen cp = new ConstantPoolGen(java_class.getConstantPool());

        for (final Method m : java_class.getMethods()) {
            if (!(m.isAbstract() || m.isNative())) {
                final MethodGen mg = new MethodGen(m, class_name, cp);

                final int compiled_stack = mg.getMaxStack();
                final int compiled_locals = mg.getMaxLocals();
                mg.setMaxStack(); // Recompute value
                mg.setMaxLocals();
                final int computed_stack = mg.getMaxStack();
                final int computed_locals = mg.getMaxLocals();

                mg.getInstructionList().dispose(); // Reuse instruction handles

                System.out.println(m);

                if (computed_stack == compiled_stack) {
                    System.out.println("Stack ok(" + computed_stack + ")");
                } else {
                    System.out.println("\nCompiled stack size " + compiled_stack + " computed size " + computed_stack);
                }

                if (computed_locals == compiled_locals) {
                    System.out.println("Locals ok(" + computed_locals + ")");
                } else {
                    System.out.println("\nCompiled locals " + compiled_locals + " computed size " + computed_locals);
                }
            }
        }
    }
}
 
Example #20
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example #21
Source File: ConstantDataflowFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ConstantDataflow analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) {
        return null;
    }
    ConstantAnalysis analysis = new ConstantAnalysis(methodGen, getDepthFirstSearch(analysisCache, descriptor));
    ConstantDataflow dataflow = new ConstantDataflow(getCFG(analysisCache, descriptor), analysis);
    dataflow.execute();

    return dataflow;
}
 
Example #22
Source File: LoadedFieldSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor. Constructs an empty object.
 *
 * @param methodGen
 *            the method being analyzed for loads/stores
 */
public LoadedFieldSet(MethodGen methodGen) {
    // this.methodGen = methodGen;
    this.loadStoreCountMap = new HashMap<>();
    this.handleToFieldMap = new HashMap<>();
    this.loadHandleSet = new BitSet();
}
 
Example #23
Source File: UnconditionalValueDerefDataflowFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public UnconditionalValueDerefDataflow analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor)
        throws CheckedAnalysisException {
    MethodGen methodGen = getMethodGen(analysisCache, descriptor);
    if (methodGen == null) {
        throw new MethodUnprofitableException(descriptor);
    }

    CFG cfg = getCFG(analysisCache, descriptor);

    ValueNumberDataflow vnd = getValueNumberDataflow(analysisCache, descriptor);

    UnconditionalValueDerefAnalysis analysis = new UnconditionalValueDerefAnalysis(getReverseDepthFirstSearch(analysisCache,
            descriptor), getDepthFirstSearch(analysisCache, descriptor), cfg, getMethod(analysisCache, descriptor),
            methodGen, vnd, getAssertionMethods(analysisCache, descriptor.getClassDescriptor()));

    IsNullValueDataflow inv = getIsNullValueDataflow(analysisCache, descriptor);
    // XXX: hack to clear derefs on not-null branches
    analysis.clearDerefsOnNonNullBranches(inv);

    TypeDataflow typeDataflow = getTypeDataflow(analysisCache, descriptor);
    // XXX: type analysis is needed to resolve method calls for
    // checking whether call targets unconditionally dereference parameters
    analysis.setTypeDataflow(typeDataflow);

    UnconditionalValueDerefDataflow dataflow = new UnconditionalValueDerefDataflow(cfg, analysis);
    dataflow.execute();
    if (ClassContext.DUMP_DATAFLOW_ANALYSIS) {
        dataflow.dumpDataflow(analysis);
    }
    if (UnconditionalValueDerefAnalysis.DEBUG) {
        ClassContext.dumpDataflowInformation(getMethod(analysisCache, descriptor), cfg, vnd, inv, dataflow, typeDataflow);
    }

    return dataflow;
}
 
Example #24
Source File: ComplexObjectCreator.java    From cougar with Apache License 2.0 5 votes vote down vote up
private void createMethod_0() {
  InstructionList il = new InstructionList();
  MethodGen method = new MethodGen(ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  }, "<init>", objectType, il, _cp);

  InstructionHandle ih_0 = il.append(_factory.createLoad(Type.OBJECT, 0));
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
  InstructionHandle ih_4 = il.append(_factory.createReturn(Type.VOID));
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #25
Source File: TestArrayAccess02Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void createMethod_0() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  }, "<init>",
          TEST_PACKAGE+".TestArrayAccess02", il, _cp);

  final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID));
  Assert.assertNotNull(ih_4); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #26
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test driver.
 */
public static void main(String[] argv) throws Exception {
    if (argv.length != 1) {
        System.err.println("Usage: " + BetterCFGBuilder2.class.getName() + " <class file>");
        System.exit(1);
    }

    String methodName = SystemProperties.getProperty("cfgbuilder.method");

    JavaClass jclass = new ClassParser(argv[0]).parse();
    ClassGen classGen = new ClassGen(jclass);

    Method[] methodList = jclass.getMethods();
    for (Method method : methodList) {
        if (method.isAbstract() || method.isNative()) {
            continue;
        }

        if (methodName != null && !method.getName().equals(methodName)) {
            continue;
        }

        MethodDescriptor descriptor = DescriptorFactory.instance().getMethodDescriptor(jclass, method);
        MethodGen methodGen = new MethodGen(method, jclass.getClassName(), classGen.getConstantPool());

        CFGBuilder cfgBuilder = new BetterCFGBuilder2(descriptor, methodGen);
        cfgBuilder.build();

        CFG cfg = cfgBuilder.getCFG();

        CFGPrinter cfgPrinter = new CFGPrinter(cfg);
        System.out.println("---------------------------------------------------------------------");
        System.out.println("Method: " + SignatureConverter.convertMethodSignature(methodGen));
        System.out.println("---------------------------------------------------------------------");
        cfgPrinter.print(System.out);
    }
}
 
Example #27
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add class and method annotations for given method.
 *
 * @param methodGen
 *            the method
 * @param sourceFile
 *            source file the method is defined in
 * @return this object
 */
@Nonnull
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
    addClass(methodGen.getClassName());
    addMethod(methodGen, sourceFile);
    if (!MemberUtils.isUserGenerated(methodGen)) {
        foundInAutogeneratedMethod();
    }
    return this;
}
 
Example #28
Source File: ResourceTrackingDetector.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void analyzeMethod(ClassContext classContext, Method method, ResourceTrackerType resourceTracker,
        ResourceCollection<Resource> resourceCollection) throws CFGBuilderException, DataflowAnalysisException {

    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    try {
        CFG cfg = classContext.getCFG(method);
        DepthFirstSearch dfs = classContext.getDepthFirstSearch(method);

        if (DEBUG) {
            System.out.println(SignatureConverter.convertMethodSignature(methodGen));
        }

        for (Iterator<Resource> i = resourceCollection.resourceIterator(); i.hasNext();) {
            Resource resource = i.next();

            ResourceValueAnalysis<Resource> analysis = new ResourceValueAnalysis<>(methodGen, cfg, dfs,
                    resourceTracker, resource);
            Dataflow<ResourceValueFrame, ResourceValueAnalysis<Resource>> dataflow = new Dataflow<>(
                    cfg, analysis);

            Profiler profiler = Global.getAnalysisCache().getProfiler();
            profiler.start(resourceTracker.getClass());
            try {
                dataflow.execute();
            } finally {
                profiler.end(resourceTracker.getClass());
            }
            inspectResult(classContext, methodGen, cfg, dataflow, resource);
        }
    } catch (RuntimeException e) {
        AnalysisContext.logError("Exception while analyzing " + methodGen.getClassName() + "." + methodGen.getName() + ":"
                + methodGen.getSignature(), e);
    }
}
 
Example #29
Source File: FindOpenStream.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg,
        Dataflow<ResourceValueFrame, ResourceValueAnalysis<Stream>> dataflow, Stream stream) {

    if (DEBUG) {
        System.out.printf("Result for %s in %s%n", stream, methodGen);
        dataflow.dumpDataflow(dataflow.getAnalysis());

    }
    ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit());

    int exitStatus = exitFrame.getStatus();
    if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {

        // FIXME: Stream object should be queried for the
        // priority.

        String bugType = stream.getBugType();
        int priority = NORMAL_PRIORITY;
        if (exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {
            bugType += "_EXCEPTION_PATH";
            priority = LOW_PRIORITY;
        }

        potentialOpenStreamList.add(new PotentialOpenStream(bugType, priority, stream));
    } else if (exitStatus == ResourceValueFrame.CLOSED) {
        // Remember that this stream was closed on all paths.
        // Later, we will mark all of the streams in its equivalence class
        // as having been closed.
        stream.setClosed();
    }
}
 
Example #30
Source File: LockAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public LockAnalysis(MethodGen methodGen, ValueNumberDataflow vnaDataflow, DepthFirstSearch dfs) {
    super(dfs);
    this.methodGen = methodGen;
    this.vnaDataflow = vnaDataflow;
    this.vna = vnaDataflow.getAnalysis();
    this.isSynchronized = methodGen.isSynchronized();
    this.isStatic = methodGen.isStatic();
    if (DEBUG) {
        System.out.println("Analyzing Locks in " + methodGen.getClassName() + "." + methodGen.getName());
    }
}