Search in sources :

Example 1 with ConstantUtf8

use of org.apache.bcel.classfile.ConstantUtf8 in project fb-contrib by mebigfatguy.

the class FieldCouldBeLocal method visitClassContext.

/**
 * overrides the visitor to collect localizable fields, and then report those that survive all method checks.
 *
 * @param classContext
 *            the context object that holds the JavaClass parsed
 */
@Override
public void visitClassContext(ClassContext classContext) {
    try {
        localizableFields = new HashMap<>();
        visitedBlocks = new BitSet();
        clsContext = classContext;
        clsName = clsContext.getJavaClass().getClassName();
        clsSig = SignatureUtils.classToSignature(clsName);
        JavaClass cls = classContext.getJavaClass();
        Field[] fields = cls.getFields();
        ConstantPool cp = classContext.getConstantPoolGen().getConstantPool();
        for (Field f : fields) {
            if (!f.isStatic() && !f.isVolatile() && (f.getName().indexOf(Values.SYNTHETIC_MEMBER_CHAR) < 0) && f.isPrivate()) {
                FieldAnnotation fa = new FieldAnnotation(cls.getClassName(), f.getName(), f.getSignature(), false);
                boolean hasExternalAnnotation = false;
                for (AnnotationEntry entry : f.getAnnotationEntries()) {
                    ConstantUtf8 cutf = (ConstantUtf8) cp.getConstant(entry.getTypeIndex());
                    if (!cutf.getBytes().startsWith(Values.JAVA)) {
                        hasExternalAnnotation = true;
                        break;
                    }
                }
                localizableFields.put(f.getName(), new FieldInfo(fa, hasExternalAnnotation));
            }
        }
        if (!localizableFields.isEmpty()) {
            buildMethodFieldModifiers(classContext);
            super.visitClassContext(classContext);
            for (FieldInfo fi : localizableFields.values()) {
                FieldAnnotation fa = fi.getFieldAnnotation();
                SourceLineAnnotation sla = fi.getSrcLineAnnotation();
                BugInstance bug = new BugInstance(this, BugType.FCBL_FIELD_COULD_BE_LOCAL.name(), NORMAL_PRIORITY).addClass(this).addField(fa);
                if (sla != null) {
                    bug.addSourceLine(sla);
                }
                bugReporter.reportBug(bug);
            }
        }
    } finally {
        localizableFields = null;
        visitedBlocks = null;
        clsContext = null;
        methodFieldModifiers = null;
    }
}
Also used : BitSet(java.util.BitSet) BugInstance(edu.umd.cs.findbugs.BugInstance) ConstantUtf8(org.apache.bcel.classfile.ConstantUtf8) Field(org.apache.bcel.classfile.Field) AnnotationEntry(org.apache.bcel.classfile.AnnotationEntry) JavaClass(org.apache.bcel.classfile.JavaClass) SourceLineAnnotation(edu.umd.cs.findbugs.SourceLineAnnotation) ConstantPool(org.apache.bcel.classfile.ConstantPool) FieldAnnotation(edu.umd.cs.findbugs.FieldAnnotation)

Example 2 with ConstantUtf8

use of org.apache.bcel.classfile.ConstantUtf8 in project fb-contrib by mebigfatguy.

the class RegisterUtilsTest method shouldGetParameterRegisters.

@Test(dataProvider = "parameterRegisters")
public void shouldGetParameterRegisters(int accessFlags, String signature, int[] expected) {
    Method method = new Method();
    method.setAccessFlags(accessFlags);
    Constant[] cnst = new Constant[] { new ConstantUtf8(signature) };
    ConstantPool cp = new ConstantPool(cnst) {

        @Override
        protected Object clone() throws CloneNotSupportedException {
            throw new CloneNotSupportedException();
        }
    };
    method.setConstantPool(cp);
    method.setSignatureIndex(0);
    int[] regs = RegisterUtils.getParameterRegisters(method);
    assertEquals(regs, expected);
}
Also used : Constant(org.apache.bcel.classfile.Constant) ConstantPool(org.apache.bcel.classfile.ConstantPool) Method(org.apache.bcel.classfile.Method) BeforeMethod(org.testng.annotations.BeforeMethod) ConstantUtf8(org.apache.bcel.classfile.ConstantUtf8) Test(org.testng.annotations.Test)

Example 3 with ConstantUtf8

use of org.apache.bcel.classfile.ConstantUtf8 in project fb-contrib by mebigfatguy.

the class OptionalIssues method sawOpcode.

/**
 * implements the visitor to look for reference compares of Optional, Optional use when more specific Optionals should be used, and use of orElse when
 * orElseGet would be more appropriate
 *
 * @param seen
 *            the opcode of the currently parsed instruction
 */
@Override
public void sawOpcode(int seen) {
    FQMethod curCalledMethod = null;
    Boolean sawPlainOptional = null;
    try {
        switch(seen) {
            case Const.IFNULL:
            case Const.IFNONNULL:
                if (stack.getStackDepth() > 0) {
                    OpcodeStack.Item itm = stack.getStackItem(0);
                    if ("Ljava/util/Optional;".equals(itm.getSignature())) {
                        bugReporter.reportBug(new BugInstance(this, BugType.OI_OPTIONAL_ISSUES_CHECKING_REFERENCE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
                    }
                }
                break;
            case Const.INVOKEDYNAMIC:
                // smells like a hack. Not sure how to do this better
                ConstantInvokeDynamic id = (ConstantInvokeDynamic) getConstantRefOperand();
                ConstantPool cp = getConstantPool();
                ConstantNameAndType nameAndType = (ConstantNameAndType) cp.getConstant(id.getNameAndTypeIndex());
                ConstantUtf8 typeConstant = (ConstantUtf8) cp.getConstant(nameAndType.getSignatureIndex());
                curCalledMethod = new FQMethod(getClassName(), "lambda$" + id.getBootstrapMethodAttrIndex(), typeConstant.getBytes());
                break;
            case Const.INVOKESTATIC:
            case Const.INVOKEINTERFACE:
            case Const.INVOKESPECIAL:
                String clsName = getClassConstantOperand();
                String methodName = getNameConstantOperand();
                curCalledMethod = new FQMethod(clsName, methodName, getSigConstantOperand());
                if ("java/util/Optional".equals(clsName) && "of".equals(methodName)) {
                    if (stack.getStackDepth() > 0) {
                        OpcodeStack.Item itm = stack.getStackItem(0);
                        String itmSig = itm.getSignature();
                        if (BOXED_OPTIONAL_TYPES.contains(itmSig)) {
                            bugReporter.reportBug(new BugInstance(this, BugType.OI_OPTIONAL_ISSUES_PRIMITIVE_VARIANT_PREFERRED.name(), LOW_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
                        }
                    }
                }
                break;
            case Const.INVOKEVIRTUAL:
                curCalledMethod = new FQMethod(getClassConstantOperand(), getNameConstantOperand(), getSigConstantOperand());
                if (OR_ELSE_METHODS.contains(curCalledMethod)) {
                    if (stack.getStackDepth() > 0) {
                        OpcodeStack.Item itm = stack.getStackItem(0);
                        if ((itm.getRegisterNumber() < 0) && (itm.getReturnValueOf() != null) && !isTrivialStackOps()) {
                            bugReporter.reportBug(new BugInstance(this, BugType.OI_OPTIONAL_ISSUES_USES_IMMEDIATE_EXECUTION.name(), NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
                        }
                    }
                    if (OPTIONAL_OR_ELSE_METHOD.equals(curCalledMethod)) {
                        sawPlainOptional = Boolean.TRUE;
                    }
                } else if (OR_ELSE_GET_METHODS.contains(curCalledMethod)) {
                    if (!activeStackOps.isEmpty()) {
                        ActiveStackOp op = activeStackOps.getLast();
                        FQMethod method = op.getMethod();
                        if (method == null) {
                            bugReporter.reportBug(new BugInstance(this, BugType.OI_OPTIONAL_ISSUES_USES_ORELSEGET_WITH_NULL.name(), LOW_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
                        } else {
                            Method getMethod = getLambdaMethod(method.getMethodName());
                            if (getMethod != null) {
                                byte[] byteCode = getMethod.getCode().getCode();
                                if (byteCode.length <= 4) {
                                    // we are looking for ALOAD, GETFIELD, or LDC followed by ARETURN, that should fit in 4 bytes
                                    if (!hasInvoke(byteCode)) {
                                        bugReporter.reportBug(new BugInstance(this, BugType.OI_OPTIONAL_ISSUES_USES_DELAYED_EXECUTION.name(), LOW_PRIORITY).addClass(this).addMethod(this).addSourceLine(this));
                                    }
                                }
                            }
                        }
                    }
                    if (OPTIONAL_OR_ELSE_GET_METHOD.equals(curCalledMethod)) {
                        sawPlainOptional = Boolean.TRUE;
                    }
                } else if (OPTIONAL_GET_METHOD.equals(curCalledMethod)) {
                    sawPlainOptional = Boolean.TRUE;
                }
                break;
        }
    } finally {
        stack.sawOpcode(this, seen);
        int stackDepth = stack.getStackDepth();
        if (stackDepth == 0) {
            activeStackOps.clear();
        } else {
            activeStackOps.addLast(new ActiveStackOp(seen, curCalledMethod));
            while (activeStackOps.size() > stackDepth) {
                activeStackOps.removeFirst();
            }
            if (sawPlainOptional != null) {
                OpcodeStack.Item itm = stack.getStackItem(0);
                itm.setUserValue(sawPlainOptional);
            }
        }
    }
}
Also used : OpcodeStack(edu.umd.cs.findbugs.OpcodeStack) BugInstance(edu.umd.cs.findbugs.BugInstance) ToString(com.mebigfatguy.fbcontrib.utils.ToString) Method(org.apache.bcel.classfile.Method) FQMethod(com.mebigfatguy.fbcontrib.utils.FQMethod) ConstantUtf8(org.apache.bcel.classfile.ConstantUtf8) ConstantNameAndType(org.apache.bcel.classfile.ConstantNameAndType) ConstantPool(org.apache.bcel.classfile.ConstantPool) FQMethod(com.mebigfatguy.fbcontrib.utils.FQMethod) ConstantInvokeDynamic(org.apache.bcel.classfile.ConstantInvokeDynamic)

Example 4 with ConstantUtf8

use of org.apache.bcel.classfile.ConstantUtf8 in project jop by jop-devel.

the class ConstantPoolRebuilder method copyConstant.

public static Constant copyConstant(Map<Integer, Integer> idMap, Constant c) {
    if (c instanceof ConstantClass) {
        int index = ((ConstantClass) c).getNameIndex();
        return new ConstantClass(idMap.get(index));
    } else if (c instanceof ConstantFieldref) {
        int clsIdx = ((ConstantFieldref) c).getClassIndex();
        int nameIdx = ((ConstantFieldref) c).getNameAndTypeIndex();
        return new ConstantFieldref(idMap.get(clsIdx), idMap.get(nameIdx));
    } else if (c instanceof ConstantMethodref) {
        int clsIdx = ((ConstantMethodref) c).getClassIndex();
        int nameIdx = ((ConstantMethodref) c).getNameAndTypeIndex();
        return new ConstantMethodref(idMap.get(clsIdx), idMap.get(nameIdx));
    } else if (c instanceof ConstantInterfaceMethodref) {
        int clsIdx = ((ConstantInterfaceMethodref) c).getClassIndex();
        int nameIdx = ((ConstantInterfaceMethodref) c).getNameAndTypeIndex();
        return new ConstantInterfaceMethodref(idMap.get(clsIdx), idMap.get(nameIdx));
    } else if (c instanceof ConstantString) {
        int index = ((ConstantString) c).getStringIndex();
        return new ConstantString(idMap.get(index));
    } else if (c instanceof ConstantInteger) {
        return new ConstantInteger((ConstantInteger) c);
    } else if (c instanceof ConstantFloat) {
        return new ConstantFloat((ConstantFloat) c);
    } else if (c instanceof ConstantLong) {
        return new ConstantLong((ConstantLong) c);
    } else if (c instanceof ConstantDouble) {
        return new ConstantDouble((ConstantDouble) c);
    } else if (c instanceof ConstantNameAndType) {
        int nameIdx = ((ConstantNameAndType) c).getNameIndex();
        int sigIdx = ((ConstantNameAndType) c).getSignatureIndex();
        return new ConstantNameAndType(idMap.get(nameIdx), idMap.get(sigIdx));
    } else if (c instanceof ConstantUtf8) {
        return new ConstantUtf8((ConstantUtf8) c);
    }
    throw new JavaClassFormatError("Unknown constant type " + c);
}
Also used : ConstantString(org.apache.bcel.classfile.ConstantString) ConstantDouble(org.apache.bcel.classfile.ConstantDouble) ConstantUtf8(org.apache.bcel.classfile.ConstantUtf8) ConstantFloat(org.apache.bcel.classfile.ConstantFloat) ConstantNameAndType(org.apache.bcel.classfile.ConstantNameAndType) ConstantMethodref(org.apache.bcel.classfile.ConstantMethodref) ConstantLong(org.apache.bcel.classfile.ConstantLong) ConstantFieldref(org.apache.bcel.classfile.ConstantFieldref) JavaClassFormatError(com.jopdesign.common.misc.JavaClassFormatError) ConstantInterfaceMethodref(org.apache.bcel.classfile.ConstantInterfaceMethodref) ConstantClass(org.apache.bcel.classfile.ConstantClass) ConstantInteger(org.apache.bcel.classfile.ConstantInteger)

Example 5 with ConstantUtf8

use of org.apache.bcel.classfile.ConstantUtf8 in project OpenGrok by OpenGrok.

the class JavaClassAnalyzer method constantToString.

public String constantToString(Constant c, ConstantPool cp, int[] v) throws ClassFormatException {
    String str;
    int i, j, k;
    byte tag = c.getTag();
    switch(tag) {
        case org.apache.bcel.Const.CONSTANT_Class:
            i = ((ConstantClass) c).getNameIndex();
            v[i] = 1;
            Constant con = cp.getConstant(i, org.apache.bcel.Const.CONSTANT_Utf8);
            str = Utility.compactClassName(((ConstantUtf8) con).getBytes(), false);
            break;
        case org.apache.bcel.Const.CONSTANT_String:
            i = ((ConstantString) c).getStringIndex();
            v[i] = 1;
            Constant con2 = cp.getConstant(i, org.apache.bcel.Const.CONSTANT_Utf8);
            str = ((ConstantUtf8) con2).getBytes();
            break;
        case org.apache.bcel.Const.CONSTANT_Utf8:
            str = ((ConstantUtf8) c).toString();
            break;
        case org.apache.bcel.Const.CONSTANT_Double:
            str = ((ConstantDouble) c).toString();
            break;
        case org.apache.bcel.Const.CONSTANT_Float:
            str = ((ConstantFloat) c).toString();
            break;
        case org.apache.bcel.Const.CONSTANT_Long:
            str = ((ConstantLong) c).toString();
            break;
        case org.apache.bcel.Const.CONSTANT_Integer:
            str = ((ConstantInteger) c).toString();
            break;
        case org.apache.bcel.Const.CONSTANT_NameAndType:
            i = ((ConstantNameAndType) c).getNameIndex();
            v[i] = 1;
            j = ((ConstantNameAndType) c).getSignatureIndex();
            v[j] = 1;
            String sig = constantToString(cp.getConstant(j), cp, v);
            if (sig.charAt(0) == '(') {
                str = Utility.methodSignatureToString(sig, constantToString(cp.getConstant(i), cp, v), " ");
            } else {
                str = Utility.signatureToString(sig) + ' ' + constantToString(cp.getConstant(i), cp, v);
            }
            break;
        case org.apache.bcel.Const.CONSTANT_InterfaceMethodref:
        case org.apache.bcel.Const.CONSTANT_Methodref:
        case org.apache.bcel.Const.CONSTANT_Fieldref:
            i = ((ConstantCP) c).getClassIndex();
            v[i] = 1;
            j = ((ConstantCP) c).getNameAndTypeIndex();
            v[j] = 1;
            str = (constantToString(cp.getConstant(i), cp, v) + ' ' + constantToString(cp.getConstant(j), cp, v));
            break;
        case org.apache.bcel.Const.CONSTANT_MethodType:
            i = ((ConstantMethodType) c).getDescriptorIndex();
            v[i] = 1;
            str = constantToString(cp.getConstant(i), cp, v);
            break;
        // }
        case org.apache.bcel.Const.CONSTANT_MethodHandle:
            // TODO fix implementation as per below to have proper lookup table/constants
            // i = ((ConstantMethodHandle) c).getReferenceKind();
            // v[i] = 1;
            // j = ((ConstantMethodHandle) c).getReferenceIndex();
            // v[j] = 1;
            // str = (constantToString(cp.getConstant(i), cp, v) + ' ' +
            // constantToString(cp.getConstant(j), cp, v));
            str = "";
            break;
        // }
        case org.apache.bcel.Const.CONSTANT_InvokeDynamic:
            // TODO fix implementation as per below and add bootstrap method tables first
            // i = ((ConstantInvokeDynamic) c).getClassIndex();
            // v[i] = 1;
            // j = ((ConstantInvokeDynamic) c).getNameAndTypeIndex();
            // v[j] = 1;
            // k = ((ConstantInvokeDynamic) c).getBootstrapMethodAttrIndex();
            // v[k] = 1;
            // str = (constantToString(cp.getConstant(i), cp, v) + ' ' +
            // constantToString(cp.getConstant(j), cp, v) + ' ' +
            // constantToString(cp.getConstant(k), cp, v));
            str = "";
            break;
        case org.apache.bcel.Const.CONSTANT_Package:
            i = ((ConstantPackage) c).getNameIndex();
            v[i] = 1;
            str = constantToString(cp.getConstant(i), cp, v);
            break;
        case org.apache.bcel.Const.CONSTANT_Module:
            i = ((ConstantModule) c).getNameIndex();
            v[i] = 1;
            str = constantToString(cp.getConstant(i), cp, v);
            break;
        default:
            // Never reached
            throw new ClassFormatException("Unknown constant type " + tag);
    }
    return str;
}
Also used : Constant(org.apache.bcel.classfile.Constant) ConstantString(org.apache.bcel.classfile.ConstantString) ConstantUtf8(org.apache.bcel.classfile.ConstantUtf8) ClassFormatException(org.apache.bcel.classfile.ClassFormatException)

Aggregations

ConstantUtf8 (org.apache.bcel.classfile.ConstantUtf8)6 ConstantPool (org.apache.bcel.classfile.ConstantPool)4 ConstantNameAndType (org.apache.bcel.classfile.ConstantNameAndType)3 BugInstance (edu.umd.cs.findbugs.BugInstance)2 Constant (org.apache.bcel.classfile.Constant)2 ConstantClass (org.apache.bcel.classfile.ConstantClass)2 ConstantInvokeDynamic (org.apache.bcel.classfile.ConstantInvokeDynamic)2 ConstantString (org.apache.bcel.classfile.ConstantString)2 Method (org.apache.bcel.classfile.Method)2 JavaClassFormatError (com.jopdesign.common.misc.JavaClassFormatError)1 MethodInfo (com.mebigfatguy.fbcontrib.collect.MethodInfo)1 FQMethod (com.mebigfatguy.fbcontrib.utils.FQMethod)1 ToString (com.mebigfatguy.fbcontrib.utils.ToString)1 FieldAnnotation (edu.umd.cs.findbugs.FieldAnnotation)1 OpcodeStack (edu.umd.cs.findbugs.OpcodeStack)1 SourceLineAnnotation (edu.umd.cs.findbugs.SourceLineAnnotation)1 BitSet (java.util.BitSet)1 AnnotationEntry (org.apache.bcel.classfile.AnnotationEntry)1 BootstrapMethod (org.apache.bcel.classfile.BootstrapMethod)1 ClassFormatException (org.apache.bcel.classfile.ClassFormatException)1