Java Code Examples for org.apache.bcel.generic.MethodGen

The following examples show how to use org.apache.bcel.generic.MethodGen. 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
Source Project: commons-bcel   Source File: PLSETestCase.java    License: 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 Project: commons-bcel   Source File: TestReturn01Creator.java    License: 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 3
/**
 * @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 4
Source Project: commons-bcel   Source File: id.java    License: 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 5
Source Project: spotbugs   Source File: BugInstance.java    License: 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 6
@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 7
Source Project: commons-bcel   Source File: PLSETestCase.java    License: 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 8
@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 9
Source Project: spotbugs   Source File: CFGDetector.java    License: 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 10
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 11
Source Project: commons-bcel   Source File: ASTIfExpr.java    License: 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 12
Source Project: commons-bcel   Source File: maxstack.java    License: 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 13
private void analyzeMethod(Method m, ClassContext classContext) throws CFGBuilderException, DataflowAnalysisException
    {

        MethodGen methodGen = classContext.getMethodGen(m);
        ConstantPoolGen cpg = classContext.getConstantPoolGen();
        CFG cfg = classContext.getCFG(m);

        if (methodGen == null || methodGen.getInstructionList() == null) {
            return; //No instruction .. nothing to do
        }

        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext(); ) {
            Location location = i.next();
            Instruction inst = location.getHandle().getInstruction();

            //
            if (inst instanceof InvokeInstruction) {
//                System.out.println(inst.getName());
                InvokeInstruction invoke = (InvokeInstruction) inst;

                String className = invoke.getClassName(cpg);
                if ("java.io.ObjectInputStream".equals(className) || className.contains("InputStream") || InterfaceUtils.isSubtype(className, "java.io.ObjectInputStream")) {

                    String methodName = invoke.getMethodName(cpg);
                    if (OBJECT_INPUTSTREAM_READ_METHODS.contains(methodName)) {

                        JavaClass clz = classContext.getJavaClass();
                        bugReporter.reportBug(new BugInstance(this, OBJECT_DESERIALIZATION_TYPE, HIGH_PRIORITY) //
                                .addClass(clz).addMethod(clz, m).addSourceLine(classContext,m,location));
                    }
                }

            }
        }
    }
 
Example 14
Source Project: commons-bcel   Source File: TestReturn01Creator.java    License: 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+".TestReturn01", 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 15
Source Project: commons-bcel   Source File: TestReturn03Creator.java    License: Apache License 2.0 5 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.INT, Type.NO_ARGS,
          new String[] {  }, "test3", TEST_PACKAGE+".TestReturn03", il, _cp);

  final InstructionHandle ih_0 = il.append(InstructionConst.ACONST_NULL);
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(InstructionFactory.createReturn(Type.OBJECT));
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example 16
Source Project: commons-bcel   Source File: TestArrayAccess04Creator.java    License: 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+".TestArrayAccess04", 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 17
Source Project: commons-bcel   Source File: ASTIdent.java    License: Apache License 2.0 5 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(name.equals("TRUE")) {
      il.append(new PUSH(cp, 1));
  } else if(name.equals("FALSE")) {
      il.append(new PUSH(cp, 0));
  } else {
    final LocalVariableGen local_var = reference.getLocalVariable();
    il.append(new ILOAD(local_var.getIndex()));
  }
  ASTFunDecl.push();
}
 
Example 18
private void analyzeMethod(ClassContext classContext, Method method) throws DataflowAnalysisException, CFGBuilderException {
    if (DEBUG || DEBUG_NULLARG) {
        System.out.println("Pre FND ");
    }

    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }

    // UsagesRequiringNonNullValues uses =
    // classContext.getUsagesRequiringNonNullValues(method);
    this.method = method;

    if (DEBUG || DEBUG_NULLARG) {
        System.out.println("FND: " + SignatureConverter.convertMethodSignature(methodGen));
    }

    findPreviouslyDeadBlocks();

    vnaDataflow = classContext.getValueNumberDataflow(method);

    // Create a NullDerefAndRedundantComparisonFinder object to do the
    // actual
    // work. It will call back to report null derefs and redundant null
    // comparisons
    // through the NullDerefAndRedundantComparisonCollector interface we
    // implement.
    NullDerefAndRedundantComparisonFinder worker = new NullDerefAndRedundantComparisonFinder(classContext, method, this);
    worker.execute();

}
 
Example 19
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {

        MethodGen methodGen = classContext.getMethodGen(method);
        CFG cfg = classContext.getCFG(method);
        LockDataflow dataflow = classContext.getLockDataflow(method);

        for (Iterator<Location> j = cfg.locationIterator(); j.hasNext();) {
            Location location = j.next();
            visitLocation(classContext, location, methodGen, dataflow);
        }
    }
 
Example 20
Source Project: commons-bcel   Source File: PLSETestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * BCEL-79:
 */
public void testB79() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    final Method m = gen.getMethodAt(2);
    final LocalVariableTable lvt = m.getLocalVariableTable();
    //System.out.println(lvt);
    //System.out.println(lvt.getTableLength());
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    //System.out.println(new_lvt);
    assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());
}
 
Example 21
@Override
public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg,
        Dataflow<ResourceValueFrame, ResourceValueAnalysis<Lock>> dataflow, Lock resource) {

    JavaClass javaClass = classContext.getJavaClass();

    ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit());
    if (DEBUG) {
        System.out.println("Resource value at exit: " + exitFrame);
    }
    int exitStatus = exitFrame.getStatus();

    if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {
        String bugType;
        int priority;
        if (exitStatus == ResourceValueFrame.OPEN) {
            bugType = "UL_UNRELEASED_LOCK";
            priority = HIGH_PRIORITY;
        } else {
            bugType = "UL_UNRELEASED_LOCK_EXCEPTION_PATH";
            priority = NORMAL_PRIORITY;
        }

        String sourceFile = javaClass.getSourceFileName();
        Location location = resource.getLocation();
        InstructionHandle handle = location.getHandle();
        InstructionHandle nextInstruction = handle.getNext();
        if (nextInstruction.getInstruction() instanceof RETURN) {
            return; // don't report as error; intentional
        }
        bugAccumulator.accumulateBug(new BugInstance(this, bugType, priority).addClassAndMethod(methodGen, sourceFile),
                SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
    }
}
 
Example 22
private void handleSuspiciousRefComparison(JavaClass jclass, Method method, MethodGen methodGen,
        List<WarningWithProperties> refComparisonList, Location location, String lhs, ReferenceType lhsType,
        ReferenceType rhsType) {
    XField xf = null;
    if (lhsType instanceof FinalConstant) {
        xf = ((FinalConstant) lhsType).getXField();
    } else if (rhsType instanceof FinalConstant) {
        xf = ((FinalConstant) rhsType).getXField();
    }
    String sourceFile = jclass.getSourceFileName();
    String bugPattern = "RC_REF_COMPARISON";
    int priority = Priorities.HIGH_PRIORITY;
    if ("java.lang.Boolean".equals(lhs)) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN";
        priority = Priorities.NORMAL_PRIORITY;
    } else if (xf != null && xf.isStatic() && xf.isFinal()) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE";
        if (xf.isPublic() || !methodGen.isPublic()) {
            priority = Priorities.NORMAL_PRIORITY;
        }
    }
    BugInstance instance = new BugInstance(this, bugPattern, priority).addClassAndMethod(methodGen, sourceFile)
            .addType("L" + lhs.replace('.', '/') + ";").describe(TypeAnnotation.FOUND_ROLE);
    if (xf != null) {
        instance.addField(xf).describe(FieldAnnotation.LOADED_FROM_ROLE);
    } else {
        instance.addSomeSourceForTopTwoStackValues(classContext, method, location);
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
            sourceFile, location.getHandle());

    refComparisonList.add(new WarningWithProperties(instance, new WarningPropertySet<>(),
            sourceLineAnnotation, location));
}
 
Example 23
private BugInstance generateBugInstance(JavaClass javaClass, MethodGen methodGen, InstructionHandle handle,
        StringAppendState stringAppendState, boolean isExecute) {
    int priority = LOW_PRIORITY;
    boolean sawSeriousTaint = false;
    if (stringAppendState.getSawAppend(handle)) {
        if (stringAppendState.getSawOpenQuote(handle) && stringAppendState.getSawCloseQuote(handle)) {
            priority = HIGH_PRIORITY;
        } else if (stringAppendState.getSawComma(handle)) {
            priority = NORMAL_PRIORITY;
        }

        if (!stringAppendState.getSawUnsafeAppend(handle)) {
            priority += 2;
        } else if (stringAppendState.getSawSeriousTaint(handle)) {
            priority--;
            sawSeriousTaint = true;
        } else if (!stringAppendState.getSawTaint(handle)) {
            priority++;
        }
    }

    String description;
    if (isExecute) {
        description = "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE";
    } else {
        description = "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING";
    }

    BugInstance bug = new BugInstance(this, description, priority);
    bug.addClassAndMethod(methodGen, javaClass.getSourceFileName());
    if (sawSeriousTaint) {
        bug.addString("non-constant SQL string involving HTTP taint");
    }

    return bug;
}
 
Example 24
Source Project: spotbugs   Source File: LockAnalysis.java    License: 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());
    }
}
 
Example 25
@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 26
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 27
Source Project: spotbugs   Source File: BugInstance.java    License: 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
/**
 * 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 29
Source Project: commons-bcel   Source File: TestArrayAccess02Creator.java    License: 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 30
Source Project: cougar   Source File: ComplexObjectCreator.java    License: 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();
}