org.apache.bcel.Const Java Examples

The following examples show how to use org.apache.bcel.Const. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InstructionFactory.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public Instruction createAppend( final Type type ) {
    final byte t = type.getType();
    if (isString(type)) {
        return createInvoke(append_mos[0], Const.INVOKEVIRTUAL);
    }
    switch (t) {
        case Const.T_BOOLEAN:
        case Const.T_CHAR:
        case Const.T_FLOAT:
        case Const.T_DOUBLE:
        case Const.T_BYTE:
        case Const.T_SHORT:
        case Const.T_INT:
        case Const.T_LONG:
            return createInvoke(append_mos[t], Const.INVOKEVIRTUAL);
        case Const.T_ARRAY:
        case Const.T_OBJECT:
            return createInvoke(append_mos[1], Const.INVOKEVIRTUAL);
        default:
            throw new IllegalArgumentException("No append for this type? " + type);
    }
}
 
Example #2
Source File: FindCircularDependencies.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if ((seen == Const.INVOKESPECIAL) || (seen == Const.INVOKESTATIC) || (seen == Const.INVOKEVIRTUAL)) {
        String refClsName = getClassConstantOperand();
        refClsName = refClsName.replace('/', '.');
        if (refClsName.startsWith("java")) {
            return;
        }

        if (clsName.equals(refClsName)) {
            return;
        }

        if (clsName.startsWith(refClsName) && (refClsName.indexOf('$') >= 0)) {
            return;
        }

        if (refClsName.startsWith(clsName) && (clsName.indexOf('$') >= 0)) {
            return;
        }

        Set<String> dependencies = dependencyGraph.computeIfAbsent(clsName, k -> new HashSet<>());

        dependencies.add(refClsName);
    }
}
 
Example #3
Source File: FindRunInvocations.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (alreadySawStart) {
        return;
    }
    if ((seen == Const.INVOKEVIRTUAL || seen == Const.INVOKEINTERFACE) && "()V".equals(getSigConstantOperand())
            && isThread(getDottedClassConstantOperand())) {
        if ("start".equals(getNameConstantOperand())) {
            alreadySawStart = true;
        } else {
            boolean isJustThread = !"java.lang.Thread".equals(getDottedClassConstantOperand());
            if (amVisitingMainMethod() && getPC() == getCode().getLength() - 4 && isJustThread) {
                return;
            } else if ("run".equals(getNameConstantOperand())) {
                bugAccumulator.accumulateBug(new BugInstance(this, "RU_INVOKE_RUN", isJustThread ? HIGH_PRIORITY
                        : NORMAL_PRIORITY).addClassAndMethod(this), this);
            }
        }
    }
}
 
Example #4
Source File: TestArrayAccess03Creator.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
private void createMethod_1() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT },
          new String[] { "arg0" }, "test", TEST_PACKAGE+".TestArrayAccess03", il, _cp);

  final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1));
  Assert.assertNotNull(ih_0); // TODO why is this not used
  il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE+".TestArrayAccess03"), (short) 1));
  il.append(InstructionFactory.createStore(Type.OBJECT, 1));
  final InstructionHandle ih_5 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
  Assert.assertNotNull(ih_5); // TODO why is this not used
  il.append(new PUSH(_cp, 0));
  il.append(_factory.createNew(TEST_PACKAGE+".TestArrayAccess03"));
  il.append(InstructionConst.DUP);
  il.append(_factory.createInvoke(TEST_PACKAGE+".TestArrayAccess03", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL));
  il.append(InstructionConst.AASTORE);
  final InstructionHandle ih_15 = il.append(InstructionFactory.createReturn(Type.VOID));
  Assert.assertNotNull(ih_15); // TODO why is this not used
  method.setMaxStack();
  method.setMaxLocals();
  _cg.addMethod(method.getMethod());
  il.dispose();
}
 
Example #5
Source File: IncompatMask.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void afterOpcode(int seen) {
    super.afterOpcode(seen);
    switch (seen) {
    case Const.IAND:
    case Const.LAND:
    case Const.IOR:
    case Const.LOR:
        if (stack.getStackDepth() > 0) {
            bitresultItem = stack.getStackItem(0);
        }
        break;
    default:
        break;
    }
}
 
Example #6
Source File: ValueNumberFrameModelingVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void checkConsumedAndProducedValues(Instruction ins, ValueNumber[] consumedValueList, ValueNumber[] producedValueList) {
    int numConsumed = ins.consumeStack(getCPG());
    int numProduced = ins.produceStack(getCPG());

    if (numConsumed == Const.UNPREDICTABLE) {
        throw new InvalidBytecodeException("Unpredictable stack consumption for " + ins);
    }
    if (numProduced == Const.UNPREDICTABLE) {
        throw new InvalidBytecodeException("Unpredictable stack production for " + ins);
    }

    if (consumedValueList.length != numConsumed) {
        throw new IllegalStateException("Wrong number of values consumed for " + ins + ": expected " + numConsumed + ", got "
                + consumedValueList.length);
    }

    if (producedValueList.length != numProduced) {
        throw new IllegalStateException("Wrong number of values produced for " + ins + ": expected " + numProduced + ", got "
                + producedValueList.length);
    }
}
 
Example #7
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field obj) {
    if (getFieldName().length() == 1) {
        return;
    }

    if (isEclipseNLS) {
        int flags = obj.getAccessFlags();
        if ((flags & Const.ACC_STATIC) != 0 && ((flags & Const.ACC_PUBLIC) != 0) && "Ljava/lang/String;".equals(getFieldSig())) {
            // ignore "public statis String InstallIUCommandTooltip;"
            // messages from Eclipse NLS bundles
            return;
        }
    }
    if (badFieldName(obj)) {
        bugReporter.reportBug(new BugInstance(this, "NM_FIELD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadFieldNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClass(this).addVisitedField(this));
    }
}
 
Example #8
Source File: FindRoughConstants.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void checkConst(Number constValue) {
    double candidate = constValue.doubleValue();
    if (Double.isNaN(candidate) || Double.isInfinite(candidate)) {
        return;
    }
    for (BadConstant badConstant : badConstants) {
        int priority = getPriority(badConstant, constValue, candidate);
        if (getNextOpcode() == Const.FASTORE || getNextOpcode() == Const.DASTORE) {
            priority++;
        }
        if (priority < IGNORE_PRIORITY) {
            lastPriority = priority;
            lastBug = new BugInstance(this, "CNT_ROUGH_CONSTANT_VALUE", priority).addClassAndMethod(this)
                    .addString(constValue.toString()).addString(badConstant.replacement);
            bugAccumulator.accumulateBug(lastBug, this);
            return;
        }
    }
}
 
Example #9
Source File: InefficientIndexOf.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (seen == Const.INVOKEVIRTUAL && stack.getStackDepth() > 0 && "java/lang/String".equals(getClassConstantOperand())) {

        boolean lastIndexOf = "lastIndexOf".equals(getNameConstantOperand());
        if (lastIndexOf || "indexOf".equals(getNameConstantOperand())) {

            int stackOff = -1;
            if ("(Ljava/lang/String;)I".equals(getSigConstantOperand())) { // sig: String
                stackOff = 0;
            } else if ("(Ljava/lang/String;I)I".equals(getSigConstantOperand())) { // sig: String, int
                stackOff = 1;
            }
            if (stackOff > -1) {
                OpcodeStack.Item item = stack.getStackItem(stackOff);
                Object o = item.getConstant();
                if (o != null && ((String) o).length() == 1) {
                    bugReporter.reportBug(new BugInstance(this, lastIndexOf ? "IIO_INEFFICIENT_LAST_INDEX_OF" : "IIO_INEFFICIENT_INDEX_OF",
                            LOW_PRIORITY).addClassAndMethod(this)
                                    .describe(StringAnnotation.STRING_MESSAGE).addCalledMethod(this).addSourceLine(this));
                }
            }
        }
    }
}
 
Example #10
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitANEWARRAY(final ANEWARRAY o) {
    indexValid(o, o.getIndex());
    final Constant c = constantPoolGen.getConstant(o.getIndex());
    if (!    (c instanceof ConstantClass)) {
        constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'.");
    }
    final Type t = o.getType(constantPoolGen);
    if (t instanceof ArrayType) {
        final int dimensions = ((ArrayType) t).getDimensions();
        if (dimensions > Const.MAX_ARRAY_DIMENSIONS) {
            constraintViolated(o,
                "Not allowed to create an array with more than "+ Const.MAX_ARRAY_DIMENSIONS + " dimensions;"+
                " actual: " + dimensions);
        }
    }
}
 
Example #11
Source File: SynchronizationOnSharedBuiltinConstant.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean newlyConstructedObject(OpcodeStack.Item item) {
    XMethod method = item.getReturnValueOf();
    if (method == null) {
        return false;
    }
    return Const.CONSTRUCTOR_NAME.equals(method.getName());
}
 
Example #12
Source File: INVOKEINTERFACE.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public INVOKEINTERFACE(final int index, final int nargs) {
    super(Const.INVOKEINTERFACE, index);
    super.setLength(5);
    if (nargs < 1) {
        throw new ClassGenException("Number of arguments must be > 0 " + nargs);
    }
    this.nargs = nargs;
}
 
Example #13
Source File: TestArrayAccess03Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private void createMethod_0() {
  final InstructionList il = new InstructionList();
  final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  }, "<init>",
          TEST_PACKAGE+".TestArrayAccess03", 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 #14
Source File: LocalVariableGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a local variable that with index `index'. Note that double and long
 * variables need two indexs. Index indices have to be provided by the user.
 *
 * @param index index of local variable
 * @param name its name
 * @param type its type
 * @param start from where the instruction is valid (null means from the start)
 * @param end until where the instruction is valid (null means to the end)
 */
public LocalVariableGen(final int index, final String name, final Type type, final InstructionHandle start,
        final InstructionHandle end) {
    if ((index < 0) || (index > Const.MAX_SHORT)) {
        throw new ClassGenException("Invalid index index: " + index);
    }
    this.name = name;
    this.type = type;
    this.index = index;
    setStart(start);
    setEnd(end);
    this.origIndex = index;
    this.liveToEnd = end == null;
}
 
Example #15
Source File: ConstantValue.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @return String representation of constant value.
 */
@Override
public String toString() {
    Constant c = super.getConstantPool().getConstant(constantValueIndex);
    String buf;
    int i;
    // Print constant to string depending on its type
    switch (c.getTag()) {
        case Const.CONSTANT_Long:
            buf = String.valueOf(((ConstantLong) c).getBytes());
            break;
        case Const.CONSTANT_Float:
            buf = String.valueOf(((ConstantFloat) c).getBytes());
            break;
        case Const.CONSTANT_Double:
            buf = String.valueOf(((ConstantDouble) c).getBytes());
            break;
        case Const.CONSTANT_Integer:
            buf = String.valueOf(((ConstantInteger) c).getBytes());
            break;
        case Const.CONSTANT_String:
            i = ((ConstantString) c).getStringIndex();
            c = super.getConstantPool().getConstant(i, Const.CONSTANT_Utf8);
            buf = "\"" + Utility.convertString(((ConstantUtf8) c).getBytes()) + "\"";
            break;
        default:
            throw new IllegalStateException("Type of ConstValue invalid: " + c);
    }
    return buf;
}
 
Example #16
Source File: FindFloatMath.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    switch (seen) {
    case Const.FMUL:
    case Const.FDIV:
        if (getFullyQualifiedMethodName().indexOf("float") == -1 && getFullyQualifiedMethodName().indexOf("Float") == -1
                && getFullyQualifiedMethodName().indexOf("FLOAT") == -1) {
            bugReporter.reportBug(new BugInstance(this, "FL_MATH_USING_FLOAT_PRECISION", LOW_PRIORITY)
                    .addClassAndMethod(this).addSourceLine(this));
        }
        break;
    case Const.FCMPG:
    case Const.FCMPL:
        break;
    case Const.FADD:
    case Const.FSUB:
    case Const.FREM:
        if (getFullyQualifiedMethodName().indexOf("float") == -1 && getFullyQualifiedMethodName().indexOf("Float") == -1
                && getFullyQualifiedMethodName().indexOf("FLOAT") == -1) {
            bugReporter.reportBug(new BugInstance(this, "FL_MATH_USING_FLOAT_PRECISION", NORMAL_PRIORITY).addClassAndMethod(
                    this).addSourceLine(this));
        }
        break;
    default:
        break;
    }
}
 
Example #17
Source File: DismantleBytecode.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressFBWarnings("ES_COMPARING_STRINGS_WITH_EQ")
public MethodDescriptor getMethodDescriptorOperand() {
    if (nameConstantOperand == NOT_AVAILABLE || classConstantOperand == NOT_AVAILABLE) {
        throw new IllegalStateException("getMethodDescriptorOperand called but value not available");
    }

    if (referencedMethod == null) {
        referencedMethod = DescriptorFactory.instance().getMethodDescriptor(classConstantOperand, nameConstantOperand,
                sigConstantOperand, opcode == Const.INVOKESTATIC);
    }
    return referencedMethod;
}
 
Example #18
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static boolean isVoidConstructor(JavaClass clazz, Method m) {
    String outerClassSignature = getSignatureOfOuterClass(clazz);
    if (outerClassSignature == null) {
        outerClassSignature = "";
    }
    return Const.CONSTRUCTOR_NAME.equals(m.getName()) && m.getSignature().equals("(" + outerClassSignature + ")V");
}
 
Example #19
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstantMethodref(final ConstantMethodref obj) {
    if (obj.getTag() != Const.CONSTANT_Methodref) {
        throw new ClassConstraintException("Wrong constant tag in '"+tostring(obj)+"'.");
    }
    checkIndex(obj, obj.getClassIndex(), CONST_Class);
    checkIndex(obj, obj.getNameAndTypeIndex(), CONST_NameAndType);
}
 
Example #20
Source File: UnnecessaryMath.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    // Don't complain about unnecessary math calls in class initializers,
    // since they may be there to improve readability.
    if (Const.STATIC_INITIALIZER_NAME.equals(getMethod().getName())) {
        return;
    }

    state = SEEN_NOTHING;
    super.visit(obj);
}
 
Example #21
Source File: NoteDirectlyRelevantTypeQualifiers.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    switch (seen) {
    case Const.INVOKEINTERFACE:
    case Const.INVOKEVIRTUAL:
    case Const.INVOKESTATIC:
    case Const.INVOKESPECIAL:
        // We don't need to look for method invocations
        // if Analysis.FIND_EFFECTIVE_RELEVANT_QUALIFIERS is enabled -
        // that will build an interprocedural call graph which
        // we'll use at a later point to find relevant qualifiers
        // stemming from called methods.

        if (!Analysis.FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
            XMethod m = getXMethodOperand();
            if (m != null) {
                updateApplicableAnnotations(m);
            }
        }
        break;

    case Const.GETSTATIC:
    case Const.PUTSTATIC:
    case Const.GETFIELD:
    case Const.PUTFIELD: {
        XField f = getXFieldOperand();
        if (f != null) {
            Collection<TypeQualifierAnnotation> annotations = TypeQualifierApplications.getApplicableApplications(f);
            Analysis.addKnownTypeQualifiers(applicableApplications, annotations);
        }

        break;
    }
    default:
        break;
    }
}
 
Example #22
Source File: FindComparatorProblems.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (getStack().getStackDepth() == 0) {
        this.lastEmptyStackPC = getPC();
    }
    if ((seen == Const.DCMPG || seen == Const.DCMPL || seen == Const.FCMPL || seen == Const.FCMPG) && getStack().getStackDepth() == 2) {
        int[] startEnd = new int[] { this.lastEmptyStackPC, getPC() };
        for (Iterator<int[]> iterator = twoDoublesInStack.iterator(); iterator.hasNext();) {
            int[] oldStartEnd = iterator.next();
            if (codeEquals(oldStartEnd, startEnd)) {
                Item item1 = getStack().getStackItem(0);
                Item item2 = getStack().getStackItem(1);
                accumulator.accumulateBug(
                        new BugInstance("CO_COMPARETO_INCORRECT_FLOATING", NORMAL_PRIORITY).addClassAndMethod(this)
                                .addType(item1.getSignature())
                                .addMethod(item1.getSignature().equals("D") ? DOUBLE_DESCRIPTOR : FLOAT_DESCRIPTOR).describe(
                                        MethodAnnotation.SHOULD_CALL)
                                .addValueSource(item1, this)
                                .addValueSource(item2, this), this);
                iterator.remove();
                return;
            }
        }
        twoDoublesInStack.add(startEnd);
    }
    if (seen == Const.IRETURN) {
        OpcodeStack.Item top = stack.getStackItem(0);
        Object o = top.getConstant();
        if (o instanceof Integer && ((Integer) o).intValue() == Integer.MIN_VALUE) {
            accumulator.accumulateBug(
                    new BugInstance(this, "CO_COMPARETO_RESULTS_MIN_VALUE", NORMAL_PRIORITY).addClassAndMethod(this), this);
        }
    }
}
 
Example #23
Source File: TestReturn03Creator.java    From commons-bcel with 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 #24
Source File: ModulePackages.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @return string array of package names
 */
public String[] getPackageNames() {
    final String[] names = new String[packageIndexTable.length];
    for (int i = 0; i < packageIndexTable.length; i++) {
        names[i] = super.getConstantPool().getConstantString(packageIndexTable[i],
                Const.CONSTANT_Package).replace('/', '.');
    }
    return names;
}
 
Example #25
Source File: FindHEmismatch.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Field obj) {
    int accessFlags = obj.getAccessFlags();
    if ((accessFlags & Const.ACC_STATIC) != 0) {
        return;
    }
    if (!obj.getName().startsWith("this$") && !BCELUtil.isSynthetic(obj) && !obj.isTransient()) {
        hasFields = true;
    }
}
 
Example #26
Source File: ConstantUtf8.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * @param value Data
 */
public ConstantUtf8(final String value) {
    super(Const.CONSTANT_Utf8);
    if (value == null) {
        throw new IllegalArgumentException("Value must not be null.");
    }
    this.value = value;
    created++;
}
 
Example #27
Source File: InstantiateStaticClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean isStaticOnlyClass(XClass xClass) {

        if (xClass.getInterfaceDescriptorList().length > 0) {
            return false;
        }
        ClassDescriptor superclassDescriptor = xClass.getSuperclassDescriptor();
        if (superclassDescriptor == null) {
            return false;
        }
        String superClassName = superclassDescriptor.getClassName();
        if (!"java/lang/Object".equals(superClassName)) {
            return false;
        }
        int staticCount = 0;

        List<? extends XMethod> methods = xClass.getXMethods();
        for (XMethod m : methods) {
            // !m.isSynthetic(): bug #1282: No warning should be generated if only static methods are synthetic
            if (m.isStatic() && !m.isSynthetic()) {
                staticCount++;
            } else if (!Const.CONSTRUCTOR_NAME.equals(m.getName()) || !"()V".equals(m.getSignature())) {
                return false;
            }
        }

        List<? extends XField> fields = xClass.getXFields();
        for (XField f : fields) {
            if (f.isStatic()) {
                staticCount++;
            } else if (!f.isPrivate()) {
                return false;
            }
        }

        return staticCount != 0;
    }
 
Example #28
Source File: MethodAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String getJavaSourceMethodName() {
    if (Const.STATIC_INITIALIZER_NAME.equals(methodName)) {
        return "<static initializer for " + getSimpleClassName() + ">";
    }

    if (Const.CONSTRUCTOR_NAME.equals(methodName)) {
        return getSimpleClassName();
    }
    return methodName;
}
 
Example #29
Source File: AppendingToAnObjectOutputStream.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (seen != Const.INVOKESPECIAL) {
        sawOpenInAppendMode = false;
        return;
    }
    String calledClassName = getClassConstantOperand();
    String calledMethodName = getNameConstantOperand();
    String calledMethodSig = getSigConstantOperand();
    if (!sawOpenInAppendMode) {
        if ("java/io/ObjectOutputStream".equals(calledClassName) && Const.CONSTRUCTOR_NAME.equals(calledMethodName)
                && "(Ljava/io/OutputStream;)V".equals(calledMethodSig)
                && stack.getStackItem(0).getSpecialKind() == OpcodeStack.Item.FILE_OPENED_IN_APPEND_MODE) {
            bugReporter.reportBug(new BugInstance(this, "IO_APPENDING_TO_OBJECT_OUTPUT_STREAM", Priorities.HIGH_PRIORITY)
                    .addClassAndMethod(this).addSourceLine(this));
        }
        return;
    }
    if ("java/io/FileOutputStream".equals(calledClassName) && Const.CONSTRUCTOR_NAME.equals(calledMethodName)
            && ("(Ljava/io/File;Z)V".equals(calledMethodSig) || "(Ljava/lang/String;Z)V".equals(calledMethodSig))) {
        OpcodeStack.Item item = stack.getStackItem(0);
        Object value = item.getConstant();
        sawOpenInAppendMode = value instanceof Integer && ((Integer) value).intValue() == 1;
    } else if ("java/io/BufferedOutputStream".equals(calledClassName) && Const.CONSTRUCTOR_NAME.equals(calledMethodName)
            && "(Ljava/io/OutputStream;)V".equals(calledMethodSig)) {
        // do nothing

    } else if ("java/io/ObjectOutputStream".equals(calledClassName) && Const.CONSTRUCTOR_NAME.equals(calledMethodName)
            && "(Ljava/io/OutputStream;)V".equals(calledMethodSig)) {
        bugReporter.reportBug(new BugInstance(this, "IO_APPENDING_TO_OBJECT_OUTPUT_STREAM", Priorities.HIGH_PRIORITY)
                .addClassAndMethod(this).addSourceLine(this));
        sawOpenInAppendMode = false;
    } else {
        sawOpenInAppendMode = false;
    }

}
 
Example #30
Source File: CloneIdiom.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (seen == Const.INVOKESPECIAL && "clone".equals(getNameConstantOperand()) && getSigConstantOperand().startsWith("()")) {
        /*
         * System.out.println("Saw call to " + nameConstant + ":" +
         * sigConstant + " in " + betterMethodName);
         */
        invokesSuperClone = true;
    }
}