Package org.apache.bcel.classfile

Examples of org.apache.bcel.classfile.JavaClass


     *   if the class or interface referenced cannot
     *   be found: use referencesClassExact() instead
     */
    public boolean referencesClass() {
        try {
            JavaClass jc = Repository.lookupClass(class_name);
            return jc.isClass();
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
View Full Code Here


     *   if the class or interface referenced cannot
     *   be found: use referencesInterfaceExact() instead
     */
    public boolean referencesInterface() {
        try {
            JavaClass jc = Repository.lookupClass(class_name);
            return !jc.isClass();
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
View Full Code Here

     *   it references an interface
     * @throws ClassNotFoundException if the class or interface
     *   referenced by this type can't be found
     */
    public boolean referencesClassExact() throws ClassNotFoundException {
        JavaClass jc = Repository.lookupClass(class_name);
        return jc.isClass();
    }
View Full Code Here

     *   it references a class
     * @throws ClassNotFoundException if the class or interface
     *   referenced by this type can't be found
     */
    public boolean referencesInterfaceExact() throws ClassNotFoundException {
        JavaClass jc = Repository.lookupClass(class_name);
        return !jc.isClass();
    }
View Full Code Here

     * Java Virtual Machine Specification edition 2, � 5.4.4 Access Control
     * @throws ClassNotFoundException if the class referenced by this type
     *   can't be found
     */
    public boolean accessibleTo( ObjectType accessor ) throws ClassNotFoundException {
        JavaClass jc = Repository.lookupClass(class_name);
        if (jc.isPublic()) {
            return true;
        } else {
            JavaClass acc = Repository.lookupClass(accessor.class_name);
            return acc.getPackageName().equals(jc.getPackageName());
        }
    }
View Full Code Here

                        equalsMethod = MethodAnnotation.fromVisitedMethod(this);
                    }
                } else {
                    String arg = m.group(1);
                    if (getSuperclassName().equals(arg)) {
                        JavaClass findSuperImplementor = Lookup.findSuperDefiner(getThisClass(), name, sig, bugReporter);
                        if (findSuperImplementor == null) {
                            hasEqualsOther = true;
                            equalsOtherMethod = MethodAnnotation.fromVisitedMethod(this);
                            equalsOtherClass = DescriptorFactory.createClassDescriptor(arg);
                        }
View Full Code Here

        }
    }

    private void check(int pos) {
        OpcodeStack.Item item = stack.getStackItem(pos);
        JavaClass type = null;

        try {
            type = item.getJavaClass();
        } catch (ClassNotFoundException e) {
            AnalysisContext.reportMissingClass(e);
        }
        if (type == null) {
            return;
        }
        String typeName = type.getClassName();
        if (typeName.startsWith("java.lang")) {
            return;
        }
        int priority = NORMAL_PRIORITY;

        OpcodeStack.Item collection = stack.getStackItem(PreorderVisitor.getNumberArguments(getSigConstantOperand()));
        String collectionSignature = collection.getSignature();
        if (collectionSignature.indexOf("Tree") >= 0
                || collectionSignature.indexOf("Sorted") >= 0
                || collectionSignature.indexOf("SkipList") >= 0 ) {
            return;
        }

        if (collectionSignature.indexOf("Hash") >= 0) {
            priority--;
        }
        if (!AnalysisContext.currentAnalysisContext()/* .getSubtypes() */.isApplicationClass(type)) {
            priority++;
        }

        if (type.isAbstract() || type.isInterface()) {
            priority++;
        }
        potentialBugs.put(
                type.getClassName(),
                new BugInstance(this, "HE_USE_OF_UNHASHABLE_CLASS", priority).addClassAndMethod(this)
                .addTypeOfNamedClass(type.getClassName()).describe(TypeAnnotation.UNHASHABLE_ROLE).addCalledMethod(this)
                .addSourceLine(this));
    }
View Full Code Here

            return;
        }
        if (className.startsWith("java.lang")) {
            return;
        }
        JavaClass type = null;

        try {
            type = Repository.lookupClass(className);
        } catch (ClassNotFoundException e) {
            AnalysisContext.reportMissingClass(e);
        }
        if (type == null) {
            return;
        }

        int priority = NORMAL_PRIORITY;
        if (sig.indexOf("Hash") >= 0) {
            priority--;
        }
        if (type.isAbstract() || type.isInterface()) {
            priority++;
        }
        if (!AnalysisContext.currentAnalysisContext()/* .getSubtypes() */.isApplicationClass(type)) {
            priority++;
        }
View Full Code Here

        if (getMethodName().equals("<clinit>") && (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC)) {
            String clazz = getClassConstantOperand();
            if (!clazz.equals(getClassName())) {
                try {
                    JavaClass targetClass = Repository.lookupClass(clazz);
                    if (Repository.instanceOf(targetClass, getThisClass())) {
                        int priority = NORMAL_PRIORITY;
                        if (seen == GETSTATIC) {
                            priority--;
                        }
                        if (!targetClass.isPublic()) {
                            priority++;
                        }
                        bugAccumulator.accumulateBug(new BugInstance(this, "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION",
                                priority).addClassAndMethod(this).addClass(getClassConstantOperand()), this);

                    }
                } catch (ClassNotFoundException e) {
                    // ignore it
                }

            }
        }
        /*
        if (false && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("equals")
                && getSigConstantOperand().equals("(Ljava/lang/Object;)Z") && stack.getStackDepth() > 1) {
            OpcodeStack.Item item0 = stack.getStackItem(0);
            OpcodeStack.Item item1 = stack.getStackItem(1);

            if (item0.isArray() || item1.isArray()) {
                bugAccumulator.accumulateBug(
                        new BugInstance(this, "EC_BAD_ARRAY_COMPARE", NORMAL_PRIORITY).addClassAndMethod(this), this);
            }
        }
         */

        if (seen >= IALOAD && seen <= SALOAD || seen >= IASTORE && seen <= SASTORE) {
            Item index = stack.getStackItem(0);
            if (index.getSpecialKind() == Item.AVERAGE_COMPUTED_USING_DIVISION) {
                SourceLineAnnotation where;
                if (index.getPC() >= 0) {
                    where = SourceLineAnnotation.fromVisitedInstruction(this, index.getPC());
                } else {
                    where = SourceLineAnnotation.fromVisitedInstruction(this);
                }
                bugAccumulator.accumulateBug(
                        new BugInstance(this, "IM_AVERAGE_COMPUTATION_COULD_OVERFLOW", NORMAL_PRIORITY).addClassAndMethod(this),
                        where);
            }

        }

        if ((seen == IFEQ || seen == IFNE) && getPrevOpcode(1) == IMUL
                && (getPrevOpcode(2) == SIPUSH || getPrevOpcode(2) == BIPUSH) && getPrevOpcode(3) == IREM) {
            bugAccumulator.accumulateBug(
                    new BugInstance(this, "IM_MULTIPLYING_RESULT_OF_IREM", LOW_PRIORITY).addClassAndMethod(this), this);
        }

        if (seen == I2S && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue
                && (!constantArgumentToShift || valueOfConstantArgumentToShift % 16 != 0) || seen == I2B
                && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue
                && (!constantArgumentToShift || valueOfConstantArgumentToShift % 8 != 0)) {
            bugAccumulator.accumulateBug(
                    new BugInstance(this, "ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT", NORMAL_PRIORITY).addClassAndMethod(this),
                    this);
        }

        constantArgumentToShift = false;
        shiftOfNonnegativeValue = false;
        if ((seen == IUSHR || seen == ISHR || seen == ISHL)) {
            if (stack.getStackDepth() <= 1) {
                // don't understand; lie so other detectors won't get concerned
                constantArgumentToShift = true;
                valueOfConstantArgumentToShift = 8;
            } else {
                Object rightHandSide = stack.getStackItem(0).getConstant();

                Object leftHandSide = stack.getStackItem(1).getConstant();
                shiftOfNonnegativeValue = stack.getStackItem(1).isNonNegative();
                if (rightHandSide instanceof Integer) {
                    constantArgumentToShift = true;
                    valueOfConstantArgumentToShift = ((Integer) rightHandSide);
                    if (valueOfConstantArgumentToShift < 0 || valueOfConstantArgumentToShift >= 32) {
                        bugAccumulator.accumulateBug(new BugInstance(this, "ICAST_BAD_SHIFT_AMOUNT",
                                valueOfConstantArgumentToShift < 0 ? LOW_PRIORITY : (valueOfConstantArgumentToShift == 32
                                && getMethodName().equals("hashCode") ? NORMAL_PRIORITY : HIGH_PRIORITY))
                        .addClassAndMethod(this).addInt(valueOfConstantArgumentToShift).describe(IntAnnotation.INT_SHIFT)
                        .addValueSource(stack.getStackItem(1), this), this);
                    }
                }
                if (leftHandSide != null && leftHandSide instanceof Integer && ((Integer) leftHandSide) > 0) {
                    // boring; lie so other detectors won't get concerned
                    constantArgumentToShift = true;
                    valueOfConstantArgumentToShift = 8;
                }

            }
        }

        if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0
                && (getClassConstantOperand().equals("java/util/Date") || getClassConstantOperand().equals("java/sql/Date"))
                && getNameConstantOperand().equals("setMonth") && getSigConstantOperand().equals("(I)V")) {
            OpcodeStack.Item item = stack.getStackItem(0);
            Object o = item.getConstant();
            if (o != null && o instanceof Integer) {
                int v = (Integer) o;
                if (v < 0 || v > 11) {
                    bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", HIGH_PRIORITY).addClassAndMethod(this).addInt(v)
                            .describe(IntAnnotation.INT_VALUE).addCalledMethod(this).addSourceLine(this));
                }
            }
        }

        if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 1 && getClassConstantOperand().equals("java/util/Calendar")
                && getNameConstantOperand().equals("set")

                || seen == INVOKESPECIAL && stack.getStackDepth() > 1
                && getClassConstantOperand().equals("java/util/GregorianCalendar") && getNameConstantOperand().equals("<init>")

                ) {
            String sig = getSigConstantOperand();
            if (sig.startsWith("(III")) {
                int pos = sig.length() - 5;
                OpcodeStack.Item item = stack.getStackItem(pos);
                Object o = item.getConstant();
                if (o != null && o instanceof Integer) {
                    int v = (Integer) o;
                    if (v < 0 || v > 11) {
                        bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY).addClassAndMethod(this)
                                .addInt(v).describe(IntAnnotation.INT_VALUE).addCalledMethod(this).addSourceLine(this));
                    }
                }
            }
        }

        if (isRegisterStore() && (seen == ISTORE || seen == ISTORE_0 || seen == ISTORE_1 || seen == ISTORE_2 || seen == ISTORE_3)
                && getRegisterOperand() == prevOpcodeIncrementedRegister) {
            bugAccumulator.accumulateBug(
                    new BugInstance(this, "DLS_OVERWRITTEN_INCREMENT", HIGH_PRIORITY).addClassAndMethod(this), this);

        }
        if (seen == IINC) {
            prevOpcodeIncrementedRegister = getRegisterOperand();
        } else {
            prevOpcodeIncrementedRegister = -1;
        }

        // Java Puzzlers, Chapter 2, puzzle 1
        // Look for ICONST_2 IREM ICONST_1 IF_ICMPNE L1

        switch (badlyComputingOddState) {
        case 0:
            if (seen == ICONST_2) {
                badlyComputingOddState++;
            }
            break;
        case 1:
            if (seen == IREM) {
                OpcodeStack.Item item = stack.getStackItem(1);
                if (!item.isNonNegative() && item.getSpecialKind() != OpcodeStack.Item.MATH_ABS) {
                    badlyComputingOddState++;
                } else {
                    badlyComputingOddState = 0;
                }
            } else {
                badlyComputingOddState = 0;
            }
            break;
        case 2:
            if (seen == ICONST_1) {
                badlyComputingOddState++;
            } else {
                badlyComputingOddState = 0;
            }
            break;
        case 3:
            if (seen == IF_ICMPEQ || seen == IF_ICMPNE) {
                bugAccumulator.accumulateBug(
                        new BugInstance(this, "IM_BAD_CHECK_FOR_ODD", NORMAL_PRIORITY).addClassAndMethod(this), this);
            }
            badlyComputingOddState = 0;
            break;
        default:
            break;
        }

        // Java Puzzlers, chapter 3, puzzle 12
        if (seen == INVOKEVIRTUAL
                && stack.getStackDepth() > 0
                && (getNameConstantOperand().equals("toString") && getSigConstantOperand().equals("()Ljava/lang/String;")
                        || getNameConstantOperand().equals("append")
                        && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuilder;")
                        && getClassConstantOperand().equals("java/lang/StringBuilder")
                        || getNameConstantOperand().equals("append")
                        && getSigConstantOperand().equals("(Ljava/lang/Object;)Ljava/lang/StringBuffer;")
                        && getClassConstantOperand().equals("java/lang/StringBuffer") || (getNameConstantOperand()
                                .equals("print") || getNameConstantOperand().equals("println"))
                                && getSigConstantOperand().equals("(Ljava/lang/Object;)V"))) {
            OpcodeStack.Item item = stack.getStackItem(0);
            String signature = item.getSignature();
            if (signature != null && signature.startsWith("[")) {
                boolean debuggingContext = signature.equals("[Ljava/lang/StackTraceElement;");

                if (!debuggingContext) {
                    for (CodeException e : getCode().getExceptionTable()) {
                        if (e.getHandlerPC() <= getPC() && e.getHandlerPC() + 30 >= getPC()) {
                            debuggingContext = true;
                        }
                    }

                    for (int i = 1; !debuggingContext && i < stack.getStackDepth(); i++) {
                        OpcodeStack.Item e = stack.getStackItem(i);

                        if (e.getSignature().indexOf("Logger") >= 0 || e.getSignature().indexOf("Exception") >= 0) {
                            debuggingContext = true;
                        }

                        XField f = e.getXField();
                        if (f != null && (SYSTEM_ERR.equals(f.getFieldDescriptor()) || SYSTEM_OUT.equals(f.getFieldDescriptor()))) {
                            debuggingContext = true;
                        }
                    }
                }
                //                String name = null;
                int reg = item.getRegisterNumber();
                Collection<BugAnnotation> as = new ArrayList<BugAnnotation>();
                XField field = item.getXField();
                FieldAnnotation fieldAnnotation = null;
                if (field != null) {
                    fieldAnnotation = FieldAnnotation.fromXField(field);
                    fieldAnnotation.setDescription(FieldAnnotation.LOADED_FROM_ROLE);
                }

                if (reg != -1) {
                    LocalVariableAnnotation lva = LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(), reg, getPC(),
                            getPC() - 1);
                    if (lva.isNamed()) {
                        as.add(lva);
                        if (fieldAnnotation != null) {
                            as.add(fieldAnnotation);
                        }
                    } else {
                        if (fieldAnnotation != null) {
                            as.add(fieldAnnotation);
                        }
                        as.add(lva);
                    }
                } else if (fieldAnnotation != null) {
                    as.add(fieldAnnotation);
                } else {
                    XMethod m = item.getReturnValueOf();
                    if (m != null) {
                        MethodAnnotation methodAnnotation = MethodAnnotation.fromXMethod(m);
                        methodAnnotation.setDescription(MethodAnnotation.METHOD_RETURN_VALUE_OF);
                        as.add(methodAnnotation);
                    }
                }
                int priority = debuggingContext ? NORMAL_PRIORITY : HIGH_PRIORITY;
                if (!as.isEmpty()) {
                    bugAccumulator.accumulateBug(new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ARRAY", priority)
                    .addClassAndMethod(this).addAnnotations(as), this);
                } else {
                    bugAccumulator.accumulateBug(
                            new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY", priority).addClassAndMethod(this),
                            this);
                }
            }
        }

        if (isTigerOrHigher) {
            if (previousMethodInvocation != null && prevOpCode == INVOKEVIRTUAL && seen == INVOKESTATIC) {
                String classNameForPreviousMethod = previousMethodInvocation.getClassName();
                String classNameForThisMethod = getClassConstantOperand();
                if (classNameForPreviousMethod.startsWith("java.lang.")
                        && classNameForPreviousMethod.equals(classNameForThisMethod.replace('/', '.'))
                        && previousMethodInvocation.getName().endsWith("Value")
                        && previousMethodInvocation.getSignature().length() == 3
                        && getNameConstantOperand().equals("valueOf")
                        && getSigConstantOperand().charAt(1) == previousMethodInvocation.getSignature().charAt(2)) {
                    bugAccumulator.accumulateBug(
                            new BugInstance(this, "BX_UNBOXING_IMMEDIATELY_REBOXED", NORMAL_PRIORITY).addClassAndMethod(this)
                            .addCalledMethod(this),
                            this);
                }

            }

            if (previousMethodInvocation != null && prevOpCode == INVOKESPECIAL && seen == INVOKEVIRTUAL) {
                String classNameForPreviousMethod = previousMethodInvocation.getClassName();
                String classNameForThisMethod = getClassConstantOperand();
                if (classNameForPreviousMethod.startsWith("java.lang.")
                        && classNameForPreviousMethod.equals(classNameForThisMethod.replace('/', '.'))
                        && getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) {
                    if (getSigConstantOperand().charAt(2) == previousMethodInvocation.getSignature().charAt(1)) {
                        bugAccumulator.accumulateBug(
                                new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED", NORMAL_PRIORITY).addClassAndMethod(this),
                                this);
                    } else {
                        bugAccumulator.accumulateBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION",
                                NORMAL_PRIORITY).addClassAndMethod(this), this);
                    }

                    ternaryConversionState = 1;
                } else {
                    ternaryConversionState = 0;
                }

            } else if (seen == INVOKEVIRTUAL) {
                if (getClassConstantOperand().startsWith("java/lang") && getNameConstantOperand().endsWith("Value")
                        && getSigConstantOperand().length() == 3) {
                    ternaryConversionState = 1;
                } else {
                    ternaryConversionState = 0;
                }
            } else if (ternaryConversionState == 1) {
                if (I2L < seen && seen <= I2S) {
                    ternaryConversionState = 2;
                } else {
                    ternaryConversionState = 0;
                }
            } else if (ternaryConversionState == 2) {
                ternaryConversionState = 0;
                if (seen == GOTO) {
                    bugReporter.reportBug(new BugInstance(this, "BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR", NORMAL_PRIORITY)
                    .addClassAndMethod(this).addSourceLine(this));
                }
            } else {
                ternaryConversionState = 0;
            }
        }

        AssertInvokedFromRun: if (seen == INVOKESTATIC) {
            if ((getNameConstantOperand().startsWith("assert") || getNameConstantOperand().startsWith("fail"))
                    && getMethodName().equals("run") && implementsRunnable(getThisClass())) {
                int size1 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Throwable",
                        getPC());
                int size2 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Error",
                        getPC());
                int size3 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(),
                        "java/lang/AssertionFailureError", getPC());
                int size = Math.min(Math.min(size1, size2), size3);
                if (size == Integer.MAX_VALUE) {
                    String dottedClassName = getClassConstantOperand().replace('/', '.');
                    if (!dottedClassName.startsWith("junit")) {
                        try {
                            JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(dottedClassName);
                            if (!targetClass.getSuperclassName().startsWith("junit")) {
                                break AssertInvokedFromRun;
                            }
                        } catch (ClassNotFoundException e) {
                            AnalysisContext.reportMissingClass(e);
                            break AssertInvokedFromRun;
View Full Code Here

    public void visitClassContext(ClassContext classContext) {
        if (qualifiers == null) {
            qualifiers = AnalysisContext.currentAnalysisContext().getDirectlyRelevantTypeQualifiersDatabase();
        }

        JavaClass javaClass = classContext.getJavaClass();
        if (!BCELUtil.preTiger(javaClass)) {
            javaClass.accept(this);
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.bcel.classfile.JavaClass

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.