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

The following examples show how to use org.apache.bcel.classfile.LocalVariable. 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: spotbugs   Source File: LVTHelper.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * returns the local variable at an index int the scope of PC
 *
 * @param lvt
 *            the local variable table
 * @param index
 *            the variable index
 * @param pc
 *            the PC where the variable is used
 */
public static LocalVariable getLocalVariableAtPC(@Nonnull LocalVariableTable lvt, int index, int pc) {
    int length = lvt.getTableLength();
    LocalVariable[] lvs = lvt.getLocalVariableTable();

    for (int i = 0; i < length; i++) {
        if (lvs[i].getIndex() == index) {
            int startPC = lvs[i].getStartPC();
            if ((pc >= startPC) && (pc < (startPC + lvs[i].getLength()))) {
                return lvs[i];
            }
        }
    }

    return null;
}
 
Example 2
public static LocalVariableAnnotation getLocalVariableAnnotation(Method method, int local, int position1, int position2) {

        LocalVariableTable localVariableTable = method.getLocalVariableTable();
        String localName = UNKNOWN_NAME;
        if (localVariableTable != null) {
            LocalVariable lv1 = localVariableTable.getLocalVariable(local, position1);
            if (lv1 == null) {
                lv1 = localVariableTable.getLocalVariable(local, position2);
                position1 = position2;
            }
            if (lv1 != null) {
                localName = lv1.getName();
            }
        }
        LineNumberTable lineNumbers = method.getLineNumberTable();
        if (lineNumbers == null) {
            return new LocalVariableAnnotation(localName, local, position1);
        }
        int line = lineNumbers.getSourceLine(position1);
        return new LocalVariableAnnotation(localName, local, position1, line);
    }
 
Example 3
private void checkReferences()
{
   if (mLocalVariableTable != null) {
      for (int i = 0; i < mLocalVariableTable.getLength(); i++) {
           if (!mLocalVariableBitSet.get(i)) {
               final LocalVariable localVariable =
                   mLocalVariableTable.getLocalVariable(i);
               if (localVariable != null
                   && !localVariable.getName().equals("this"))
               {
                   log(0,
                       "unread.variable",
                       new Object[] {
                           mCurrentJavaClass.getClassName(),
                           mCurrentMethod.getName(),
                           localVariable.getName(),});
               }
           }
       }
   }
}
 
Example 4
private void checkReferences()
{
   if (mLocalVariableTable != null) {
      for (int i = 0; i < mLocalVariableTable.getLength(); i++) {
           if (!mLocalVariableBitSet.get(i)) {
               final LocalVariable localVariable =
                   mLocalVariableTable.getLocalVariable(i);
               if (localVariable != null
                   && !localVariable.getName().equals("this"))
               {
                   log(0,
                       "unread.variable",
                       new Object[] {
                           mCurrentJavaClass.getClassName(),
                           mCurrentMethod.getName(),
                           localVariable.getName(),});
               }
           }
       }
   }
}
 
Example 5
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 6 votes vote down vote up
private void updateLocalVariableTable(final LocalVariableTable a) {
    final LocalVariable[] lv = a.getLocalVariableTable();
    removeLocalVariables();
    for (final LocalVariable l : lv) {
        InstructionHandle start = il.findHandle(l.getStartPC());
        final InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength());
        // Repair malformed handles
        if (null == start) {
            start = il.getStart();
        }
        // end == null => live to end of method
        // Since we are recreating the LocalVaraible, we must
        // propagate the orig_index to new copy.
        addLocalVariable(l.getName(), Type.getType(l.getSignature()), l
                .getIndex(), start, end, l.getOrigIndex());
    }
}
 
Example 6
Source Project: commons-bcel   Source File: LocalVariableGen.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets LocalVariable object.
 *
 * This relies on that the instruction list has already been dumped to byte code or
 * or that the `setPositions' methods has been called for the instruction list.
 *
 * Note that due to the conversion from byte code offset to InstructionHandle,
 * it is impossible to tell the difference between a live range that ends BEFORE
 * the last insturction of the method or a live range that ends AFTER the last
 * instruction of the method.  Hence the liveToEnd flag to differentiate
 * between these two cases.
 *
 * @param cp constant pool
 */
public LocalVariable getLocalVariable( final ConstantPoolGen cp ) {
    int start_pc = 0;
    int length = 0;
    if ((start != null) && (end != null)) {
        start_pc = start.getPosition();
        length = end.getPosition() - start_pc;
        if ((end.getNext() == null) && liveToEnd) {
            length += end.getInstruction().getLength();
        }
    }
    final int name_index = cp.addUtf8(name);
    final int signature_index = cp.addUtf8(type.getSignature());
    return new LocalVariable(start_pc, length, name_index, signature_index, index, cp
            .getConstantPool(), origIndex);
}
 
Example 7
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 8
@Override
public void visitLocalVariableTable(LocalVariableTable obj) {
    super.visitLocalVariableTable(obj);
    LocalVariable[] local_variable_table = obj.getLocalVariableTable();
    for (LocalVariable aLocal_variable_table : local_variable_table) {
        aLocal_variable_table.accept(this);
    }
}
 
Example 9
@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 10
@Override
public void visit(LocalVariableTable obj) {
    if (ENABLE_LOCALS) {
        if (staticMethod) {
            return;
        }

        LocalVariable[] vars = obj.getLocalVariableTable();
        // System.out.println("Num params = " + numParms);
        for (LocalVariable var : vars) {
            if (var.getIndex() < numParms) {
                continue;
            }
            String varName = var.getName();
            if ("serialVersionUID".equals(varName)) {
                continue;
            }
            Field f = classFields.get(varName);
            // System.out.println("Checking " + varName);
            // System.out.println(" got " + f);
            // TODO: we could distinguish between obscuring a field in the
            // same class
            // vs. obscuring a field in a superclass. Not sure how important
            // that is.
            if (f != null) {
                FieldAnnotation fa = FieldAnnotation.fromBCELField(getDottedClassName(), f);
                if (true || var.getStartPC() > 0) {
                    bugReporter.reportBug(new BugInstance(this, "MF_METHOD_MASKS_FIELD", LOW_PRIORITY)
                            .addClassAndMethod(this).addField(fa).addSourceLine(this, var.getStartPC() - 1));
                }
            }
        }
    }
    super.visit(obj);
}
 
Example 11
Source Project: spotbugs   Source File: DontUseEnum.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(LocalVariable obj) {
    if (isReservedName(obj.getName())) {
        LocalVariableAnnotation var = new LocalVariableAnnotation(obj.getName(), obj.getIndex(), obj.getStartPC());
        SourceLineAnnotation source = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this, obj.getStartPC());
        BugInstance bug = new BugInstance(this, "NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER", NORMAL_PRIORITY)
                .addClassAndMethod(this).add(var).add(source);
        bugReporter.reportBug(bug);
    }
}
 
Example 12
Source Project: spotbugs   Source File: OpcodeStack.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
    Method m = dbc.getMethod();
    LocalVariableTable lvt = m.getLocalVariableTable();
    if (lvt != null) {
        LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
        if (lv != null) {
            String signature = lv.getSignature();
            pushByLocalLoad(signature, register);
            return;
        }
    }
    pushByLocalLoad("Ljava/lang/Object;", register);
}
 
Example 13
@CheckForNull
GenericObjectType getLocalVariable(int index, int pos) {
    if (genericLocalVariables == null || !genericLocalVariables.get(index)) {
        return null;
    }
    for (LocalVariable local : localTypeTable.getLocalVariableTypeTable()) {
        if (local.getIndex() == index && local.getStartPC() <= pos
                && pos < +local.getStartPC() + local.getLength()) {
            String signature = local.getSignature();
            if (signature.indexOf('<') < 0) {
                continue;
            }
            Type t;
            try {
                t = GenericUtilities.getType(signature);
                if (t instanceof GenericObjectType) {
                    return (GenericObjectType) t;
                }
            } catch (RuntimeException e) {
                AnalysisContext.logError("Bad signature " + signature
                        + " for " + local.getName(), e);

            }
            return null;
        }
    }
    return null;
}
 
Example 14
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return `LocalVariableTable' attribute of all the local variables of this method.
 */
public LocalVariableTable getLocalVariableTable( final ConstantPoolGen cp ) {
    final LocalVariableGen[] lg = getLocalVariables();
    final int size = lg.length;
    final LocalVariable[] lv = new LocalVariable[size];
    for (int i = 0; i < size; i++) {
        lv[i] = lg[i].getLocalVariable(cp);
    }
    return new LocalVariableTable(cp.addUtf8("LocalVariableTable"), 2 + lv.length * 10, lv, cp
            .getConstantPool());
}
 
Example 15
Source Project: commons-bcel   Source File: MethodGen.java    License: Apache License 2.0 5 votes vote down vote up
private void adjustLocalVariableTypeTable(final LocalVariableTable lvt) {
    final LocalVariable[] lv = lvt.getLocalVariableTable();
    final LocalVariable[] lvg = localVariableTypeTable.getLocalVariableTypeTable();

    for (final LocalVariable element : lvg) {
        for (final LocalVariable l : lv) {
            if (element.getName().equals(l.getName()) && element.getIndex() == l.getOrigIndex()) {
                element.setLength(l.getLength());
                element.setStartPC(l.getStartPC());
                element.setIndex(l.getIndex());
                break;
            }
        }
    }
}
 
Example 16
Source Project: commons-bcel   Source File: Pass2Verifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visitLocalVariable(final LocalVariable obj) {
    // This does not represent an Attribute but is only
    // related to internal BCEL data representation.

    // see visitLocalVariableTable(LocalVariableTable)
}
 
Example 17
public void visit(LocalVariable obj) {
}
 
Example 18
@Override
public void visitLocalVariable(LocalVariable obj) {
    visit(obj);
}
 
Example 19
@Override
public void sawOpcode(int seen) {
    if (iteratorBug != null) {
        if (isRegisterStore()) {
            LocalVariableTable lvt = getMethod().getLocalVariableTable();
            if (lvt != null) {
                LocalVariable localVariable = lvt.getLocalVariable(getRegisterOperand(), getNextPC());
                if (localVariable == null || localVariable.getName().endsWith("$")) {
                    // iterator() result is stored to the synthetic variable which has no name in LVT or name is suffixed with '$'
                    // Looks like it's for-each cycle like for(Object obj : this)
                    // Do not report such case
                    iteratorBug = null;
                }
            }
        }
        if (iteratorBug != null) {
            bugAccumulator.accumulateBug(iteratorBug, this);
        }
        iteratorBug = null;
    }
    if (seen != Const.INVOKEVIRTUAL) {
        return;
    }
    if (!getClassName().equals(getClassConstantOperand())) {
        return;
    }
    XMethod invokedMethod = XFactory.createXMethod(getDottedClassConstantOperand(), getNameConstantOperand(),
            getSigConstantOperand(), false);
    if (invokedMethod.isResolved() && invokedMethod.getClassName().equals(getDottedClassConstantOperand())
            || invokedMethod.isSynthetic()) {
        return;
    }
    if (getStack().getStackItem(getNumberArguments(getSigConstantOperand())).getRegisterNumber() != 0) {
        // called not for this object
        return;
    }
    // method is inherited
    String possibleTargetClass = getDottedClassName();
    String superClassName = getDottedSuperclassName();
    while (true) {
        int i = possibleTargetClass.lastIndexOf('$');
        if (i <= 0) {
            break;
        }
        possibleTargetClass = possibleTargetClass.substring(0, i);
        if (possibleTargetClass.equals(superClassName)) {
            break;
        }
        XMethod alternativeMethod = XFactory.createXMethod(possibleTargetClass, getNameConstantOperand(),
                getSigConstantOperand(), false);
        if (alternativeMethod.isResolved() && alternativeMethod.getClassName().equals(possibleTargetClass)) {
            String targetPackage = invokedMethod.getPackageName();
            String alternativePackage = alternativeMethod.getPackageName();
            int priority = HIGH_PRIORITY;
            if (targetPackage.equals(alternativePackage)) {
                priority++;
            }
            if (targetPackage.startsWith("javax.swing") || targetPackage.startsWith("java.awt")) {
                priority += 2;
            }
            if (invokedMethod.getName().equals(getMethodName())) {
                priority++;
            }

            BugInstance bug = new BugInstance(this, "IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD", priority)
                    .addClassAndMethod(this).addMethod(invokedMethod).describe("METHOD_INHERITED")
                    .addMethod(alternativeMethod).describe("METHOD_ALTERNATIVE_TARGET");
            if (invokedMethod.getName().equals("iterator") && invokedMethod.getSignature().equals("()Ljava/util/Iterator;")
                    && Subtypes2.instanceOf(getDottedClassName(), "java.lang.Iterable")) {
                iteratorBug = bug;
            } else {
                bugAccumulator.accumulateBug(bug, this);
            }
            break;
        }
    }
}
 
Example 20
@Override
public void sawOpcode(int seen) {
    switch (state) {
    case SEEN_NOTHING:
        if (seen == Const.ALOAD) {
            register = getRegisterOperand();
        } else if ((seen >= Const.ALOAD_0) && (seen <= Const.ALOAD_3)) {
            register = seen - Const.ALOAD_0;
        } else {
            return;
        }
        state = SEEN_ALOAD;
        break;

    case SEEN_ALOAD:
        try {
            if (seen == Const.INSTANCEOF) {
                LocalVariable lv = LVTHelper.getLocalVariableAtPC(varTable, register, getPC());
                if (lv != null) {
                    String objSignature = lv.getSignature();
                    if (objSignature.charAt(0) == 'L') {
                        objSignature = objSignature.substring(1, objSignature.length() - 1).replace('/', '.');
                        String clsSignature = getDottedClassConstantOperand();

                        if (clsSignature.charAt(0) != '[') {
                            if (org.apache.bcel.Repository.instanceOf(objSignature, clsSignature)) {
                                bugReporter.reportBug(new BugInstance(this, "SIO_SUPERFLUOUS_INSTANCEOF", LOW_PRIORITY)
                                        .addClassAndMethod(this).addSourceLine(this));
                            }
                        }
                    }
                }
            }
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
        }

        state = SEEN_NOTHING;
        break;
    default:
        break;
    }

}
 
Example 21
Source Project: commons-bcel   Source File: StringRepresentation.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visitLocalVariable(final LocalVariable obj) {
    tostring = toString(obj);
}
 
Example 22
Source Project: commons-bcel   Source File: CounterVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visitLocalVariable(final LocalVariable obj)
{
    localVariableCount++;
}