- FindBugs ( )
- Analysis for
-
-
-
-
-
-
- -
-
|
-
-
-
-
- - FindBugs Change Log, Version 2.0.0 -- -Changes since version 1.3.8-
Changes since version 1.3.8 -
Changes since version 1.3.7 -
Changes since version 1.3.6 -
Changes since version 1.3.5 -
Changes since version 1.3.4 -
Changes since version 1.3.3 - -
Changes since version 1.3.2 - -
Changes since version 1.3.1 - -
Changes since version 1.3.0 -
Changes since version 1.2.1 -
Changes since version 1.2.0 -
Changes since version 1.1.3 -
- Changes since version 1.1.2: - -
- Changes since version 1.1.1: - -
- Changes since version 1.1.0: - -
- Changes since version 1.0.0: - - -
- Changes since version 0.9.7: - - -
- Changes since version 0.9.6: - - -
- Changes since version 0.9.5: - - -
- Changes since version 0.9.4: - -
- Changes since version 0.9.3: - -
- Note: there was no version 0.9.2 - - -- Changes since version 0.9.1: - -
- Changes since version 0.9.0: - -
- Changes since version 0.8.8: - -
- Changes since version 0.8.7: - - -
- Changes since version 0.8.6: - - -
- Changes since version 0.8.5: - - -
- Changes since version 0.8.4: - - -
- Changes since version 0.8.3: - -
- Changes since version 0.8.2: - -
- Changes since version 0.8.1: - -
- Changes since version 0.8.0: - - -
- Also, two contributors to the 0.8.0 release were inadvertently - left out of the credits: - - -
- Changes since version 0.7.4: - - -
- Changes since version 0.7.3: - - -
- Changes since version 0.7.2: - - -
- Changes since version 0.7.1: - - -
- Changes since version 0.7.0: - - -
- Note that the version number jumped from 0.6.6 to 0.6.9; there - were no 0.6.7 or 0.6.8 releases. - - -- Changes since version 0.6.9: - -
- Changes since version 0.6.6: - - -
- Changes since 0.6.5: - - -
- Changes since version 0.6.4: - - -
- Changes since version 0.6.3: - - -
- Changes since version 0.6.2: - - -
- Changes since version 0.6.1: - - -
- Changes since version 0.6.0: - - -
- Changes since version 0.5.4 - - -
- Changes since version 0.5.3 - - -
- Changes since version 0.5.2 - - -
- Changes since version 0.5.1: - -
- Changes since version 0.5.0: - -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-FindBugs FAQ- -This document contains answers to frequently asked questions about -FindBugs. If you just want general -information about FindBugs, have a look at the -fact sheet and the -manual. - - Contents-
Q1: I'm getting java.lang.UnsupportedClassVersionError when I try to run FindBugs- -FindBugs requires JRE 1.5.0 or later to run. If you use an earlier version, -you will see an exception error message similar to the following: - -Exception in thread "main" java.lang.UnsupportedClassVersionError: -edu/umd/cs/findbugs/gui/FindBugsFrame (Unsupported major.minor version 48.0) --The solution is to upgrade to JRE 1.5.0 or later. - - Q2: When I click the "Find Bugs!" button, I get a NoSuchMethodError or VerifyError- -The symptom of this bug is that when you start the FindBugs analysis, -you see an exception similar to the following: - -java.lang.NoSuchMethodError: org.apache.bcel.Repository.setRepository(Lorg/apache/bcel/util/Repository;)V - at edu.umd.cs.findbugs.FindBugs.clearRepository(FindBugs.java:483) - ... -- -or - - -java.lang.VerifyError: Cannot inherit from final class - at java.lang.ClassLoader.defineClass0(Native Method) - at java.lang.ClassLoader.defineClass(ClassLoader.java:537) - ... -- - The problem here is that the wrong version of the
-Apache BCEL
-library is being found. FindBugs requires its own
-version of BCEL, which normally will be used automatically
-when you invoke the
In all of these cases, you should be able to run FindBugs -by either removing the offending version of BCEL from your JRE, -or installing a clean JRE or JDK and using that to run FindBugs. - - Many thanks to Peter Meulmeester, Michael Levi, and Thomas Klaeger -for providing information on this problem. - - Q3: FindBugs is running out of memory, or is taking a long time to finish- - In general, FindBugs requires lots of memory and a relatively
-fast CPU. For large applications, 512M or more of heap space may be
-required. By default, FindBugs allocates 256M of heap space.
-You can increase this using the Q4: What is the "auxiliary classpath"? Why should I specify it?- -Many important facts about a Java class require information about -the classes that it references. For example: -
The "auxiliary classpath" is a list of Jar files, directories, and -class files containing classes that are used by the code you -want FindBugs to analyze, but should not themselves be analyzed -by FindBugs. - - If FindBugs doesn't have complete information about referenced classes, -it will not be able to produce results that are as accurate as possible. -For example, having a complete repository of referenced classes allows -FindBugs to prune control flow information so it can concentrate on -paths through methods that are most likely to be feasible at runtime. -Also, some bug detectors (such as the suspicious reference comparison detector) -rely on being able to perform type inference, which requires complete -type hierarchy information. - - For these reasons, we strongly recommend that you completely specify
-the auxiliary classpath when you run FindBugs. You can do this
-by using the If FindBugs cannot find a class referenced by your application, it -will print out a message when the analysis completes, specifying the -classes that were missing. You should modify the auxiliary classpath -to specify how to find the missing classes, and then run FindBugs again. - - Q5: The Eclipse plugin doesn't load- -The symptom of this problem is that Eclipse fails to load -the FindBugs UI plugin with the message: - -Plug-in "edu.umd.cs.findbugs.plugin.eclipse" was disabled due to missing or disabled -prerequisite plug-in "org.eclipse.ui.ide" -- - The reason for this problem is that the Eclipse -plugin distributed with FindBugs -does not work with 2.x versions of Eclipse. -Please use Eclipse version 3.3 (June 2007) or newer. - - Q6: I'm getting a lot of false "OS" and "ODR" warnings- - By default, FindBugs assumes that any method invocation can
-throw an unchecked runtime exception. As a result,
-it may assume that an unchecked exception thrown out of the
-method could bypass a call to a You can use the Q7: The Eclipse plugin loads, but doesn't work correctly- -In versions 0.0.6 and 0.0.7 of the FindBugs Eclipse plugin, -which correspond to the 0.7.4 and 0.8.0 releases, -bugs in the experimental SwitchFallthrough detector can prevent -FindBugs from running properly within Eclipse. - - To work around the problem, make sure that SwitchFallthrough -is disabled in the FindBugs Properties of your project. -Right click on your project, and choose "Properties". -In the Properties dialog, choose "FindBugs", -and disable the checkbox next to SwitchFallthrough. - - Another common problem with the Eclipse plugin is that -the FindBugs warnings do not appear in the "Problems" view. -Make sure that FindBugs warnings are enabled in the filters -for this view. The Filters menu is accessible by -clicking on the icon that looks like this: - --Make sure the "FindBugs Problem" checkbox is enabled. - - Q8: Where is the Maven plugin for FindBugs?- --The Maven Plugin for FindBugs -may be found here. -Please note that the Maven plugin is not maintained by the FindBugs developers, -so we can't answer questions about it. - - -Q9: Where is the NetBeans plugin for FindBugs?- -We recommend SQE: Software Quality Environment -which bundles FindBugs, PMD and CheckStyle. Use the following -update site: -http://deadlock.netbeans.org/hudson/job/sqe/lastStableBuild/artifact/build/full-sqe-updatecenter/updates.xmla> - Pease note that the SQE plugin is not maintained by the FindBugs developers, -so we can't answer questions about it. - - - -- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-FindBugs Bug Descriptions (Unabridged)-This document lists all of the bug patterns reported by the -latest development version of -FindBugs. Note that this may include -bug patterns not available in any released version of FindBugs, -as well as bug patterns that are not enabled by default. - Summary-Descriptions-AM: Creates an empty jar file entry (AM_CREATES_EMPTY_JAR_FILE_ENTRY)- - -The code calls AM: Creates an empty zip file entry (AM_CREATES_EMPTY_ZIP_FILE_ENTRY)- - -The code calls BC: Equals method should not assume anything about the type of its argument (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)- - -
-The BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK)- - -This method compares an expression such as - ((event.detail & SWT.SELECTED) > 0). -Using bit arithmetic and then comparing with the greater than operator can -lead to unexpected results (of course depending on the value of -SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate -for a bug. Even when SWT.SELECTED is not negative, it seems good practice -to use '!= 0' instead of '> 0'. - - -Boris Bokowski - - - -CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)- - -- Class implements Cloneable but does not define or - use the clone method. - - -CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL)- - -This non-final class defines a clone() method that does not call super.clone(). -If this class ("A") is extended by a subclass ("B"), -and the subclass B calls super.clone(), then it is likely that -B's clone() method will return an object of type A, -which violates the standard contract for clone(). - -If all clone() methods call super.clone(), then they are guaranteed -to use Object.clone(), which always returns an object of the correct type. - - -CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)- - -This class defines a clone() method but the class doesn't implement Cloneable. -There are some situations in which this is OK (e.g., you want to control how subclasses -can clone themselves), but just make sure that this is what you intended. - - - -Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)- - - This class defines a covariant version of Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)- - - This class defines a covariant version of DE: Method might drop exception (DE_MIGHT_DROP)- - -This method might drop an exception. In general, exceptions - should be handled or reported in some way, or they should be thrown - out of the method. - - -DE: Method might ignore exception (DE_MIGHT_IGNORE)- - -This method might ignore an exception. In general, exceptions - should be handled or reported in some way, or they should be thrown - out of the method. - - -DMI: Adding elements of an entry set may fail due to reuse of Entry objects (DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS)- - -The entrySet() method is allowed to return a view of the - underlying Map in which a single Entry object is reused and returned - during the iteration. As of Java 1.6, both IdentityHashMap - and EnumMap did so. When iterating through such a Map, - the Entry value is only valid until you advance to the next iteration. - If, for example, you try to pass such an entrySet to an addAll method, - things will go badly wrong. - - - -DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)- - -This code creates a java.util.Random object, uses it to generate one random number, and then discards -the Random object. This produces mediocre quality random numbers and is inefficient. -If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number -is required invoke a method on the existing Random object to obtain it. - - -If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random -number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead -(and avoid allocating a new SecureRandom for each random number needed). - - - -DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)- - - If you want to remove all elements from a collection Dm: Method invokes System.exit(...) (DM_EXIT)- - -Invoking System.exit shuts down the entire Java virtual machine. This - should only been done when it is appropriate. Such calls make it - hard or impossible for your code to be invoked by other code. - Consider throwing a RuntimeException instead. - - -Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)- - -Never call System.runFinalizersOnExit -or Runtime.runFinalizersOnExit for any reason: they are among the most -dangerous methods in the Java libraries. -- Joshua Bloch - - -ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)- - -This code compares a ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)- - -This code compares Eq: Abstract class defines covariant equals() method (EQ_ABSTRACT_SELF)- - - This class defines a covariant version of Eq: Equals checks for incompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)- - -This equals method is checking to see if the argument is some incompatible type -(i.e., a class that is neither a supertype nor subtype of the class that defines -the equals method). For example, the Foo class might have an equals method -that looks like: - -
This is considered bad practice, as it makes it very hard to implement an equals method that -is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. - - - -Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)- - - This class defines a From the JavaDoc for the compareTo method in the Comparable interface: -
-It is strongly recommended, but not strictly required that
-
-
-Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)- - - This class has an equals method that will be broken if it is inherited by subclasses.
-It compares a class literal with the class of the argument (e.g., in class Eq: Covariant equals() method defined (EQ_SELF_NO_OBJECT)- - - This class defines a covariant version of FI: Empty finalizer should be deleted (FI_EMPTY)- - - Empty FI: Explicit invocation of finalizer (FI_EXPLICIT_INVOCATION)- - - This method contains an explicit invocation of the If a connected set of objects beings finalizable, then the VM will invoke the -finalize method on all the finalizable object, possibly at the same time in different threads. -Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize -on objects referenced by X, because they may already be getting finalized in a separate thread. - - - FI: Finalizer nulls fields (FI_FINALIZER_NULLS_FIELDS)- - -This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, - and the object is going to be garbage collected anyway. - - - FI: Finalizer only nulls fields (FI_FINALIZER_ONLY_NULLS_FIELDS)- - -This finalizer does nothing except null out fields. This is completely pointless, and requires that -the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize -method. - - - FI: Finalizer does not call superclass finalizer (FI_MISSING_SUPER_CALL)- - - This FI: Finalizer nullifies superclass finalizer (FI_NULLIFY_SUPER)- - - This empty FI: Finalizer does nothing but call superclass finalizer (FI_USELESS)- - - The only thing this FS: Format string should use %n rather than \n (VA_FORMAT_STRING_USES_NEWLINE)- - --This format string include a newline character (\n). In format strings, it is generally - preferable better to use %n, which will produce the platform-specific line separator. - - - -GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)- - -This call to a generic collection method passes an argument - while compile type Object where a specific type from - the generic type parameters is expected. - Thus, neither the standard Java type system nor static analysis - can provide useful information on whether the - object being passed as a parameter is of an appropriate type. - - - -HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)- - - This class overrides HE: Class defines equals() and uses Object.hashCode() (HE_EQUALS_USE_HASHCODE)- - - This class overrides If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
-the recommended public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
-
-HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)- - - This class defines a HE: Class defines hashCode() and uses Object.equals() (HE_HASHCODE_USE_OBJECT_EQUALS)- - - This class defines a If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
-the recommended public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
-
-HE: Class inherits equals() and uses Object.hashCode() (HE_INHERITS_EQUALS_USE_HASHCODE)- - - This class inherits If you don't want to define a hashCode method, and/or don't
- believe the object will ever be put into a HashMap/Hashtable,
- define the IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)- - - During the initialization of a class, the class makes an active use of a subclass.
-That subclass will not yet be initialized at the time of this use.
-For example, in the following code,
-public class CircularClassInitialization {
- static class InnerClassSingleton extends CircularClassInitialization {
- static InnerClassSingleton singleton = new InnerClassSingleton();
- }
-
- static CircularClassInitialization foo = InnerClassSingleton.singleton;
-}
-
-
-
-
-IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)- - -IllegalMonitorStateException is generally only - thrown in case of a design flaw in your code (calling wait or - notify on an object you do not hold a lock on). - - -ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)- - -This class allocates an object that is based on a class that only supplies static methods. This object -does not need to be created, just access the static methods directly using the class name as a qualifier. - - -It: Iterator next() method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT)- - - This class implements the J2EE: Store of non serializable object into HttpSession (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)- - --This code seems to be storing a non-serializable object into an HttpSession. -If this session is passivated or migrated, an error will result. - - - -JCIP: Fields of immutable classes should be final (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)- - -The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require -that all fields are final. - . - - -NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL)- - -- A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. - This method can be invoked as though it returned a value of type boolean, and - the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, - this will result in a NullPointerException. - - - -NP: Clone method may return null (NP_CLONE_COULD_RETURN_NULL)- - -- This clone method seems to return null in some circumstances, but clone is never - allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError - instead. - - - -NP: equals() method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)- - -- This implementation of equals(Object) violates the contract defined - by java.lang.Object.equals() because it does not check for null - being passed as the argument. All equals() methods should return - false if passed a null value. - - - -NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL)- - -- This toString method seems to return null in some circumstances. A liberal reading of the - spec could be interpreted as allowing this, but it is probably a bad idea and could cause - other code to break. Return the empty string or some other appropriate string rather than null. - - - -Nm: Class names should start with an upper case letter (NM_CLASS_NAMING_CONVENTION)- - -Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). - - - -Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION)- - -This class is not derived from another exception, but ends with 'Exception'. This will -be confusing to users of this class. - - -Nm: Confusing method names (NM_CONFUSING)- - -The referenced methods have names that differ only by capitalization. - - -Nm: Field names should start with a lower case letter (NM_FIELD_NAMING_CONVENTION)- - --Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. - - - -Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)- - -The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed -in order to compile it in later versions of Java. - - - -Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)- - -This identifier is used as a keyword in later versions of Java. This code, and -any code that references this API, -will need to be changed in order to compile it in later versions of Java. - - - -Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION)- - --Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. - - - -Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE)- - - This class/interface has a simple name that is identical to that of an implemented/extended interface, except
-that the interface is in a different package (e.g., Nm: Class names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)- - - This class has a simple name that is identical to that of its superclass, except
-that its superclass is in a different package (e.g., Nm: Very confusing method names (but perhaps intentional) (NM_VERY_CONFUSING_INTENTIONAL)- - -The referenced methods have names that differ only by capitalization. -This is very confusing because if the capitalization were -identical then one of the methods would override the other. From the existence of other methods, it -seems that the existence of both of these methods is intentional, but is sure is confusing. -You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs. - - - -Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL)- - -The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match -the type of the corresponding parameter in the superclass. For example, if you have: - -
-
-
-The In this case, the subclass does define a method with a signature identical to the method in the superclass, -so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider -removing or deprecating the method with the similar but not identical signature. - - - -ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE)- - -The method creates a database resource (such as a database connection -or row set), does not assign it to any -fields, pass it to other methods, or return it, and does not appear to close -the object on all paths out of the method. Failure to -close database resources on all paths out of a method may -result in poor performance, and could cause the application to -have problems communicating with the database. - - - -ODR: Method may fail to close database resource on exception (ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)- - -The method creates a database resource (such as a database connection -or row set), does not assign it to any -fields, pass it to other methods, or return it, and does not appear to close -the object on all exception paths out of the method. Failure to -close database resources on all paths out of a method may -result in poor performance, and could cause the application to -have problems communicating with the database. - - -OS: Method may fail to close stream (OS_OPEN_STREAM)- - - The method creates an IO stream object, does not assign it to any
-fields, pass it to other methods that might close it,
-or return it, and does not appear to close
-the stream on all paths out of the method. This may result in
-a file descriptor leak. It is generally a good
-idea to use a OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)- - - The method creates an IO stream object, does not assign it to any
-fields, pass it to other methods, or return it, and does not appear to close
-it on all possible exception paths out of the method.
-This may result in a file descriptor leak. It is generally a good
-idea to use a PZ: Don't reuse entry objects in iterators (PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS)- - - The entrySet() method is allowed to return a view of the
- underlying Map in which an Iterator and Map.Entry. This clever
- idea was used in several Map implementations, but introduces the possibility
- of nasty coding mistakes. If a map RC: Suspicious reference comparison to constant (RC_REF_COMPARISON_BAD_PRACTICE)- - -This method compares a reference value to a constant using the == or != operator, -where the correct way to compare instances of this type is generally -with the equals() method. -It is possible to create distinct instances that are equal but do not compare as == since -they are different objects. -Examples of classes which should generally -not be compared by reference are java.lang.Integer, java.lang.Float, etc. - - -RC: Suspicious reference comparison of Boolean values (RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN)- - - This method compares two Boolean values using the == or != operator.
-Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE),
-but it is possible to create other Boolean objects using the RR: Method ignores results of InputStream.read() (RR_NOT_CHECKED)- - - This method ignores the return value of one of the variants of
- RR: Method ignores results of InputStream.skip() (SR_NOT_CHECKED)- - - This method ignores the return value of
- RV: Negating the result of compareTo()/compare() (RV_NEGATING_RESULT_OF_COMPARETO)- - -This code negatives the return value of a compareTo or compare method. -This is a questionable or bad programming practice, since if the return -value is Integer.MIN_VALUE, negating the return value won't -negate the sign of the result. You can achieve the same intended result -by reversing the order of the operands rather than by negating the results. - - - -RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)- - - This method returns a value that is not checked. The return value should be checked
-since it can indicate an unusual or unexpected function execution. For
-example, the SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)- - -The class's static initializer creates an instance of the class -before all of the static final fields are assigned. - - -SW: Certain swing methods needs to be invoked in Swing thread (SW_SWING_METHODS_INVOKED_IN_SWING_THREAD)- - -(From JDC Tech Tip): The Swing methods -show(), setVisible(), and pack() will create the associated peer for the frame. -With the creation of the peer, the system creates the event dispatch thread. -This makes things problematic because the event dispatch thread could be notifying -listeners while pack and validate are still processing. This situation could result in -two threads going through the Swing component-based GUI -- it's a serious flaw that -could result in deadlocks or other related threading issues. A pack call causes -components to be realized. As they are being realized (that is, not necessarily -visible), they could trigger listener notification on the event dispatch thread. - - - -Se: Non-transient non-serializable instance field in serializable class (SE_BAD_FIELD)- - - This Serializable class defines a non-primitive instance field which is neither transient,
-Serializable, or Se: Non-serializable class has a serializable inner class (SE_BAD_FIELD_INNER_CLASS)- - -This Serializable class is an inner class of a non-serializable class. -Thus, attempts to serialize it will also attempt to associate instance of the outer -class with which it is associated, leading to a runtime error. - -If possible, making the inner class a static inner class should solve the -problem. Making the outer class serializable might also work, but that would -mean serializing an instance of the inner class would always also serialize the instance -of the outer class, which it often not what you really want. - - - Se: Non-serializable value stored into instance field of a serializable class (SE_BAD_FIELD_STORE)- - -A non-serializable value is stored into a non-transient field -of a serializable class. - - -Se: Comparator doesn't implement Serializable (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)- - - This class implements the Se: Serializable inner class (SE_INNER_CLASS)- - -This Serializable class is an inner class. Any attempt to serialize -it will also serialize the associated outer instance. The outer instance is serializable, -so this won't fail, but it might serialize a lot more data than intended. -If possible, making the inner class a static inner class (also known as a nested class) should solve the -problem. - - - Se: serialVersionUID isn't final (SE_NONFINAL_SERIALVERSIONID)- - - This class defines a Se: serialVersionUID isn't long (SE_NONLONG_SERIALVERSIONID)- - - This class defines a Se: serialVersionUID isn't static (SE_NONSTATIC_SERIALVERSIONID)- - - This class defines a Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR)- - - This class implements the Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)- - - This class implements the Se: The readResolve method must be declared with a return type of Object. (SE_READ_RESOLVE_MUST_RETURN_OBJECT)- - -In order for the readResolve method to be recognized by the serialization -mechanism, it must be declared to have a return type of Object. - - - -Se: Transient field that isn't set by deserialization. (SE_TRANSIENT_FIELD_NOT_RESTORED)- - -This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any -deserialized instance of the class. - - - -SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID)- - - This class implements the UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)- - -Calling BC: Impossible cast (BC_IMPOSSIBLE_CAST)- - --This cast will always throw a ClassCastException. -FindBugs tracks type information from instanceof checks, -and also uses more precise information about the types -of values returned from methods and loaded from fields. -Thus, it may have more precise information that just -the declared type of a variable, and can use this to determine -that a cast will always throw an exception at runtime. - - - - -BC: Impossible downcast (BC_IMPOSSIBLE_DOWNCAST)- - --This cast will always throw a ClassCastException. -The analysis believes it knows -the precise type of the value being cast, and the attempt to -downcast it to a subtype will always fail by throwing a ClassCastException. - - - -BC: Impossible downcast of toArray() result (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)- - -
-This code is casting the result of calling
-String[] getAsArray(Collection<String> c) {
- return (String[]) c.toArray();
- }
-
-This will usually fail by throwing a ClassCastException. The The correct way to do get an array of a specific type from a collection is to use
- There is one common/known exception exception to this. The BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF)- - --This instanceof test will always return false. Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. - - - -BIT: Bitwise add of signed byte value (BIT_ADD_OF_SIGNED_BYTE)- - - Adds a byte value and a value which is known to have the 8 lower bits clear.
-Values loaded from a byte array are sign extended to 32 bits
-before any any bitwise operations are performed on the value.
-Thus, if In particular, the following code for packing a byte array into an int is badly wrong: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) + b[i]); -- - The following idiom will work instead: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) + (b[i] & 0xff)); -- - - - BIT: Incompatible bit masks (BIT_AND)- - -This method compares an expression of the form (e & C) to D, -which will always compare unequal -due to the specific values of constants C and D. -This may indicate a logic error or typo. - - -BIT: Check to see if ((...) & 0) == 0 (BIT_AND_ZZ)- - -This method compares an expression of the form (e & 0) to 0, -which will always compare equal. -This may indicate a logic error or typo. - - -BIT: Incompatible bit masks (BIT_IOR)- - -This method compares an expression of the form (e | C) to D. -which will always compare unequal -due to the specific values of constants C and D. -This may indicate a logic error or typo. - -Typically, this bug occurs because the code wants to perform -a membership test in a bit set, but uses the bitwise OR -operator ("|") instead of bitwise AND ("&"). - - -BIT: Bitwise OR of signed byte value (BIT_IOR_OF_SIGNED_BYTE)- - - Loads a byte value (e.g., a value loaded from a byte array or returned by a method
-with return type byte) and performs a bitwise OR with
-that value. Byte values are sign extended to 32 bits
-before any any bitwise operations are performed on the value.
-Thus, if In particular, the following code for packing a byte array into an int is badly wrong: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) | b[i]); -- - The following idiom will work instead: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) | (b[i] & 0xff)); -- - - - BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT)- - -This method compares an expression such as - ((event.detail & SWT.SELECTED) > 0). -Using bit arithmetic and then comparing with the greater than operator can -lead to unexpected results (of course depending on the value of -SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate -for a bug. Even when SWT.SELECTED is not negative, it seems good practice -to use '!= 0' instead of '> 0'. - - -Boris Bokowski - - - -BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER)- - -This method overrides a method found in a parent class, where that class is an Adapter that implements -a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not -get called when the event occurs. - - -BSHIFT: 32 bit int shifted by an amount not in the range 0..31 (ICAST_BAD_SHIFT_AMOUNT)- - --The code performs shift of a 32 bit int by a constant amount outside -the range 0..31. -The effect of this is to use the lower 5 bits of the integer -value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, -and shifting by 32 bits is the same as shifting by zero bits). This probably isn't what was expected, -and it is at least confusing. - - - -Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)- - -A wrapped primitive value is unboxed and converted to another primitive type as part of the
-evaluation of a conditional ternary operator (the Co: compareTo()/compare() returns Integer.MIN_VALUE (CO_COMPARETO_RESULTS_MIN_VALUE)- - -In some situation, this compareTo or compare method returns -the constant Integer.MIN_VALUE, which is an exceptionally bad practice. - The only thing that matters about the return value of compareTo is the sign of the result. - But people will sometimes negate the return value of compareTo, expecting that this will negate - the sign of the result. And it will, except in the case where the value returned is Integer.MIN_VALUE. - So just return -1 rather than Integer.MIN_VALUE. - - - DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL)- - -
-This instruction assigns a class literal to a variable and then never uses it.
-The behavior of this differs in Java 1.4 and in Java 5.
-In Java 1.4 and earlier, a reference to See Sun's article on Java SE compatibility -for more details and examples, and suggestions on how to force class initialization in Java 5. - - - -DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT)- - -
-The code performs an increment operation (e.g., DMI: Reversed method arguments (DMI_ARGUMENTS_WRONG_ORDER)- - - The arguments to this method call seem to be in the wrong order.
-For example, a call DMI: Bad constant value for month (DMI_BAD_MONTH)- - --This code passes a constant month -value outside the expected range of 0..11 to a method. - - - -DMI: BigDecimal constructed from double that isn't represented precisely (DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE)- - --This code creates a BigDecimal from a double value that doesn't translate well to a -decimal number. -For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. -You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation -of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1). - - - - -DMI: hasNext method invokes next (DMI_CALLING_NEXT_FROM_HASNEXT)- - --The hasNext() method invokes the next() method. This is almost certainly wrong, -since the hasNext() method is not supposed to change the state of the iterator, -and the next method is supposed to change the state of the iterator. - - - -DMI: Collections should not contain themselves (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)- - - This call to a generic collection's method would only make sense if a collection contained
-itself (e.g., if DMI: D'oh! A nonsensical method invocation (DMI_DOH)- - --This partical method invocation doesn't make sense, for reasons that should be apparent from inspection. - - - - -DMI: Invocation of hashCode on an array (DMI_INVOKING_HASHCODE_ON_ARRAY)- - -
-The code invokes hashCode on an array. Calling hashCode on
-an array returns the same value as System.identityHashCode, and ingores
-the contents and length of the array. If you need a hashCode that
-depends on the contents of an array DMI: Double.longBitsToDouble invoked on an int (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)- - -The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed - as an argument. This almostly certainly is not intended and is unlikely - to give the intended result. - - - -DMI: Vacuous call to collections (DMI_VACUOUS_SELF_COLLECTION_CALL)- - - This call doesn't make sense. For any collection Dm: Can't use reflection to check for presence of annotation without runtime retention (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)- - -Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection -(e.g., by using the isAnnotationPresent method). - . - - -Dm: Futile attempt to change max pool size of ScheduledThreadPoolExecutor (DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR)- - -(Javadoc) -While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. - - - - -Dm: Creation of ScheduledThreadPoolExecutor with zero core threads (DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS)- - -(Javadoc) -A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored. - - - - -Dm: Useless/vacuous call to EasyMock method (DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD)- - -This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything. - - - - -EC: equals() used to compare array and nonarray (EC_ARRAY_AND_NONARRAY)- - --This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem -to be an array. If things being compared are of different types, they are guaranteed to be unequal -and the comparison is almost certainly an error. Even if they are both arrays, the equals method -on arrays only determines of the two arrays are the same object. -To compare the -contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). - - - -EC: Invocation of equals() on an array, which is equivalent to == (EC_BAD_ARRAY_COMPARE)- - -
-This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals
-method of Object, calling equals on an array is the same as comparing their addresses. To compare the
-contents of the arrays, use EC: equals(...) used to compare incompatible arrays (EC_INCOMPATIBLE_ARRAY_COMPARE)- - --This method invokes the .equals(Object o) to compare two arrays, but the arrays of -of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]). -They will never be equal. In addition, when equals(...) is used to compare arrays it -only checks to see if they are the same array, and ignores the contents of the arrays. - - - -EC: Call to equals(null) (EC_NULL_ARG)- - - This method calls equals(Object), passing a null value as
-the argument. According to the contract of the equals() method,
-this call should always return EC: Call to equals() comparing unrelated class and interface (EC_UNRELATED_CLASS_AND_INTERFACE)- - --This method calls equals(Object) on two references, one of which is a class -and the other an interface, where neither the class nor any of its -non-abstract subclasses implement the interface. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Call to equals() comparing different interface types (EC_UNRELATED_INTERFACES)- - -This method calls equals(Object) on two references of unrelated -interface types, where neither is a subtype of the other, -and there are no known non-abstract classes which implement both interfaces. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Call to equals() comparing different types (EC_UNRELATED_TYPES)- - -This method calls equals(Object) on two references of different -class types with no common subclasses. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Using pointer equality to compare different types (EC_UNRELATED_TYPES_USING_POINTER_EQUALITY)- - -This method uses using pointer equality to compare two references that seem to be of -different types. The result of this comparison will always be false at runtime. - - - -Eq: equals method always returns false (EQ_ALWAYS_FALSE)- - -This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means -that equals is not reflexive, one of the requirements of the equals method. -The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class
-public boolean equals(Object o) { return this == o; }
-
-
-
-
-Eq: equals method always returns true (EQ_ALWAYS_TRUE)- - -This class defines an equals method that always returns true. This is imaginative, but not very smart. -Plus, it means that the equals method is not symmetric. - - - -Eq: equals method compares class names rather than class objects (EQ_COMPARING_CLASS_NAMES)- - -This method checks to see if two objects are the same class by checking to see if the names -of their classes are equal. You can have different classes with the same name if they are loaded by -different class loaders. Just check to see if the class objects are the same. - - - -Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)- - -This class defines an enumeration, and equality on enumerations are defined -using object identity. Defining a covariant equals method for an enumeration -value is exceptionally bad practice, since it would likely result -in having two different enumeration values that compare as equals using -the covariant enum method, and as not equal when compared normally. -Don't do it. - - - -Eq: equals() method defined that doesn't override equals(Object) (EQ_OTHER_NO_OBJECT)- - - This class defines an Eq: equals() method defined that doesn't override Object.equals(Object) (EQ_OTHER_USE_OBJECT)- - - This class defines an Eq: equals method overrides equals in superclass and may not be symmetric (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)- - - This class defines an equals method that overrides an equals method in a superclass. Both equals methods
-methods use Eq: Covariant equals() method defined, Object.equals(Object) inherited (EQ_SELF_USE_OBJECT)- - - This class defines a covariant version of the FE: Doomed test for equality to NaN (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)- - -
- This code checks to see if a floating point value is equal to the special
- Not A Number value (e.g., FS: Format string placeholder incompatible with passed argument (VA_FORMAT_STRING_BAD_ARGUMENT)- - -
-The format string placeholder is incompatible with the corresponding
-argument. For example,
- The %d placeholder requires a numeric argument, but a string value is -passed instead. -A runtime exception will occur when -this statement is executed. - - - -FS: The type of a supplied argument doesn't match format specifier (VA_FORMAT_STRING_BAD_CONVERSION)- - -
-One of the arguments is uncompatible with the corresponding format string specifier.
-As a result, this will generate a runtime exception when executed.
-For example, FS: MessageFormat supplied where printf style format expected (VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED)- - --A method is called that expects a Java printf format string and a list of arguments. -However, the format string doesn't contain any format specifiers (e.g., %s) but -does contain message format elements (e.g., {0}). It is likely -that the code is supplying a MessageFormat string when a printf-style format string -is required. At runtime, all of the arguments will be ignored -and the format string will be returned exactly as provided without any formatting. - - - - -FS: More arguments are passed than are actually used in the format string (VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED)- - --A format-string method with a variable number of arguments is called, -but more arguments are passed than are actually used by the format string. -This won't cause a runtime exception, but the code may be silently omitting -information that was intended to be included in the formatted string. - - - -FS: Illegal format string (VA_FORMAT_STRING_ILLEGAL)- - --The format string is syntactically invalid, -and a runtime exception will occur when -this statement is executed. - - - -FS: Format string references missing argument (VA_FORMAT_STRING_MISSING_ARGUMENT)- - --Not enough arguments are passed to satisfy a placeholder in the format string. -A runtime exception will occur when -this statement is executed. - - - -FS: No previous argument for format string (VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT)- - --The format string specifies a relative index to request that the argument for the previous format specifier -be reused. However, there is no previous argument. -For example, - -
would throw a MissingFormatArgumentException when executed. - - - -GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)- - -This call to a generic collection method contains an argument - with an incompatible class from that of the collection's parameter - (i.e., the type of the argument is neither a supertype nor a subtype - of the corresponding generic type argument). - Therefore, it is unlikely that the collection contains any objects - that are equal to the method argument used here. - Most likely, the wrong value is being passed to the method. -In general, instances of two unrelated classes are not equal.
- For example, if the In rare cases, people do define nonsymmetrical equals methods and still manage to make
- their code work. Although none of the APIs document or guarantee it, it is typically
- the case that if you check if a HE: Signature declares use of unhashable class in hashed construct (HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS)- - -A method, field or class declares a generic signature where a non-hashable class -is used in context where a hashable class is required. -A class that declares an equals method but inherits a hashCode() method -from Object is unhashable, since it doesn't fulfill the requirement that -equal objects have equal hashCodes. - - - -HE: Use of class without a hashCode() method in a hashed data structure (HE_USE_OF_UNHASHABLE_CLASS)- - -A class defines an equals(Object) method but not a hashCode() method, -and thus doesn't fulfill the requirement that equal objects have equal hashCodes. -An instance of this class is used in a hash data structure, making the need to -fix this problem of highest importance. - - - ICAST: int value converted to long and used as absolute time (ICAST_INT_2_LONG_AS_INSTANT)- - --This code converts a 32-bit int value to a 64-bit long value, and then -passes that value for a method parameter that requires an absolute time value. -An absolute time value is the number -of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. -For example, the following method, intended to convert seconds since the epoc into a Date, is badly -broken: -
-Date getDate(int seconds) { return new Date(seconds * 1000); }
-
-The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value. -When a 32-bit value is converted to 64-bits and used to express an absolute time -value, only dates in December 1969 and January 1970 can be represented. - -Correct implementations for the above method are: - -
-// Fails for dates after 2037
-Date getDate(int seconds) { return new Date(seconds * 1000L); }
-
-// better, works for all dates
-Date getDate(long seconds) { return new Date(seconds * 1000); }
-
-
-
-ICAST: integral value cast to double and then passed to Math.ceil (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)- - --This code converts an integral value (e.g., int or long) -to a double precision -floating point number and then -passing the result to the Math.ceil() function, which rounds a double to -the next higher integer value. This operation should always be a no-op, -since the converting an integer to a double should give a number with no fractional part. -It is likely that the operation that generated the value to be passed -to Math.ceil was intended to be performed using double precision -floating point arithmetic. - - - - -ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)- - --This code converts an int value to a float precision -floating point number and then -passing the result to the Math.round() function, which returns the int/long closest -to the argument. This operation should always be a no-op, -since the converting an integer to a float should give a number with no fractional part. -It is likely that the operation that generated the value to be passed -to Math.round was intended to be performed using -floating point arithmetic. - - - - -IJU: JUnit assertion in run method will not be noticed by JUnit (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)- - -A JUnit assertion is performed in a run method. Failed JUnit assertions -just result in exceptions being thrown. -Thus, if this exception occurs in a thread other than the thread that invokes -the test method, the exception will terminate the thread but not result -in the test failing. - - - -IJU: TestCase declares a bad suite method (IJU_BAD_SUITE_METHOD)- - -Class is a JUnit TestCase and defines a suite() method. -However, the suite method needs to be declared as either - public static junit.framework.Test suite()-or - public static junit.framework.TestSuite suite()- - - - IJU: TestCase has no tests (IJU_NO_TESTS)- - -Class is a JUnit TestCase but has not implemented any test methods - - -IJU: TestCase defines setUp that doesn't call super.setUp() (IJU_SETUP_NO_SUPER)- - -Class is a JUnit TestCase and implements the setUp method. The setUp method should call -super.setUp(), but doesn't. - - -IJU: TestCase implements a non-static suite method (IJU_SUITE_NOT_STATIC)- - -Class is a JUnit TestCase and implements the suite() method. - The suite method should be declared as being static, but isn't. - - -IJU: TestCase defines tearDown that doesn't call super.tearDown() (IJU_TEARDOWN_NO_SUPER)- - -Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call -super.tearDown(), but doesn't. - - -IL: A collection is added to itself (IL_CONTAINER_ADDED_TO_ITSELF)- - -A collection is added to itself. As a result, computing the hashCode of this -set will throw a StackOverflowException. - - - -IL: An apparent infinite loop (IL_INFINITE_LOOP)- - -This loop doesn't seem to have a way to terminate (other than by perhaps -throwing an exception). - - -IL: An apparent infinite recursive loop (IL_INFINITE_RECURSIVE_LOOP)- - -This method unconditionally invokes itself. This would seem to indicate -an infinite recursive loop that will result in a stack overflow. - - -IM: Integer multiply of result of integer remainder (IM_MULTIPLYING_RESULT_OF_IREM)- - --The code multiplies the result of an integer remaining by an integer constant. -Be sure you don't have your operator precedence confused. For example -i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000). - - - -INT: Bad comparison of int value with long constant (INT_BAD_COMPARISON_WITH_INT_VALUE)- - -This code compares an int value with a long constant that is outside -the range of values that can be represented as an int value. -This comparison is vacuous and possibily to be incorrect. - - - -INT: Bad comparison of nonnegative value with negative constant (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)- - -This code compares a value that is guaranteed to be non-negative with a negative constant. - - - -INT: Bad comparison of signed byte (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)- - - Signed bytes can only have a value in the range -128 to 127. Comparing
-a signed byte with a value outside that range is vacuous and likely to be incorrect.
-To convert a signed byte IO: Doomed attempt to append to an object output stream (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)- - -- This code opens a file in append mode and then wraps the result in an object output stream. - This won't allow you to append to an existing object output stream stored in a file. If you want to be - able to append to an object output stream, you need to keep the object output stream open. - -The only situation in which opening a file in append mode and the writing an object output stream - could work is if on reading the file you plan to open it in random access mode and seek to the byte offset - where the append started. - - -- TODO: example. - - - -IP: A parameter is dead upon entry to a method but overwritten (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)- - --The initial value of this parameter is ignored, and the parameter -is overwritten here. This often indicates a mistaken belief that -the write to the parameter will be conveyed back to -the caller. - - - -MF: Class defines field that masks a superclass field (MF_CLASS_MASKS_FIELD)- - -This class defines a field with the same name as a visible -instance field in a superclass. This is confusing, and -may indicate an error if methods update or access one of -the fields when they wanted the other. - - -MF: Method defines a variable that obscures a field (MF_METHOD_MASKS_FIELD)- - -This method defines a local variable with the same name as a field -in this class or a superclass. This may cause the method to -read an uninitialized value from the field, leave the field uninitialized, -or both. - - -NP: Null pointer dereference (NP_ALWAYS_NULL)- - - A null pointer is dereferenced here. This will lead to a
- NP: Null pointer dereference in method on exception path (NP_ALWAYS_NULL_EXCEPTION)- - - A pointer which is null on an exception path is dereferenced here.
-This will lead to a Also note that FindBugs considers the default case of a switch statement to -be an exception path, since the default case is often infeasible. - - -NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)- - -- A parameter to this method has been identified as a value that should - always be checked to see whether or not it is null, but it is being dereferenced - without a preceding null check. - - - -NP: close() invoked on a value that is always null (NP_CLOSING_NULL)- - -close() is being invoked on a value that is always null. If this statement is executed, -a null pointer exception will occur. But the big risk here you never close -something that should be closed. - - - NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)- - -- There is a statement or branch that if executed guarantees that - a value is null at this point, and that - value that is guaranteed to be dereferenced - (except on forward paths involving runtime exceptions). - -Note that a check such as
- NP: Value is null and guaranteed to be dereferenced on exception path (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)- - -- There is a statement or branch on an exception path - that if executed guarantees that - a value is null at this point, and that - value that is guaranteed to be dereferenced - (except on forward paths involving runtime exceptions). - - - -NP: Method call passes null to a nonnull parameter (NP_NONNULL_PARAM_VIOLATION)- - -- This method passes a null value as the parameter of a method which - must be nonnull. Either this parameter has been explicitly marked - as @Nonnull, or analysis has determined that this parameter is - always dereferenced. - - - -NP: Method may return null, but is declared @NonNull (NP_NONNULL_RETURN_VIOLATION)- - -- This method may return a null value, but the method (or a superclass method - which it overrides) is declared to return @NonNull. - - - -NP: A known null value is checked to see if it is an instance of a type (NP_NULL_INSTANCEOF)- - --This instanceof test will always return false, since the value being checked is guaranteed to be null. -Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. - - - -NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)- - - There is a branch of statement that, if executed, guarantees that
-a null value will be dereferenced, which
-would generate a NP: Possible null pointer dereference in method on exception path (NP_NULL_ON_SOME_PATH_EXCEPTION)- - - A reference value which is null on some exception control path is
-dereferenced here. This may lead to a Also note that FindBugs considers the default case of a switch statement to -be an exception path, since the default case is often infeasible. - - -NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF)- - -- This method call passes a null value for a nonnull method parameter. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)- - -- A possibly-null value is passed at a call site where all known - target methods require the parameter to be nonnull. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Non-virtual method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_NONVIRTUAL)- - -- A possibly-null value is passed to a nonnull method parameter. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Store of null value into field annotated NonNull (NP_STORE_INTO_NONNULL_FIELD)- - -A value that could be null is stored into a field that has been annotated as NonNull. - - -NP: Read of unwritten field (NP_UNWRITTEN_FIELD)- - -The program is dereferencing a field that does not seem to ever have a non-null value written to it. -Unless the field is initialized via some mechanism not seen by the analysis, -dereferencing this value will generate a null pointer exception. - - - -Nm: Class defines equal(Object); should it be equals(Object)? (NM_BAD_EQUAL)- - - This class defines a method Nm: Class defines hashcode(); should it be hashCode()? (NM_LCASE_HASHCODE)- - - This class defines a method called Nm: Class defines tostring(); should it be toString()? (NM_LCASE_TOSTRING)- - - This class defines a method called Nm: Apparent method/constructor confusion (NM_METHOD_CONSTRUCTOR_CONFUSION)- - -This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. - If it was intended to be a constructor, remove the declaration of a void return value. - If you had accidently defined this method, realized the mistake, defined a proper constructor - but can't get rid of this method due to backwards compatibility, deprecate the method. - - - -Nm: Very confusing method names (NM_VERY_CONFUSING)- - -The referenced methods have names that differ only by capitalization. -This is very confusing because if the capitalization were -identical then one of the methods would override the other. - - - -Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE)- - -The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match -the type of the corresponding parameter in the superclass. For example, if you have: - -
-
-
-The QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)- - -- This method assigns a literal boolean value (true or false) to a boolean variable inside - an if or while expression. Most probably this was supposed to be a boolean comparison using - ==, not an assignment using =. - - - -RC: Suspicious reference comparison (RC_REF_COMPARISON)- - -This method compares two reference values using the == or != operator, -where the correct way to compare instances of this type is generally -with the equals() method. -It is possible to create distinct instances that are equal but do not compare as == since -they are different objects. -Examples of classes which should generally -not be compared by reference are java.lang.Integer, java.lang.Float, etc. - - -RCN: Nullcheck of value previously dereferenced (RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)- - -A value is checked here to see whether it is null, but this value can't -be null because it was previously dereferenced and if it were null a null pointer -exception would have occurred at the earlier dereference. -Essentially, this code and the previous dereference -disagree as to whether this value is allowed to be null. Either the check is redundant -or the previous dereference is erroneous. - - -RE: Invalid syntax for regular expression (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)- - --The code here uses a regular expression that is invalid according to the syntax -for regular expressions. This statement will throw a PatternSyntaxException when -executed. - - - -RE: File.separator used for regular expression (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)- - -
-The code here uses RE: "." used for regular expression (RE_POSSIBLE_UNINTENDED_PATTERN)- - --A String function is being invoked and "." is being passed -to a parameter that takes a regular expression as an argument. Is this what you intended? -For example -s.replaceAll(".", "/") will return a String in which every -character has been replaced by a / character, -and s.split(".") always returns a zero length array of String. - - - -RV: Random value from 0 to 1 is coerced to the integer 0 (RV_01_TO_INT)- - -A random value from 0 to 1 is being coerced to the integer value 0. You probably
-want to multiple the random value by something else before coercing it to an integer, or use the RV: Bad attempt to compute absolute value of signed 32-bit hashcode (RV_ABSOLUTE_VALUE_OF_HASHCODE)- - - This code generates a hashcode and then computes
-the absolute value of that hashcode. If the hashcode
-is One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, -including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES". - - - -RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)- - - This code generates a random signed integer and then computes
-the absolute value of that random integer. If the number returned by the random number
-generator is RV: Code checks for specific values returned by compareTo (RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE)- - -This code invoked a compareTo or compare method, and checks to see if the return value is a specific value, -such as 1 or -1. When invoking these methods, you should only check the sign of the result, not for any specific -non-zero value. While many or most compareTo and compare methods only return -1, 0 or 1, some of them -will return other values. - - - RV: Exception created and dropped rather than thrown (RV_EXCEPTION_NOT_THROWN)- - -This code creates an exception (or error) object, but doesn't do anything with it. For example, -something like -
-
-It was probably the intent of the programmer to throw the created exception: -
-
-
-
-RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)- - -The return value of this method should be checked. One common -cause of this warning is to invoke a method on an immutable object, -thinking that it updates the object. For example, in the following code -fragment, ----String dateString = getHeaderField(name); -dateString.trim(); -- the programmer seems to be thinking that the trim() method will update -the String referenced by dateString. But since Strings are immutable, the trim() -function returns a new String value, which is being ignored here. The code -should be corrected to: --- - --String dateString = getHeaderField(name); -dateString = dateString.trim(); -- RpC: Repeated conditional tests (RpC_REPEATED_CONDITIONAL_TEST)- - -The code contains a conditional test is performed twice, one right after the other
-(e.g., SA: Self assignment of field (SA_FIELD_SELF_ASSIGNMENT)- - -This method contains a self assignment of a field; e.g. - -
- int x;
- public void foo() {
- x = x;
- }
-
-Such assignments are useless, and may indicate a logic error or typo. - - -SA: Self comparison of field with itself (SA_FIELD_SELF_COMPARISON)- - -This method compares a field with itself, and may indicate a typo or -a logic error. Make sure that you are comparing the right things. - - - -SA: Nonsensical self computation involving a field (e.g., x & x) (SA_FIELD_SELF_COMPUTATION)- - -This method performs a nonsensical computation of a field with another -reference to the same field (e.g., x&x or x-x). Because of the nature -of the computation, this operation doesn't seem to make sense, -and may indicate a typo or -a logic error. Double check the computation. - - - -SA: Self assignment of local rather than assignment to field (SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD)- - -This method contains a self assignment of a local variable, and there -is a field with an identical name. -assignment appears to have been ; e.g. -
- int foo;
- public void setFoo(int foo) {
- foo = foo;
- }
-
-The assignment is useless. Did you mean to assign to the field instead? - - -SA: Self comparison of value with itself (SA_LOCAL_SELF_COMPARISON)- - -This method compares a local variable with itself, and may indicate a typo or -a logic error. Make sure that you are comparing the right things. - - - -SA: Nonsensical self computation involving a variable (e.g., x & x) (SA_LOCAL_SELF_COMPUTATION)- - -This method performs a nonsensical computation of a local variable with another -reference to the same variable (e.g., x&x or x-x). Because of the nature -of the computation, this operation doesn't seem to make sense, -and may indicate a typo or -a logic error. Double check the computation. - - - -SF: Dead store due to switch statement fall through (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)- - -A value stored in the previous switch case is overwritten here due to a switch fall through. It is likely that - you forgot to put a break or return at the end of the previous case. - - - -SF: Dead store due to switch statement fall through to throw (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW)- - -A value stored in the previous switch case is ignored here due to a switch fall through to a place where - an exception is thrown. It is likely that - you forgot to put a break or return at the end of the previous case. - - - -SIC: Deadly embrace of non-static inner class and thread local (SIC_THREADLOCAL_DEADLY_EMBRACE)- - -This class is an inner class, but should probably be a static inner class. - As it is, there is a serious danger of a deadly embrace between the inner class - and the thread local in the outer class. Because the inner class isn't static, - it retains a reference to the outer class. - If the thread local contains a reference to an instance of the inner - class, the inner and outer instance will both be reachable - and not eligible for garbage collection. - - - -SIO: Unnecessary type check done using instanceof operator (SIO_SUPERFLUOUS_INSTANCEOF)- - -Type check performed using the instanceof operator where it can be statically determined whether the object -is of the type requested. - - -SQL: Method attempts to access a prepared statement parameter with index 0 (SQL_BAD_PREPARED_STATEMENT_ACCESS)- - -A call to a setXXX method of a prepared statement was made where the -parameter index is 0. As parameter indexes start at index 1, this is always a mistake. - - -SQL: Method attempts to access a result set field with index 0 (SQL_BAD_RESULTSET_ACCESS)- - -A call to getXXX or updateXXX methods of a result set was made where the -field index is 0. As ResultSet fields start at index 1, this is always a mistake. - - -STI: Unneeded use of currentThread() call, to call interrupted() (STI_INTERRUPTED_ON_CURRENTTHREAD)- - --This method invokes the Thread.currentThread() call, just to call the interrupted() method. As interrupted() is a -static method, is more simple and clear to use Thread.interrupted(). - - - -STI: Static Thread.interrupted() method invoked on thread instance (STI_INTERRUPTED_ON_UNKNOWNTHREAD)- - --This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is -not the current thread. As the interrupted() method is static, the interrupted method will be called on a different -object than the one the author intended. - - - -Se: Method must be private in order for serialization to work (SE_METHOD_MUST_BE_PRIVATE)- - - This class implements the Se: The readResolve method must not be declared as a static method. (SE_READ_RESOLVE_IS_STATIC)- - -In order for the readResolve method to be recognized by the serialization -mechanism, it must not be declared as a static method. - - - -TQ: Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required (TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED)- - -- A value specified as carrying a type qualifier annotation is - consumed in a location or locations requiring that the value not - carry that annotation. - - -- More precisely, a value annotated with a type qualifier specifying when=ALWAYS - is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER. - - -- For example, say that @NonNegative is a nickname for - the type qualifier annotation @Negative(when=When.NEVER). - The following code will generate this warning because - the return statement requires a @NonNegative value, - but receives one that is marked as @Negative. - -
-
-
-
-TQ: Value that might not carry a type qualifier is always used in a way requires that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK)- - -- A value that is annotated as possibility not being an instance of - the values denoted by the type qualifier, and the value is guaranteed to be used - in a way that requires values denoted by that type qualifier. - - - -TQ: Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK)- - -- A value that is annotated as possibility being an instance of - the values denoted by the type qualifier, and the value is guaranteed to be used - in a way that prohibits values denoted by that type qualifier. - - - -TQ: Value annotated as never carrying a type qualifier used where value carrying that qualifier is required (TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED)- - -- A value specified as not carrying a type qualifier annotation is guaranteed - to be consumed in a location or locations requiring that the value does - carry that annotation. - - -- More precisely, a value annotated with a type qualifier specifying when=NEVER - is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS. - - -- TODO: example - - - -UMAC: Uncallable method defined in anonymous class (UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)- - -This anonymous class defined a method that is not directly invoked and does not override -a method in a superclass. Since methods in other classes cannot directly invoke methods -declared in an anonymous class, it seems that this method is uncallable. The method -might simply be dead code, but it is also possible that the method is intended to -override a method declared in a superclass, and due to an typo or other error the method does not, -in fact, override the method it is intended to. - - - -UR: Uninitialized read of field in constructor (UR_UNINIT_READ)- - -This constructor reads a field which has not yet been assigned a value. - This is often caused when the programmer mistakenly uses the field instead - of one of the constructor's parameters. - - -UR: Uninitialized read of field method called from constructor of superclass (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)- - -This method is invoked in the constructor of of the superclass. At this point, - the fields of the class have not yet initialized. -To make this more concrete, consider the following classes: -abstract class A {
- int hashCode;
- abstract Object getValue();
- A() {
- hashCode = getValue().hashCode();
- }
- }
-class B extends A {
- Object value;
- B(Object v) {
- this.value = v;
- }
- Object getValue() {
- return value;
- }
- }
-When a USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)- - --The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result -such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable -String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. - - - -USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ARRAY)- - --The code invokes toString on an array, which will generate a fairly useless result -such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable -String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. - - - -USELESS_STRING: Array formatted in useless way using format string (VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY)- - -
-One of the arguments being formatted with a format string is an array. This will be formatted
-using a fairly useless format, such as [I@304282, which doesn't actually show the contents
-of the array.
-Consider wrapping the array using UwF: Field only ever set to null (UWF_NULL_FIELD)- - -All writes to this field are of the constant value null, and thus -all reads of the field will return null. -Check for errors, or remove it if it is useless. - - -UwF: Unwritten field (UWF_UNWRITTEN_FIELD)- - -This field is never written. All reads of it will return the default -value. Check for errors (should it have been initialized?), or remove it if it is useless. - - -VA: Primitive array passed to function expecting a variable number of object arguments (VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG)- - --This code passes a primitive array to a function that takes a variable number of object arguments. -This creates an array of length one to hold the primitive array and passes it to the function. - - - -LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)- - -OpenJDK introduces a potential incompatibility. - In particular, the java.util.logging.Logger behavior has - changed. Instead of using strong references, it now uses weak references - internally. That's a reasonable change, but unfortunately some code relies on - the old behavior - when changing logger configuration, it simply drops the - logger reference. That means that the garbage collector is free to reclaim - that memory, which means that the logger configuration is lost. For example, -consider: - - -public static void initLogging() throws Exception {
- Logger logger = Logger.getLogger("edu.umd.cs");
- logger.addHandler(new FileHandler()); // call to change logger configuration
- logger.setUseParentHandlers(false); // another call to change logger configuration
-}
-
-The logger reference is lost at the end of the method (it doesn't -escape the method), so if you have a garbage collection cycle just -after the call to initLogging, the logger configuration is lost -(because Logger only keeps weak references). - -public static void main(String[] args) throws Exception {
- initLogging(); // adds a file handler to the logger
- System.gc(); // logger configuration lost
- Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
-}
-Ulf Ochsenfahrt and Eric Fellheimer - - -OBL: Method may fail to clean up stream or resource (OBL_UNSATISFIED_OBLIGATION)- - -- This method may fail to clean up (close, dispose of) a stream, - database object, or other - resource requiring an explicit cleanup operation. - - -- In general, if a method opens a stream or other resource, - the method should use a try/finally block to ensure that - the stream or resource is cleaned up before the method - returns. - - -- This bug pattern is essentially the same as the - OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE - bug patterns, but is based on a different - (and hopefully better) static analysis technique. - We are interested is getting feedback about the - usefulness of this bug pattern. - To send feedback, either: - -
- In particular, - the false-positive suppression heuristics for this - bug pattern have not been extensively tuned, so - reports about false positives are helpful to us. - - -- See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for - a description of the analysis technique. - - - -OBL: Method may fail to clean up stream or resource on checked exception (OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE)- - -- This method may fail to clean up (close, dispose of) a stream, - database object, or other - resource requiring an explicit cleanup operation. - - -- In general, if a method opens a stream or other resource, - the method should use a try/finally block to ensure that - the stream or resource is cleaned up before the method - returns. - - -- This bug pattern is essentially the same as the - OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE - bug patterns, but is based on a different - (and hopefully better) static analysis technique. - We are interested is getting feedback about the - usefulness of this bug pattern. - To send feedback, either: - -
- In particular, - the false-positive suppression heuristics for this - bug pattern have not been extensively tuned, so - reports about false positives are helpful to us. - - -- See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for - a description of the analysis technique. - - - -Dm: Consider using Locale parameterized version of invoked method (DM_CONVERT_CASE)- - -A String is being converted to upper or lowercase, using the platform's default encoding. This may - result in improper conversions when used with international characters. Use the -
versions instead. - - -Dm: Reliance on default encoding (DM_DEFAULT_ENCODING)- - -Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly. - - -DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)- - -This code creates a classloader, which needs permission if a security manage is installed. - If this code might be invoked by code that does not - have security permissions, then the classloader creation needs to occur inside a doPrivileged block. - - -DP: Method invoked that should be only be invoked inside a doPrivileged block (DP_DO_INSIDE_DO_PRIVILEGED)- - -This code invokes a method that requires a security permission check. - If this code will be granted security permissions, but might be invoked by code that does not - have security permissions, then the invocation needs to occur inside a doPrivileged block. - - -EI: May expose internal representation by returning reference to mutable object (EI_EXPOSE_REP)- - -Returning a reference to a mutable object value stored in one of the object's fields - exposes the internal representation of the object. - If instances - are accessed by untrusted code, and unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Returning a new copy of the object is better approach in many situations. - - -EI2: May expose internal representation by incorporating reference to mutable object (EI_EXPOSE_REP2)- - -This code stores a reference to an externally mutable object into the - internal representation of the object. - If instances - are accessed by untrusted code, and unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Storing a copy of the object is better approach in many situations. - - -FI: Finalizer should be protected, not public (FI_PUBLIC_SHOULD_BE_PROTECTED)- - - A class's MS: May expose internal static state by storing a mutable object into a static field (EI_EXPOSE_STATIC_REP2)- - -This code stores a reference to an externally mutable object into a static - field. - If unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Storing a copy of the object is better approach in many situations. - - -MS: Field isn't final and can't be protected from malicious code (MS_CANNOT_BE_FINAL)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - Unfortunately, the way the field is used doesn't allow - any easy fix to this problem. - - -MS: Public static method may expose internal representation by returning array (MS_EXPOSE_REP)- - -A public static method returns a reference to - an array that is part of the static state of the class. - Any code that calls this method can freely modify - the underlying array. - One fix is to return a copy of the array. - - -MS: Field should be both final and package protected (MS_FINAL_PKGPROTECT)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - The field could be made package protected and/or made final - to avoid - this vulnerability. - - -MS: Field is a mutable array (MS_MUTABLE_ARRAY)- - -A final static field references an array - and can be accessed by malicious code or - by accident from another package. - This code can freely modify the contents of the array. - - -MS: Field is a mutable Hashtable (MS_MUTABLE_HASHTABLE)- - -A final static field references a Hashtable - and can be accessed by malicious code or - by accident from another package. - This code can freely modify the contents of the Hashtable. - - -MS: Field should be moved out of an interface and made package protected (MS_OOI_PKGPROTECT)- - -- A final static field that is -defined in an interface references a mutable - object such as an array or hashtable. - This mutable object could - be changed by malicious code or - by accident from another package. - To solve this, the field needs to be moved to a class - and made package protected - to avoid - this vulnerability. - - -MS: Field should be package protected (MS_PKGPROTECT)- - -A mutable static field could be changed by malicious code or - by accident. - The field could be made package protected to avoid - this vulnerability. - - -MS: Field isn't final but should be (MS_SHOULD_BE_FINAL)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - The field could be made final to avoid - this vulnerability. - - -AT: Sequence of calls to concurrent abstraction may not be atomic (AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION)- - -This code contains a sequence of calls to a concurrent abstraction - (such as a concurrent hash map). - These calls will not be executed atomically. - - - DC: Possible double check of field (DC_DOUBLECHECK)- - -This method may contain an instance of double-checked locking. - This idiom is not correct according to the semantics of the Java memory - model. For more information, see the web page - http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html. - - -DL: Synchronization on Boolean (DL_SYNCHRONIZATION_ON_BOOLEAN)- - -The code synchronizes on a boxed primitive constant, such as an Boolean. -
-private static Boolean inited = Boolean.FALSE;
-...
- synchronized(inited) {
- if (!inited) {
- init();
- inited = Boolean.TRUE;
- }
- }
-...
-
-
-Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness -and possible deadlock -See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - -DL: Synchronization on boxed primitive (DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE)- - -The code synchronizes on a boxed primitive constant, such as an Integer. -
-private static Integer count = 0;
-...
- synchronized(count) {
- count++;
- }
-...
-
-
-Since Integer objects can be cached and shared, -this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness -and possible deadlock -See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - -DL: Synchronization on interned String (DL_SYNCHRONIZATION_ON_SHARED_CONSTANT)- - -The code synchronizes on interned String. -
-private static String LOCK = "LOCK";
-...
- synchronized(LOCK) { ...}
-...
-
-
-Constant Strings are interned and shared across all other classes loaded by the JVM. Thus, this could -is locking on something that other code might also be locking. This could result in very strange and hard to diagnose -blocking and deadlock behavior. See http://www.javalobby.org/java/forums/t96352.html and http://jira.codehaus.org/browse/JETTY-352. - See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - - -DL: Synchronization on boxed primitive values (DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE)- - -The code synchronizes on an apparently unshared boxed primitive, -such as an Integer. -
-private static final Integer fileLock = new Integer(1);
-...
- synchronized(fileLock) {
- .. do something ..
- }
-...
-
-
-It would be much better, in this code, to redeclare fileLock as - -private static final Object fileLock = new Object(); --The existing code might be OK, but it is confusing and a -future refactoring, such as the "Remove Boxing" refactoring in IntelliJ, -might replace this with the use of an interned Integer object shared -throughout the JVM, leading to very confusing behavior and potential deadlock. - - - - Dm: Monitor wait() called on Condition (DM_MONITOR_WAIT_ON_CONDITION)- - -
- This method calls Dm: A thread was created using the default empty run method (DM_USELESS_THREAD)- - -This method creates a thread without specifying a run method either by deriving from the Thread class, or - by passing a Runnable object. This thread, then, does nothing but waste time. - - - -ESync: Empty synchronized block (ESync_EMPTY_SYNC)- - -The code contains an empty synchronized block: -
-synchronized() {}
-
-Empty synchronized blocks are far more subtle and hard to use correctly -than most people recognize, and empty synchronized blocks -are almost never a better solution -than less contrived solutions. - - - -IS: Inconsistent synchronization (IS2_INCONSISTENT_SYNC)- - -The fields of this class appear to be accessed inconsistently with respect - to synchronization. This bug report indicates that the bug pattern detector - judged that - -
A typical bug matching this bug pattern is forgetting to synchronize - one of the methods in a class that is intended to be thread-safe. - -You can select the nodes labeled "Unsynchronized access" to show the - code locations where the detector believed that a field was accessed - without synchronization. - -Note that there are various sources of inaccuracy in this detector; - for example, the detector cannot statically detect all situations in which - a lock is held. Also, even when the detector is accurate in - distinguishing locked vs. unlocked accesses, the code in question may still - be correct. - - - -IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)- - -This field is annotated with net.jcip.annotations.GuardedBy, -but can be accessed in a way that seems to violate the annotation. - - -JLM: Synchronization performed on Lock (JLM_JSR166_LOCK_MONITORENTER)- - - This method performs synchronization an object that implements
-java.util.concurrent.locks.Lock. Such an object is locked/unlocked
-using
- JLM: Synchronization performed on util.concurrent instance (JLM_JSR166_UTILCONCURRENT_MONITORENTER)- - - This method performs synchronization an object that is an instance of
-a class from the java.util.concurrent package (or its subclasses). Instances
-of these classes have their own concurrency control mechanisms that are orthogonal to
-the synchronization provided by the Java keyword Such code may be correct, but should be carefully reviewed and documented, -and may confuse people who have to maintain the code at a later date. - - - -JLM: Using monitor style wait methods on util.concurrent abstraction (JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT)- - - This method calls
- LI: Incorrect lazy initialization of static field (LI_LAZY_INIT_STATIC)- - -This method contains an unsynchronized lazy initialization of a non-volatile static field. -Because the compiler or processor may reorder instructions, -threads are not guaranteed to see a completely initialized object, -if the method can be called by multiple threads. -You can make the field volatile to correct the problem. -For more information, see the -Java Memory Model web site. - - - -LI: Incorrect lazy initialization and update of static field (LI_LAZY_INIT_UPDATE_STATIC)- - -This method contains an unsynchronized lazy initialization of a static field. -After the field is set, the object stored into that location is further updated or accessed. -The setting of the field is visible to other threads as soon as it is set. If the -futher accesses in the method that set the field serve to initialize the object, then -you have a very serious multithreading bug, unless something else prevents -any other thread from accessing the stored object until it is fully initialized. - -Even if you feel confident that the method is never called by multiple -threads, it might be better to not set the static field until the value -you are setting it to is fully populated/initialized. - - - ML: Synchronization on field in futile attempt to guard that field (ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD)- - -This method synchronizes on a field in what appears to be an attempt -to guard against simultaneous updates to that field. But guarding a field -gets a lock on the referenced object, not on the field. This may not -provide the mutual exclusion you need, and other threads might -be obtaining locks on the referenced objects (for other purposes). An example -of this pattern would be: - -
-private Long myNtfSeqNbrCounter = new Long(0);
-private Long getNotificationSequenceNumber() {
- Long result = null;
- synchronized(myNtfSeqNbrCounter) {
- result = new Long(myNtfSeqNbrCounter.longValue() + 1);
- myNtfSeqNbrCounter = new Long(result.longValue());
- }
- return result;
- }
-
-
-
-
-
-
-ML: Method synchronizes on an updated field (ML_SYNC_ON_UPDATED_FIELD)- - -This method synchronizes on an object - referenced from a mutable field. - This is unlikely to have useful semantics, since different -threads may be synchronizing on different objects. - - -MSF: Mutable servlet field (MSF_MUTABLE_SERVLET_FIELD)- - -A web server generally only creates one instance of servlet or jsp class (i.e., treats -the class as a Singleton), -and will -have multiple threads invoke methods on that instance to service multiple -simultaneous requests. -Thus, having a mutable instance field generally creates race conditions. - - - MWN: Mismatched notify() (MWN_MISMATCHED_NOTIFY)- - - This method calls Object.notify() or Object.notifyAll() without obviously holding a lock
-on the object. Calling notify() or notifyAll() without a lock held will result in
-an MWN: Mismatched wait() (MWN_MISMATCHED_WAIT)- - - This method calls Object.wait() without obviously holding a lock
-on the object. Calling wait() without a lock held will result in
-an NN: Naked notify (NN_NAKED_NOTIFY)- - - A call to This bug does not necessarily indicate an error, since the change to - mutable object state may have taken place in a method which then called - the method containing the notification. - - -NP: Synchronize and null check on the same field. (NP_SYNC_AND_NULL_CHECK_FIELD)- - -Since the field is synchronized on, it seems not likely to be null. -If it is null and then synchronized on a NullPointerException will be -thrown and the check would be pointless. Better to synchronize on -another field. - - - -No: Using notify() rather than notifyAll() (NO_NOTIFY_NOT_NOTIFYALL)- - - This method calls RS: Class's readObject() method is synchronized (RS_READOBJECT_SYNC)- - - This serializable class defines a RV: Return value of putIfAbsent ignored, value passed to putIfAbsent reused (RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED)- - - TheputIfAbsent method is typically used to ensure that a
- single value is associated with a given key (the first value for which put
- if absent succeeds).
- If you ignore the return value and retain a reference to the value passed in,
- you run the risk of retaining a value that is not the one that is associated with the key in the map.
- If it matters which one you use and you use the one that isn't stored in the map,
- your program will behave incorrectly.
-
-
-Ru: Invokes run on a thread (did you mean to start it instead?) (RU_INVOKE_RUN)- - - This method explicitly invokes SC: Constructor invokes Thread.start() (SC_START_IN_CTOR)- - -The constructor starts a thread. This is likely to be wrong if - the class is ever extended/subclassed, since the thread will be started - before the subclass constructor is started. - - -SP: Method spins on field (SP_SPIN_ON_FIELD)- - -This method spins in a loop which reads a field. The compiler - may legally hoist the read out of the loop, turning the code into an - infinite loop. The class should be changed so it uses proper - synchronization (including wait and notify calls). - - -STCAL: Call to static Calendar (STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)- - -Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. -The detector has found a call to an instance of Calendar that has been obtained via a static -field. This looks suspicous. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)- - -As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. -The detector has found a call to an instance of DateFormat that has been obtained via a static -field. This looks suspicous. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Static Calendar field (STCAL_STATIC_CALENDAR_INSTANCE)- - -Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. -Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the -application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see -random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(). -You may also experience serialization problems. -Using an instance field is recommended. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Static DateFormat (STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)- - -As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. -Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the -application. -You may also experience serialization problems. -Using an instance field is recommended. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -SWL: Method calls Thread.sleep() with a lock held (SWL_SLEEP_WITH_LOCK_HELD)- - -- This method calls Thread.sleep() with a lock held. This may result - in very poor performance and scalability, or a deadlock, since other threads may - be waiting to acquire the lock. It is a much better idea to call - wait() on the lock, which releases the lock and allows other threads - to run. - - - -TLW: Wait with two locks held (TLW_TWO_LOCK_WAIT)- - -Waiting on a monitor while two locks are held may cause - deadlock. - - Performing a wait only releases the lock on the object - being waited on, not any other locks. - -This not necessarily a bug, but is worth examining - closely. - - -UG: Unsynchronized get method, synchronized set method (UG_SYNC_SET_UNSYNC_GET)- - -This class contains similarly-named get and set - methods where the set method is synchronized and the get method is not. - This may result in incorrect behavior at runtime, as callers of the get - method will not necessarily see a consistent state for the object. - The get method should be made synchronized. - - -UL: Method does not release lock on all paths (UL_UNRELEASED_LOCK)- - - This method acquires a JSR-166 (
- Lock l = ...;
- l.lock();
- try {
- // do something
- } finally {
- l.unlock();
- }
-
-
-
-UL: Method does not release lock on all exception paths (UL_UNRELEASED_LOCK_EXCEPTION_PATH)- - - This method acquires a JSR-166 (
- Lock l = ...;
- l.lock();
- try {
- // do something
- } finally {
- l.unlock();
- }
-
-
-
-UW: Unconditional wait (UW_UNCOND_WAIT)- - - This method contains a call to VO: An increment to a volatile field isn't atomic (VO_VOLATILE_INCREMENT)- - -This code increments a volatile field. Increments of volatile fields aren't -atomic. If more than one thread is incrementing the field at the same time, -increments could be lost. - - - -VO: A volatile reference to an array doesn't treat the array elements as volatile (VO_VOLATILE_REFERENCE_TO_ARRAY)- - -This declares a volatile reference to an array, which might not be what -you want. With a volatile reference to an array, reads and writes of -the reference to the array are treated as volatile, but the array elements -are non-volatile. To get volatile array elements, you will need to use -one of the atomic array classes in java.util.concurrent (provided -in Java 5.0). - - -WL: Synchronization on getClass rather than class literal (WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)- - -
- This instance method synchronizes on
- private static final String base = "label";
- private static int nameCounter = 0;
- String constructComponentName() {
- synchronized (getClass()) {
- return base + nameCounter++;
- }
- }
-
- Subclasses of
- private static final String base = "label";
- private static int nameCounter = 0;
- String constructComponentName() {
- synchronized (Label.class) {
- return base + nameCounter++;
- }
- }
-
- Bug pattern contributed by Jason Mehrens - - -WS: Class's writeObject() method is synchronized but nothing else is (WS_WRITEOBJECT_SYNC)- - - This class has a Wa: Condition.await() not in loop (WA_AWAIT_NOT_IN_LOOP)- - - This method contains a call to Wa: Wait not in loop (WA_NOT_IN_LOOP)- - - This method contains a call to Bx: Primitive value is boxed and then immediately unboxed (BX_BOXING_IMMEDIATELY_UNBOXED)- - -A primitive is boxed, and then immediately unboxed. This probably is due to a manual - boxing in a place where an unboxed value is required, thus forcing the compiler -to immediately undo the work of the boxing. - - - -Bx: Primitive value is boxed then unboxed to perform primitive coercion (BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)- - -A primitive boxed value constructed and then immediately converted into a different primitive type
-(e.g., Bx: Boxed value is unboxed and then immediately reboxed (BX_UNBOXING_IMMEDIATELY_REBOXED)- - -A boxed value is unboxed and then immediately reboxed. - - - -Bx: Method allocates a boxed primitive just to call toString (DM_BOXED_PRIMITIVE_TOSTRING)- - -A boxed primitive is allocated just to call toString(). It is more effective to just use the static - form of toString which takes the primitive value. So, -
Bx: Method invokes inefficient floating-point Number constructor; use static valueOf instead (DM_FP_NUMBER_CTOR)- - -
- Using
- Unless the class must be compatible with JVMs predating Java 1.5,
- use either autoboxing or the Bx: Method invokes inefficient Number constructor; use static valueOf instead (DM_NUMBER_CTOR)- - -
- Using
- Values between -128 and 127 are guaranteed to have corresponding cached instances
- and using
- Unless the class must be compatible with JVMs predating Java 1.5,
- use either autoboxing or the Dm: The equals and hashCode methods of URL are blocking (DMI_BLOCKING_METHODS_ON_URL)- - - The equals and hashCode
-method of URL perform domain name resolution, this can result in a big performance hit.
-See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
-Consider using Dm: Maps and sets of URLs can be performance hogs (DMI_COLLECTION_OF_URLS)- - - This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode
-method of URL perform domain name resolution, this can result in a big performance hit.
-See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
-Consider using Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead (DM_BOOLEAN_CTOR)- - - Creating new instances of Dm: Explicit garbage collection; extremely dubious except in benchmarking code (DM_GC)- - -Code explicitly invokes garbage collection. - Except for specific use in benchmarking, this is very dubious. -In the past, situations where people have explicitly invoked - the garbage collector in routines such as close or finalize methods - has led to huge performance black holes. Garbage collection - can be expensive. Any situation that forces hundreds or thousands - of garbage collections will bring the machine to a crawl. - - -Dm: Method allocates an object, only to get the class object (DM_NEW_FOR_GETCLASS)- - -This method allocates an object just to call getClass() on it, in order to - retrieve the Class object for it. It is simpler to just access the .class property of the class. - - -Dm: Use the nextInt method of Random rather than nextDouble to generate a random integer (DM_NEXTINT_VIA_NEXTDOUBLE)- - -If The argument to nextInt must be positive. If, for example, you want to generate a random
-value from -99 to 0, use Dm: Method invokes inefficient new String(String) constructor (DM_STRING_CTOR)- - - Using the Dm: Method invokes toString() method on a String (DM_STRING_TOSTRING)- - - Calling Dm: Method invokes inefficient new String() constructor (DM_STRING_VOID_CTOR)- - - Creating a new HSC: Huge string constants is duplicated across multiple class files (HSC_HUGE_SHARED_STRING_CONSTANT)- - -- A large String constant is duplicated across multiple class files. - This is likely because a final field is initialized to a String constant, and the Java language - mandates that all references to a final field from other classes be inlined into -that classfile. See JDK bug 6447475 - for a description of an occurrence of this bug in the JDK and how resolving it reduced - the size of the JDK by 1 megabyte. - - - -ITA: Method uses toArray() with zero-length array argument (ITA_INEFFICIENT_TO_ARRAY)- - - This method uses the toArray() method of a collection derived class, and passes
-in a zero-length prototype array argument. It is more efficient to use
- SBSC: Method concatenates strings using + in a loop (SBSC_USE_STRINGBUFFER_CONCATENATION)- - -The method seems to be building a String using concatenation in a loop. -In each iteration, the String is converted to a StringBuffer/StringBuilder, - appended to, and converted back to a String. - This can lead to a cost quadratic in the number of iterations, - as the growing string is recopied in each iteration. - -Better performance can be obtained by using -a StringBuffer (or StringBuilder in Java 1.5) explicitly. - -For example: -
- // This is bad
- String s = "";
- for (int i = 0; i < field.length; ++i) {
- s = s + field[i];
- }
-
- // This is better
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < field.length; ++i) {
- buf.append(field[i]);
- }
- String s = buf.toString();
-
-
-
-SIC: Should be a static inner class (SIC_INNER_SHOULD_BE_STATIC)- - -This class is an inner class, but does not use its embedded reference - to the object which created it. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made static. - - - -SIC: Could be refactored into a named static inner class (SIC_INNER_SHOULD_BE_STATIC_ANON)- - -This class is an inner class, but does not use its embedded reference - to the object which created it. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made into a static inner class. Since anonymous inner -classes cannot be marked as static, doing this will require refactoring -the inner class so that it is a named inner class. - - -SIC: Could be refactored into a static inner class (SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS)- - -This class is an inner class, but does not use its embedded reference - to the object which created it except during construction of the -inner object. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made into a static inner class. Since the reference to the - outer object is required during construction of the inner instance, - the inner class will need to be refactored so as to - pass a reference to the outer instance to the constructor - for the inner class. - - -SS: Unread field: should this field be static? (SS_SHOULD_BE_STATIC)- - -This class contains an instance final field that - is initialized to a compile-time static value. - Consider making the field static. - - -UM: Method calls static Math class method on a constant value (UM_UNNECESSARY_MATH)- - -This method uses a static method from java.lang.Math on a constant value. This method's -result in this case, can be determined statically, and is faster and sometimes more accurate to -just use the constant. Methods detected are: - -
UPM: Private method is never called (UPM_UNCALLED_PRIVATE_METHOD)- - -This private method is never called. Although it is -possible that the method will be invoked through reflection, -it is more likely that the method is never used, and should be -removed. - - - -UrF: Unread field (URF_UNREAD_FIELD)- - -This field is never read. Consider removing it from the class. - - -UuF: Unused field (UUF_UNUSED_FIELD)- - -This field is never used. Consider removing it from the class. - - -WMI: Inefficient use of keySet iterator instead of entrySet iterator (WMI_WRONG_MAP_ITERATOR)- - -This method accesses the value of a Map entry, using a key that was retrieved from -a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the -Map.get(key) lookup. - - -Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD)- - -This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can - easily learn the password. - - - - -Dm: Empty database password (DMI_EMPTY_DB_PASSWORD)- - -This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. - - - - -HRS: HTTP cookie formed from untrusted input (HRS_REQUEST_PARAMETER_TO_COOKIE)- - -This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting -vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting -for more information. -FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. -If FindBugs found any, you almost certainly have more -vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -HRS: HTTP Response splitting vulnerability (HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)- - -This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting -vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting -for more information. -FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. -If FindBugs found any, you almost certainly have more -vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -SQL: Nonconstant string passed to execute method on an SQL statement (SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)- - -The method invokes the execute method on an SQL statement with a String that seems -to be dynamically generated. Consider using -a prepared statement instead. It is more efficient and less vulnerable to -SQL injection attacks. - - - -SQL: A prepared statement is generated from a nonconstant String (SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)- - -The code creates an SQL prepared statement from a nonconstant String. -If unchecked, tainted data from a user is used in building this String, SQL injection could -be used to make the prepared statement do something unexpected and undesirable. - - - -XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)- - -This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - -XSS: Servlet reflected cross site scripting vulnerability in error page (XSS_REQUEST_PARAMETER_TO_SEND_ERROR)- - -This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows -for a reflected cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -XSS: Servlet reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER)- - -This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -BC: Questionable cast to abstract collection (BC_BAD_CAST_TO_ABSTRACT_COLLECTION)- - -
-This code casts a Collection to an abstract collection
-(such as BC: Questionable cast to concrete collection (BC_BAD_CAST_TO_CONCRETE_COLLECTION)- - --This code casts an abstract collection (such as a Collection, List, or Set) -to a specific concrete implementation (such as an ArrayList or HashSet). -This might not be correct, and it may make your code fragile, since -it makes it harder to switch to other concrete implementations at a future -point. Unless you have a particular reason to do so, just use the abstract -collection class. - - - -BC: Unchecked/unconfirmed cast (BC_UNCONFIRMED_CAST)- - --This cast is unchecked, and not all instances of the type casted from can be cast to -the type it is being cast to. Ensure that your program logic ensures that this -cast will not fail. - - - -BC: instanceof will always return true (BC_VACUOUS_INSTANCEOF)- - --This instanceof test will always return true (unless the value being tested is null). -Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. -If you really want to test the value for being null, perhaps it would be clearer to do -better to do a null test rather than an instanceof test. - - - -BSHIFT: Unsigned right shift cast to short/byte (ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT)- - --The code performs an unsigned right shift, whose result is then -cast to a short or byte, which discards the upper bits of the result. -Since the upper bits are discarded, there may be no difference between -a signed and unsigned right shift (depending upon the size of the shift). - - - -CI: Class is final but declares protected field (CI_CONFUSED_INHERITANCE)- - -- This class is declared to be final, but declares fields to be protected. Since the class - is final, it can not be derived from, and the use of protected is confusing. The access - modifier for the field should be changed to private or public to represent the true - use for the field. - - - -DB: Method uses the same code for two branches (DB_DUPLICATE_BRANCHES)- - -- This method uses the same code to implement two branches of a conditional branch. - Check to ensure that this isn't a coding mistake. - - - -DB: Method uses the same code for two switch clauses (DB_DUPLICATE_SWITCH_CLAUSES)- - -- This method uses the same code to implement two clauses of a switch statement. - This could be a case of duplicate code, but it might also indicate - a coding mistake. - - - -DLS: Dead store to local variable (DLS_DEAD_LOCAL_STORE)- - --This instruction assigns a value to a local variable, -but the value is not read or used in any subsequent instruction. -Often, this indicates an error, because the value computed is never -used. - --Note that Sun's javac compiler often generates dead stores for -final local variables. Because FindBugs is a bytecode-based tool, -there is no easy way to eliminate these false positives. - - - -DLS: Useless assignment in return statement (DLS_DEAD_LOCAL_STORE_IN_RETURN)- - --This statement assigns to a local variable in a return statement. This assignment -has effect. Please verify that this statement does the right thing. - - - -DLS: Dead store of null to local variable (DLS_DEAD_LOCAL_STORE_OF_NULL)- - -The code stores null into a local variable, and the stored value is not -read. This store may have been introduced to assist the garbage collector, but -as of Java SE 6.0, this is no longer needed or useful. - - - -DLS: Dead store to local variable that shadows field (DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD)- - --This instruction assigns a value to a local variable, -but the value is not read or used in any subsequent instruction. -Often, this indicates an error, because the value computed is never -used. There is a field with the same name as the local variable. Did you -mean to assign to that variable instead? - - - -DMI: Code contains a hard coded reference to an absolute pathname (DMI_HARDCODED_ABSOLUTE_FILENAME)- - -This code constructs a File object using a hard coded to an absolute pathname
-(e.g., DMI: Non serializable object written to ObjectOutput (DMI_NONSERIALIZABLE_OBJECT_WRITTEN)- - --This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. -If the object is, indeed, non-serializable, an error will result. - - - -DMI: Invocation of substring(0), which returns the original value (DMI_USELESS_SUBSTRING)- - --This code invokes substring(0) on a String, which returns the original value. - - - -Dm: Thread passed where Runnable expected (DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED)- - -A Thread object is passed as a parameter to a method where -a Runnable is expected. This is rather unusual, and may indicate a logic error -or cause unexpected behavior. - - - -Eq: Class doesn't override equals in superclass (EQ_DOESNT_OVERRIDE_EQUALS)- - -This class extends a class that defines an equals method and adds fields, but doesn't -define an equals method itself. Thus, equality on instances of this class will -ignore the identity of the subclass and the added fields. Be sure this is what is intended, -and that you don't need to override the equals method. Even if you don't need to override -the equals method, consider overriding it anyway to document the fact -that the equals method for the subclass just return the result of -invoking super.equals(o). - - - -Eq: Unusual equals method (EQ_UNUSUAL)- - - This class doesn't do any of the patterns we recognize for checking that the type of the argument
-is compatible with the type of the FE: Test for floating point equality (FE_FLOATING_POINT_EQUALITY)- - -
- This operation compares two floating point values for equality.
- Because floating point calculations may involve rounding,
- calculated float and double values may not be accurate.
- For values that must be precise, such as monetary values,
- consider using a fixed-precision type such as BigDecimal.
- For values that need not be precise, consider comparing for equality
- within some range, for example:
- FS: Non-Boolean argument formatted using %b format specifier (VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN)- - --An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an -exception; instead, it will print true for any nonnull value, and false for null. -This feature of format strings is strange, and may not be what you intended. - - - -IA: Ambiguous invocation of either an inherited or outer method (IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD)- - -An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. By the Java semantics, -it will be resolved to invoke the inherited method, but this may not be want -you intend. If you really intend to invoke the inherited method, -invoke it by invoking the method on super (e.g., invoke super.foo(17)), and -thus it will be clear to other readers of your code and to FindBugs -that you want to invoke the inherited method, not the method in the outer class. - - - -IC: Initialization circularity (IC_INIT_CIRCULARITY)- - -A circularity was detected in the static initializers of the two - classes referenced by the bug instance. Many kinds of unexpected - behavior may arise from such circularity. - - -ICAST: integral division result cast to double or float (ICAST_IDIV_CAST_TO_DOUBLE)- - --This code casts the result of an integral division (e.g., int or long division) -operation to double or -float. -Doing division on integers truncates the result -to the integer value closest to zero. The fact that the result -was cast to double suggests that this precision should have been retained. -What was probably meant was to cast one or both of the operands to -double before performing the division. Here is an example: - --- - --int x = 2; -int y = 5; -// Wrong: yields result 0.0 -double value1 = x / y; - -// Right: yields result 0.4 -double value2 = x / (double) y; -- ICAST: Result of integer multiplication cast to long (ICAST_INTEGER_MULTIPLY_CAST_TO_LONG)- - -
-This code performs integer multiply and then converts the result to a long,
-as in:
- IM: Computation of average could overflow (IM_AVERAGE_COMPUTATION_COULD_OVERFLOW)- - -The code computes the average of two integers using either division or signed right shift,
-and then uses the result as the index of an array.
-If the values being averaged are very large, this can overflow (resulting in the computation
-of a negative average). Assuming that the result is intended to be nonnegative, you
-can use an unsigned right shift instead. In other words, rather that using This bug exists in many earlier implementations of binary search and merge sort. -Martin Buchholz found and fixed it -in the JDK libraries, and Joshua Bloch -widely -publicized the bug pattern. - - - -IM: Check for oddness that won't work for negative numbers (IM_BAD_CHECK_FOR_ODD)- - --The code uses x % 2 == 1 to check to see if a value is odd, but this won't work -for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check -for oddness, consider using x & 1 == 1, or x % 2 != 0. - - - -INT: Integer remainder modulo 1 (INT_BAD_REM_BY_1)- - -Any expression (exp % 1) is guaranteed to always return zero. -Did you mean (exp & 1) or (exp % 2) instead? - - - -INT: Vacuous bit mask operation on integer value (INT_VACUOUS_BIT_OPERATION)- - - This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work
-(e.g., INT: Vacuous comparison of integer value (INT_VACUOUS_COMPARISON)- - -There is an integer comparison that always returns -the same value (e.g., x <= Integer.MAX_VALUE). - - - -MTIA: Class extends Servlet class and uses instance variables (MTIA_SUSPECT_SERVLET_INSTANCE_FIELD)- - -- This class extends from a Servlet class, and uses an instance member variable. Since only - one instance of a Servlet class is created by the J2EE framework, and used in a - multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider - only using method local variables. - - - -MTIA: Class extends Struts Action class and uses instance variables (MTIA_SUSPECT_STRUTS_INSTANCE_FIELD)- - -- This class extends from a Struts Action class, and uses an instance member variable. Since only - one instance of a struts Action class is created by the Struts framework, and used in a - multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider - only using method local variables. Only instance fields that are written outside of a monitor - are reported. - - - -NP: Dereference of the result of readLine() without nullcheck (NP_DEREFERENCE_OF_READLINE_VALUE)- - -The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text -to read, readLine() will return null and dereferencing that will generate a null pointer exception. - - - -NP: Immediate dereference of the result of readLine() (NP_IMMEDIATE_DEREFERENCE_OF_READLINE)- - -The result of invoking readLine() is immediately dereferenced. If there are no more lines of text -to read, readLine() will return null and dereferencing that will generate a null pointer exception. - - - -NP: Load of known null value (NP_LOAD_OF_KNOWN_NULL_VALUE)- - -The variable referenced at this point is known to be null due to an earlier - check against null. Although this is valid, it might be a mistake (perhaps you -intended to refer to a different variable, or perhaps the earlier check to see if the -variable is null should have been a check to see if it was nonnull). - - - -NP: Possible null pointer dereference due to return value of called method (NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)- - - The return value from a method is dereferenced without a null check,
-and the return value of that method is one that should generally be checked
-for null. This may lead to a NP: Possible null pointer dereference on branch that might be infeasible (NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE)- - - There is a branch of statement that, if executed, guarantees that
-a null value will be dereferenced, which
-would generate a NP: Parameter must be nonnull but is marked as nullable (NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE)- - -This parameter is always used in a way that requires it to be nonnull, -but the parameter is explicitly annotated as being Nullable. Either the use -of the parameter or the annotation is wrong. - - - -NP: Read of unwritten public or protected field (NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)- - -The program is dereferencing a public or protected -field that does not seem to ever have a non-null value written to it. -Unless the field is initialized via some mechanism not seen by the analysis, -dereferencing this value will generate a null pointer exception. - - - -NS: Potentially dangerous use of non-short-circuit logic (NS_DANGEROUS_NON_SHORT_CIRCUIT)- - -This code seems to be using non-short-circuit logic (e.g., & -or |) -rather than short-circuit logic (&& or ||). In addition, -it seem possible that, depending on the value of the left hand side, you might not -want to evaluate the right hand side (because it would have side effects, could cause an exception -or could be expensive. --Non-short-circuit logic causes both sides of the expression -to be evaluated even when the result can be inferred from -knowing the left-hand side. This can be less efficient and -can result in errors if the left-hand side guards cases -when evaluating the right-hand side can generate an error. - - -See the Java -Language Specification for details - - - - -NS: Questionable use of non-short-circuit logic (NS_NON_SHORT_CIRCUIT)- - -This code seems to be using non-short-circuit logic (e.g., & -or |) -rather than short-circuit logic (&& or ||). -Non-short-circuit logic causes both sides of the expression -to be evaluated even when the result can be inferred from -knowing the left-hand side. This can be less efficient and -can result in errors if the left-hand side guards cases -when evaluating the right-hand side can generate an error. - - See the Java -Language Specification for details - - - - -PZLA: Consider returning a zero length array rather than null (PZLA_PREFER_ZERO_LENGTH_ARRAYS)- - -It is often a better design to -return a length zero array rather than a null reference to indicate that there -are no results (i.e., an empty list of results). -This way, no explicit check for null is needed by clients of the method. - -On the other hand, using null to indicate
-"there is no answer to this question" is probably appropriate.
-For example, QF: Complicated, subtle or wrong increment in for-loop (QF_QUESTIONABLE_FOR_LOOP)- - -Are you sure this for loop is incrementing the correct variable? - It appears that another variable is being initialized and checked - by the for loop. - - - -RCN: Redundant comparison of non-null value to null (RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE)- - -This method contains a reference known to be non-null with another reference -known to be null. - - -RCN: Redundant comparison of two null values (RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES)- - -This method contains a redundant comparison of two references known to -both be definitely null. - - -RCN: Redundant nullcheck of value known to be non-null (RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE)- - -This method contains a redundant check of a known non-null value against -the constant null. - - -RCN: Redundant nullcheck of value known to be null (RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE)- - -This method contains a redundant check of a known null value against -the constant null. - - -REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)- - -- This method uses a try-catch block that catches Exception objects, but Exception is not - thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to - say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception - each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, - masking potential bugs. - - - -RI: Class implements same interface as superclass (RI_REDUNDANT_INTERFACES)- - -- This class declares that it implements an interface that is also implemented by a superclass. - This is redundant because once a superclass implements an interface, all subclasses by default also - implement this interface. It may point out that the inheritance hierarchy has changed since - this class was created, and consideration should be given to the ownership of - the interface's implementation. - - - -RV: Method checks to see if result of String.indexOf is positive (RV_CHECK_FOR_POSITIVE_INDEXOF)- - -The method invokes String.indexOf and checks to see if the result is positive or non-positive. - It is much more typical to check to see if the result is negative or non-negative. It is - positive only if the substring checked for occurs at some place other than at the beginning of - the String. - - -RV: Method discards result of readLine after checking if it is nonnull (RV_DONT_JUST_NULL_CHECK_READLINE)- - -The value returned by readLine is discarded after checking to see if the return -value is non-null. In almost all situations, if the result is non-null, you will want -to use that non-null value. Calling readLine again will give you a different line. - - -RV: Remainder of hashCode could be negative (RV_REM_OF_HASHCODE)- - -This code computes a hashCode, and then computes -the remainder of that value modulo another value. Since the hashCode -can be negative, the result of the remainder operation -can also be negative. - Assuming you want to ensure that the result of your computation is nonnegative,
-you may need to change your code.
-If you know the divisor is a power of 2,
-you can use a bitwise and operator instead (i.e., instead of
-using RV: Remainder of 32-bit signed random integer (RV_REM_OF_RANDOM_INT)- - -This code generates a random signed integer and then computes -the remainder of that value modulo another value. Since the random -number can be negative, the result of the remainder operation -can also be negative. Be sure this is intended, and strongly -consider using the Random.nextInt(int) method instead. - - - -RV: Method ignores return value, is this OK? (RV_RETURN_VALUE_IGNORED_INFERRED)- - -This code calls a method and ignores the return value. The return value
-is the same type as the type the method is invoked on, and from our analysis it looks
-like the return value might be important (e.g., like ignoring the
-return value of We are guessing that ignoring the return value might be a bad idea just from -a simple analysis of the body of the method. You can use a @CheckReturnValue annotation -to instruct FindBugs as to whether ignoring the return value of this method -is important or acceptable. - -Please investigate this closely to decide whether it is OK to ignore the return value. - - - -SA: Double assignment of field (SA_FIELD_DOUBLE_ASSIGNMENT)- - -This method contains a double assignment of a field; e.g. - -
- int x,y;
- public void foo() {
- x = x = 17;
- }
-
-Assigning to a field twice is useless, and may indicate a logic error or typo. - - -SA: Double assignment of local variable (SA_LOCAL_DOUBLE_ASSIGNMENT)- - -This method contains a double assignment of a local variable; e.g. - -
- public void foo() {
- int x,y;
- x = x = 17;
- }
-
-Assigning the same value to a variable twice is useless, and may indicate a logic error or typo. - - -SA: Self assignment of local variable (SA_LOCAL_SELF_ASSIGNMENT)- - -This method contains a self assignment of a local variable; e.g. -
- public void foo() {
- int x = 3;
- x = x;
- }
-
--Such assignments are useless, and may indicate a logic error or typo. - - - -SF: Switch statement found where one case falls through to the next case (SF_SWITCH_FALLTHROUGH)- - -This method contains a switch statement where one case branch will fall through to the next case. - Usually you need to end this case with a break or return. - - -SF: Switch statement found where default case is missing (SF_SWITCH_NO_DEFAULT)- - -This method contains a switch statement where default case is missing. - Usually you need to provide a default case. - - -ST: Write to static field from instance method (ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)- - -This instance method writes to a static field. This is tricky to get -correct if multiple instances are being manipulated, -and generally bad practice. - - - -Se: private readResolve method not inherited by subclasses (SE_PRIVATE_READ_RESOLVE_NOT_INHERITED)- - -This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses. -This might be intentional and OK, but should be reviewed to ensure it is what is intended. - - - -Se: Transient field of class that isn't Serializable. (SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS)- - -The field is marked as transient, but the class isn't Serializable, so marking it as transient -has absolutely no effect. -This may be leftover marking from a previous version of the code in which the class was transient, or -it may indicate a misunderstanding of how serialization works. - - - -TQ: Value required to have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK)- - -- A value is used in a way that requires it to be always be a value denoted by a type qualifier, but - there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. - Either the usage or the annotation is incorrect. - - - -TQ: Value required to not have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK)- - -- A value is used in a way that requires it to be never be a value denoted by a type qualifier, but - there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. - Either the usage or the annotation is incorrect. - - - -UCF: Useless control flow (UCF_USELESS_CONTROL_FLOW)- - - This method contains a useless control flow statement, where
-control flow continues onto the same place regardless of whether or not
-the branch is taken. For example,
-this is caused by having an empty statement
-block for an
- if (argv.length == 0) {
- // TODO: handle this case
- }
-
-
-
-UCF: Useless control flow to next line (UCF_USELESS_CONTROL_FLOW_NEXT_LINE)- - - This method contains a useless control flow statement in which control
-flow follows to the same or following line regardless of whether or not
-the branch is taken.
-Often, this is caused by inadvertently using an empty statement as the
-body of an
- if (argv.length == 1);
- System.out.println("Hello, " + argv[0]);
-
-
-
-UrF: Unread public/protected field (URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD)- - -This field is never read.  -The field is public or protected, so perhaps - it is intended to be used with classes not seen as part of the analysis. If not, -consider removing it from the class. - - -UuF: Unused public or protected field (UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD)- - -This field is never used. -The field is public or protected, so perhaps - it is intended to be used with classes not seen as part of the analysis. If not, -consider removing it from the class. - - -UwF: Field not initialized in constructor but dereferenced without null check (UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)- - -This field is never initialized within any constructor, and is therefore could be null after -the object is constructed. Elsewhere, it is loaded and dereferenced without a null check. -This could be a either an error or a questionable design, since -it means a null pointer exception will be generated if that field is dereferenced -before being initialized. - - - -UwF: Unwritten public or protected field (UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)- - -No writes were seen to this public/protected field. All reads of it will return the default -value. Check for errors (should it have been initialized?), or remove it if it is useless. - - -XFB: Method directly allocates a specific implementation of xml interfaces (XFB_XML_FACTORY_BYPASS)- - -- This method allocates a specific implementation of an xml interface. It is preferable to use - the supplied factory classes to create these objects so that the implementation can be - changed at runtime. See - -
for details. - - - - -- - Send comments to findbugs@cs.umd.edu - |
-
|
-
-FindBugs Bug Descriptions-This document lists the standard bug patterns reported by -FindBugs version 2.0.0. -Summary-Descriptions-AM: Creates an empty jar file entry (AM_CREATES_EMPTY_JAR_FILE_ENTRY)- - -The code calls AM: Creates an empty zip file entry (AM_CREATES_EMPTY_ZIP_FILE_ENTRY)- - -The code calls BC: Equals method should not assume anything about the type of its argument (BC_EQUALS_METHOD_SHOULD_WORK_FOR_ALL_OBJECTS)- - -
-The BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK)- - -This method compares an expression such as - ((event.detail & SWT.SELECTED) > 0). -Using bit arithmetic and then comparing with the greater than operator can -lead to unexpected results (of course depending on the value of -SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate -for a bug. Even when SWT.SELECTED is not negative, it seems good practice -to use '!= 0' instead of '> 0'. - - -Boris Bokowski - - - -CN: Class implements Cloneable but does not define or use clone method (CN_IDIOM)- - -- Class implements Cloneable but does not define or - use the clone method. - - -CN: clone method does not call super.clone() (CN_IDIOM_NO_SUPER_CALL)- - -This non-final class defines a clone() method that does not call super.clone(). -If this class ("A") is extended by a subclass ("B"), -and the subclass B calls super.clone(), then it is likely that -B's clone() method will return an object of type A, -which violates the standard contract for clone(). - -If all clone() methods call super.clone(), then they are guaranteed -to use Object.clone(), which always returns an object of the correct type. - - -CN: Class defines clone() but doesn't implement Cloneable (CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE)- - -This class defines a clone() method but the class doesn't implement Cloneable. -There are some situations in which this is OK (e.g., you want to control how subclasses -can clone themselves), but just make sure that this is what you intended. - - - -Co: Abstract class defines covariant compareTo() method (CO_ABSTRACT_SELF)- - - This class defines a covariant version of Co: Covariant compareTo() method defined (CO_SELF_NO_OBJECT)- - - This class defines a covariant version of DE: Method might drop exception (DE_MIGHT_DROP)- - -This method might drop an exception. In general, exceptions - should be handled or reported in some way, or they should be thrown - out of the method. - - -DE: Method might ignore exception (DE_MIGHT_IGNORE)- - -This method might ignore an exception. In general, exceptions - should be handled or reported in some way, or they should be thrown - out of the method. - - -DMI: Adding elements of an entry set may fail due to reuse of Entry objects (DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS)- - -The entrySet() method is allowed to return a view of the - underlying Map in which a single Entry object is reused and returned - during the iteration. As of Java 1.6, both IdentityHashMap - and EnumMap did so. When iterating through such a Map, - the Entry value is only valid until you advance to the next iteration. - If, for example, you try to pass such an entrySet to an addAll method, - things will go badly wrong. - - - -DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE)- - -This code creates a java.util.Random object, uses it to generate one random number, and then discards -the Random object. This produces mediocre quality random numbers and is inefficient. -If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number -is required invoke a method on the existing Random object to obtain it. - - -If it is important that the generated Random numbers not be guessable, you must not create a new Random for each random -number; the values are too easily guessable. You should strongly consider using a java.security.SecureRandom instead -(and avoid allocating a new SecureRandom for each random number needed). - - - -DMI: Don't use removeAll to clear a collection (DMI_USING_REMOVEALL_TO_CLEAR_COLLECTION)- - - If you want to remove all elements from a collection Dm: Method invokes System.exit(...) (DM_EXIT)- - -Invoking System.exit shuts down the entire Java virtual machine. This - should only been done when it is appropriate. Such calls make it - hard or impossible for your code to be invoked by other code. - Consider throwing a RuntimeException instead. - - -Dm: Method invokes dangerous method runFinalizersOnExit (DM_RUN_FINALIZERS_ON_EXIT)- - -Never call System.runFinalizersOnExit -or Runtime.runFinalizersOnExit for any reason: they are among the most -dangerous methods in the Java libraries. -- Joshua Bloch - - -ES: Comparison of String parameter using == or != (ES_COMPARING_PARAMETER_STRING_WITH_EQ)- - -This code compares a ES: Comparison of String objects using == or != (ES_COMPARING_STRINGS_WITH_EQ)- - -This code compares Eq: Abstract class defines covariant equals() method (EQ_ABSTRACT_SELF)- - - This class defines a covariant version of Eq: Equals checks for incompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)- - -This equals method is checking to see if the argument is some incompatible type -(i.e., a class that is neither a supertype nor subtype of the class that defines -the equals method). For example, the Foo class might have an equals method -that looks like: - -
This is considered bad practice, as it makes it very hard to implement an equals method that -is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. - - - -Eq: Class defines compareTo(...) and uses Object.equals() (EQ_COMPARETO_USE_OBJECT_EQUALS)- - - This class defines a From the JavaDoc for the compareTo method in the Comparable interface: -
-It is strongly recommended, but not strictly required that
-
-
-Eq: equals method fails for subtypes (EQ_GETCLASS_AND_CLASS_CONSTANT)- - - This class has an equals method that will be broken if it is inherited by subclasses.
-It compares a class literal with the class of the argument (e.g., in class Eq: Covariant equals() method defined (EQ_SELF_NO_OBJECT)- - - This class defines a covariant version of FI: Empty finalizer should be deleted (FI_EMPTY)- - - Empty FI: Explicit invocation of finalizer (FI_EXPLICIT_INVOCATION)- - - This method contains an explicit invocation of the If a connected set of objects beings finalizable, then the VM will invoke the -finalize method on all the finalizable object, possibly at the same time in different threads. -Thus, it is a particularly bad idea, in the finalize method for a class X, invoke finalize -on objects referenced by X, because they may already be getting finalized in a separate thread. - - - FI: Finalizer nulls fields (FI_FINALIZER_NULLS_FIELDS)- - -This finalizer nulls out fields. This is usually an error, as it does not aid garbage collection, - and the object is going to be garbage collected anyway. - - - FI: Finalizer only nulls fields (FI_FINALIZER_ONLY_NULLS_FIELDS)- - -This finalizer does nothing except null out fields. This is completely pointless, and requires that -the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize -method. - - - FI: Finalizer does not call superclass finalizer (FI_MISSING_SUPER_CALL)- - - This FI: Finalizer nullifies superclass finalizer (FI_NULLIFY_SUPER)- - - This empty FI: Finalizer does nothing but call superclass finalizer (FI_USELESS)- - - The only thing this FS: Format string should use %n rather than \n (VA_FORMAT_STRING_USES_NEWLINE)- - --This format string include a newline character (\n). In format strings, it is generally - preferable better to use %n, which will produce the platform-specific line separator. - - - -GC: Unchecked type in generic call (GC_UNCHECKED_TYPE_IN_GENERIC_CALL)- - -This call to a generic collection method passes an argument - while compile type Object where a specific type from - the generic type parameters is expected. - Thus, neither the standard Java type system nor static analysis - can provide useful information on whether the - object being passed as a parameter is of an appropriate type. - - - -HE: Class defines equals() but not hashCode() (HE_EQUALS_NO_HASHCODE)- - - This class overrides HE: Class defines equals() and uses Object.hashCode() (HE_EQUALS_USE_HASHCODE)- - - This class overrides If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
-the recommended public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
-
-HE: Class defines hashCode() but not equals() (HE_HASHCODE_NO_EQUALS)- - - This class defines a HE: Class defines hashCode() and uses Object.equals() (HE_HASHCODE_USE_OBJECT_EQUALS)- - - This class defines a If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
-the recommended public int hashCode() {
- assert false : "hashCode not designed";
- return 42; // any arbitrary constant will do
- }
-
-
-HE: Class inherits equals() and uses Object.hashCode() (HE_INHERITS_EQUALS_USE_HASHCODE)- - - This class inherits If you don't want to define a hashCode method, and/or don't
- believe the object will ever be put into a HashMap/Hashtable,
- define the IC: Superclass uses subclass during initialization (IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION)- - - During the initialization of a class, the class makes an active use of a subclass.
-That subclass will not yet be initialized at the time of this use.
-For example, in the following code,
-public class CircularClassInitialization {
- static class InnerClassSingleton extends CircularClassInitialization {
- static InnerClassSingleton singleton = new InnerClassSingleton();
- }
-
- static CircularClassInitialization foo = InnerClassSingleton.singleton;
-}
-
-
-
-
-IMSE: Dubious catching of IllegalMonitorStateException (IMSE_DONT_CATCH_IMSE)- - -IllegalMonitorStateException is generally only - thrown in case of a design flaw in your code (calling wait or - notify on an object you do not hold a lock on). - - -ISC: Needless instantiation of class that only supplies static methods (ISC_INSTANTIATE_STATIC_CLASS)- - -This class allocates an object that is based on a class that only supplies static methods. This object -does not need to be created, just access the static methods directly using the class name as a qualifier. - - -It: Iterator next() method can't throw NoSuchElementException (IT_NO_SUCH_ELEMENT)- - - This class implements the J2EE: Store of non serializable object into HttpSession (J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION)- - --This code seems to be storing a non-serializable object into an HttpSession. -If this session is passivated or migrated, an error will result. - - - -JCIP: Fields of immutable classes should be final (JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS)- - -The class is annotated with net.jcip.annotations.Immutable, and the rules for that annotation require -that all fields are final. - . - - -NP: Method with Boolean return type returns explicit null (NP_BOOLEAN_RETURN_NULL)- - -- A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. - This method can be invoked as though it returned a value of type boolean, and - the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, - this will result in a NullPointerException. - - - -NP: Clone method may return null (NP_CLONE_COULD_RETURN_NULL)- - -- This clone method seems to return null in some circumstances, but clone is never - allowed to return a null value. If you are convinced this path is unreachable, throw an AssertionError - instead. - - - -NP: equals() method does not check for null argument (NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT)- - -- This implementation of equals(Object) violates the contract defined - by java.lang.Object.equals() because it does not check for null - being passed as the argument. All equals() methods should return - false if passed a null value. - - - -NP: toString method may return null (NP_TOSTRING_COULD_RETURN_NULL)- - -- This toString method seems to return null in some circumstances. A liberal reading of the - spec could be interpreted as allowing this, but it is probably a bad idea and could cause - other code to break. Return the empty string or some other appropriate string rather than null. - - - -Nm: Class names should start with an upper case letter (NM_CLASS_NAMING_CONVENTION)- - -Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). - - - -Nm: Class is not derived from an Exception, even though it is named as such (NM_CLASS_NOT_EXCEPTION)- - -This class is not derived from another exception, but ends with 'Exception'. This will -be confusing to users of this class. - - -Nm: Confusing method names (NM_CONFUSING)- - -The referenced methods have names that differ only by capitalization. - - -Nm: Field names should start with a lower case letter (NM_FIELD_NAMING_CONVENTION)- - --Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. - - - -Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER)- - -The identifier is a word that is reserved as a keyword in later versions of Java, and your code will need to be changed -in order to compile it in later versions of Java. - - - -Nm: Use of identifier that is a keyword in later versions of Java (NM_FUTURE_KEYWORD_USED_AS_MEMBER_IDENTIFIER)- - -This identifier is used as a keyword in later versions of Java. This code, and -any code that references this API, -will need to be changed in order to compile it in later versions of Java. - - - -Nm: Method names should start with a lower case letter (NM_METHOD_NAMING_CONVENTION)- - --Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. - - - -Nm: Class names shouldn't shadow simple name of implemented interface (NM_SAME_SIMPLE_NAME_AS_INTERFACE)- - - This class/interface has a simple name that is identical to that of an implemented/extended interface, except
-that the interface is in a different package (e.g., Nm: Class names shouldn't shadow simple name of superclass (NM_SAME_SIMPLE_NAME_AS_SUPERCLASS)- - - This class has a simple name that is identical to that of its superclass, except
-that its superclass is in a different package (e.g., Nm: Very confusing method names (but perhaps intentional) (NM_VERY_CONFUSING_INTENTIONAL)- - -The referenced methods have names that differ only by capitalization. -This is very confusing because if the capitalization were -identical then one of the methods would override the other. From the existence of other methods, it -seems that the existence of both of these methods is intentional, but is sure is confusing. -You should try hard to eliminate one of them, unless you are forced to have both due to frozen APIs. - - - -Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE_INTENTIONAL)- - -The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match -the type of the corresponding parameter in the superclass. For example, if you have: - -
-
-
-The In this case, the subclass does define a method with a signature identical to the method in the superclass, -so this is presumably understood. However, such methods are exceptionally confusing. You should strongly consider -removing or deprecating the method with the similar but not identical signature. - - - -ODR: Method may fail to close database resource (ODR_OPEN_DATABASE_RESOURCE)- - -The method creates a database resource (such as a database connection -or row set), does not assign it to any -fields, pass it to other methods, or return it, and does not appear to close -the object on all paths out of the method. Failure to -close database resources on all paths out of a method may -result in poor performance, and could cause the application to -have problems communicating with the database. - - - -ODR: Method may fail to close database resource on exception (ODR_OPEN_DATABASE_RESOURCE_EXCEPTION_PATH)- - -The method creates a database resource (such as a database connection -or row set), does not assign it to any -fields, pass it to other methods, or return it, and does not appear to close -the object on all exception paths out of the method. Failure to -close database resources on all paths out of a method may -result in poor performance, and could cause the application to -have problems communicating with the database. - - -OS: Method may fail to close stream (OS_OPEN_STREAM)- - - The method creates an IO stream object, does not assign it to any
-fields, pass it to other methods that might close it,
-or return it, and does not appear to close
-the stream on all paths out of the method. This may result in
-a file descriptor leak. It is generally a good
-idea to use a OS: Method may fail to close stream on exception (OS_OPEN_STREAM_EXCEPTION_PATH)- - - The method creates an IO stream object, does not assign it to any
-fields, pass it to other methods, or return it, and does not appear to close
-it on all possible exception paths out of the method.
-This may result in a file descriptor leak. It is generally a good
-idea to use a PZ: Don't reuse entry objects in iterators (PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS)- - - The entrySet() method is allowed to return a view of the
- underlying Map in which an Iterator and Map.Entry. This clever
- idea was used in several Map implementations, but introduces the possibility
- of nasty coding mistakes. If a map RC: Suspicious reference comparison to constant (RC_REF_COMPARISON_BAD_PRACTICE)- - -This method compares a reference value to a constant using the == or != operator, -where the correct way to compare instances of this type is generally -with the equals() method. -It is possible to create distinct instances that are equal but do not compare as == since -they are different objects. -Examples of classes which should generally -not be compared by reference are java.lang.Integer, java.lang.Float, etc. - - -RC: Suspicious reference comparison of Boolean values (RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN)- - - This method compares two Boolean values using the == or != operator.
-Normally, there are only two Boolean values (Boolean.TRUE and Boolean.FALSE),
-but it is possible to create other Boolean objects using the RR: Method ignores results of InputStream.read() (RR_NOT_CHECKED)- - - This method ignores the return value of one of the variants of
- RR: Method ignores results of InputStream.skip() (SR_NOT_CHECKED)- - - This method ignores the return value of
- RV: Negating the result of compareTo()/compare() (RV_NEGATING_RESULT_OF_COMPARETO)- - -This code negatives the return value of a compareTo or compare method. -This is a questionable or bad programming practice, since if the return -value is Integer.MIN_VALUE, negating the return value won't -negate the sign of the result. You can achieve the same intended result -by reversing the order of the operands rather than by negating the results. - - - -RV: Method ignores exceptional return value (RV_RETURN_VALUE_IGNORED_BAD_PRACTICE)- - - This method returns a value that is not checked. The return value should be checked
-since it can indicate an unusual or unexpected function execution. For
-example, the SI: Static initializer creates instance before all static final fields assigned (SI_INSTANCE_BEFORE_FINALS_ASSIGNED)- - -The class's static initializer creates an instance of the class -before all of the static final fields are assigned. - - -SW: Certain swing methods needs to be invoked in Swing thread (SW_SWING_METHODS_INVOKED_IN_SWING_THREAD)- - -(From JDC Tech Tip): The Swing methods -show(), setVisible(), and pack() will create the associated peer for the frame. -With the creation of the peer, the system creates the event dispatch thread. -This makes things problematic because the event dispatch thread could be notifying -listeners while pack and validate are still processing. This situation could result in -two threads going through the Swing component-based GUI -- it's a serious flaw that -could result in deadlocks or other related threading issues. A pack call causes -components to be realized. As they are being realized (that is, not necessarily -visible), they could trigger listener notification on the event dispatch thread. - - - -Se: Non-transient non-serializable instance field in serializable class (SE_BAD_FIELD)- - - This Serializable class defines a non-primitive instance field which is neither transient,
-Serializable, or Se: Non-serializable class has a serializable inner class (SE_BAD_FIELD_INNER_CLASS)- - -This Serializable class is an inner class of a non-serializable class. -Thus, attempts to serialize it will also attempt to associate instance of the outer -class with which it is associated, leading to a runtime error. - -If possible, making the inner class a static inner class should solve the -problem. Making the outer class serializable might also work, but that would -mean serializing an instance of the inner class would always also serialize the instance -of the outer class, which it often not what you really want. - - - Se: Non-serializable value stored into instance field of a serializable class (SE_BAD_FIELD_STORE)- - -A non-serializable value is stored into a non-transient field -of a serializable class. - - -Se: Comparator doesn't implement Serializable (SE_COMPARATOR_SHOULD_BE_SERIALIZABLE)- - - This class implements the Se: Serializable inner class (SE_INNER_CLASS)- - -This Serializable class is an inner class. Any attempt to serialize -it will also serialize the associated outer instance. The outer instance is serializable, -so this won't fail, but it might serialize a lot more data than intended. -If possible, making the inner class a static inner class (also known as a nested class) should solve the -problem. - - - Se: serialVersionUID isn't final (SE_NONFINAL_SERIALVERSIONID)- - - This class defines a Se: serialVersionUID isn't long (SE_NONLONG_SERIALVERSIONID)- - - This class defines a Se: serialVersionUID isn't static (SE_NONSTATIC_SERIALVERSIONID)- - - This class defines a Se: Class is Serializable but its superclass doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR)- - - This class implements the Se: Class is Externalizable but doesn't define a void constructor (SE_NO_SUITABLE_CONSTRUCTOR_FOR_EXTERNALIZATION)- - - This class implements the Se: The readResolve method must be declared with a return type of Object. (SE_READ_RESOLVE_MUST_RETURN_OBJECT)- - -In order for the readResolve method to be recognized by the serialization -mechanism, it must be declared to have a return type of Object. - - - -Se: Transient field that isn't set by deserialization. (SE_TRANSIENT_FIELD_NOT_RESTORED)- - -This class contains a field that is updated at multiple places in the class, thus it seems to be part of the state of the class. However, since the field is marked as transient and not set in readObject or readResolve, it will contain the default value in any -deserialized instance of the class. - - - -SnVI: Class is Serializable, but doesn't define serialVersionUID (SE_NO_SERIALVERSIONID)- - - This class implements the UI: Usage of GetResource may be unsafe if class is extended (UI_INHERITANCE_UNSAFE_GETRESOURCE)- - -Calling BC: Impossible cast (BC_IMPOSSIBLE_CAST)- - --This cast will always throw a ClassCastException. -FindBugs tracks type information from instanceof checks, -and also uses more precise information about the types -of values returned from methods and loaded from fields. -Thus, it may have more precise information that just -the declared type of a variable, and can use this to determine -that a cast will always throw an exception at runtime. - - - - -BC: Impossible downcast (BC_IMPOSSIBLE_DOWNCAST)- - --This cast will always throw a ClassCastException. -The analysis believes it knows -the precise type of the value being cast, and the attempt to -downcast it to a subtype will always fail by throwing a ClassCastException. - - - -BC: Impossible downcast of toArray() result (BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY)- - -
-This code is casting the result of calling
-String[] getAsArray(Collection<String> c) {
- return (String[]) c.toArray();
- }
-
-This will usually fail by throwing a ClassCastException. The The correct way to do get an array of a specific type from a collection is to use
- There is one common/known exception exception to this. The BC: instanceof will always return false (BC_IMPOSSIBLE_INSTANCEOF)- - --This instanceof test will always return false. Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. - - - -BIT: Bitwise add of signed byte value (BIT_ADD_OF_SIGNED_BYTE)- - - Adds a byte value and a value which is known to have the 8 lower bits clear.
-Values loaded from a byte array are sign extended to 32 bits
-before any any bitwise operations are performed on the value.
-Thus, if In particular, the following code for packing a byte array into an int is badly wrong: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) + b[i]); -- - The following idiom will work instead: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) + (b[i] & 0xff)); -- - - - BIT: Incompatible bit masks (BIT_AND)- - -This method compares an expression of the form (e & C) to D, -which will always compare unequal -due to the specific values of constants C and D. -This may indicate a logic error or typo. - - -BIT: Check to see if ((...) & 0) == 0 (BIT_AND_ZZ)- - -This method compares an expression of the form (e & 0) to 0, -which will always compare equal. -This may indicate a logic error or typo. - - -BIT: Incompatible bit masks (BIT_IOR)- - -This method compares an expression of the form (e | C) to D. -which will always compare unequal -due to the specific values of constants C and D. -This may indicate a logic error or typo. - -Typically, this bug occurs because the code wants to perform -a membership test in a bit set, but uses the bitwise OR -operator ("|") instead of bitwise AND ("&"). - - -BIT: Bitwise OR of signed byte value (BIT_IOR_OF_SIGNED_BYTE)- - - Loads a byte value (e.g., a value loaded from a byte array or returned by a method
-with return type byte) and performs a bitwise OR with
-that value. Byte values are sign extended to 32 bits
-before any any bitwise operations are performed on the value.
-Thus, if In particular, the following code for packing a byte array into an int is badly wrong: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) | b[i]); -- - The following idiom will work instead: --int result = 0; -for(int i = 0; i < 4; i++) - result = ((result << 8) | (b[i] & 0xff)); -- - - - BIT: Check for sign of bitwise operation (BIT_SIGNED_CHECK_HIGH_BIT)- - -This method compares an expression such as - ((event.detail & SWT.SELECTED) > 0). -Using bit arithmetic and then comparing with the greater than operator can -lead to unexpected results (of course depending on the value of -SWT.SELECTED). If SWT.SELECTED is a negative number, this is a candidate -for a bug. Even when SWT.SELECTED is not negative, it seems good practice -to use '!= 0' instead of '> 0'. - - -Boris Bokowski - - - -BOA: Class overrides a method implemented in super class Adapter wrongly (BOA_BADLY_OVERRIDDEN_ADAPTER)- - -This method overrides a method found in a parent class, where that class is an Adapter that implements -a listener defined in the java.awt.event or javax.swing.event package. As a result, this method will not -get called when the event occurs. - - -BSHIFT: 32 bit int shifted by an amount not in the range 0..31 (ICAST_BAD_SHIFT_AMOUNT)- - --The code performs shift of a 32 bit int by a constant amount outside -the range 0..31. -The effect of this is to use the lower 5 bits of the integer -value to decide how much to shift by (e.g., shifting by 40 bits is the same as shifting by 8 bits, -and shifting by 32 bits is the same as shifting by zero bits). This probably isn't what was expected, -and it is at least confusing. - - - -Bx: Primitive value is unboxed and coerced for ternary operator (BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR)- - -A wrapped primitive value is unboxed and converted to another primitive type as part of the
-evaluation of a conditional ternary operator (the Co: compareTo()/compare() returns Integer.MIN_VALUE (CO_COMPARETO_RESULTS_MIN_VALUE)- - -In some situation, this compareTo or compare method returns -the constant Integer.MIN_VALUE, which is an exceptionally bad practice. - The only thing that matters about the return value of compareTo is the sign of the result. - But people will sometimes negate the return value of compareTo, expecting that this will negate - the sign of the result. And it will, except in the case where the value returned is Integer.MIN_VALUE. - So just return -1 rather than Integer.MIN_VALUE. - - - DLS: Dead store of class literal (DLS_DEAD_STORE_OF_CLASS_LITERAL)- - -
-This instruction assigns a class literal to a variable and then never uses it.
-The behavior of this differs in Java 1.4 and in Java 5.
-In Java 1.4 and earlier, a reference to See Sun's article on Java SE compatibility -for more details and examples, and suggestions on how to force class initialization in Java 5. - - - -DLS: Overwritten increment (DLS_OVERWRITTEN_INCREMENT)- - -
-The code performs an increment operation (e.g., DMI: Reversed method arguments (DMI_ARGUMENTS_WRONG_ORDER)- - - The arguments to this method call seem to be in the wrong order.
-For example, a call DMI: Bad constant value for month (DMI_BAD_MONTH)- - --This code passes a constant month -value outside the expected range of 0..11 to a method. - - - -DMI: BigDecimal constructed from double that isn't represented precisely (DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE)- - --This code creates a BigDecimal from a double value that doesn't translate well to a -decimal number. -For example, one might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. -You probably want to use the BigDecimal.valueOf(double d) method, which uses the String representation -of the double to create the BigDecimal (e.g., BigDecimal.valueOf(0.1) gives 0.1). - - - - -DMI: hasNext method invokes next (DMI_CALLING_NEXT_FROM_HASNEXT)- - --The hasNext() method invokes the next() method. This is almost certainly wrong, -since the hasNext() method is not supposed to change the state of the iterator, -and the next method is supposed to change the state of the iterator. - - - -DMI: Collections should not contain themselves (DMI_COLLECTIONS_SHOULD_NOT_CONTAIN_THEMSELVES)- - - This call to a generic collection's method would only make sense if a collection contained
-itself (e.g., if DMI: D'oh! A nonsensical method invocation (DMI_DOH)- - --This partical method invocation doesn't make sense, for reasons that should be apparent from inspection. - - - - -DMI: Invocation of hashCode on an array (DMI_INVOKING_HASHCODE_ON_ARRAY)- - -
-The code invokes hashCode on an array. Calling hashCode on
-an array returns the same value as System.identityHashCode, and ingores
-the contents and length of the array. If you need a hashCode that
-depends on the contents of an array DMI: Double.longBitsToDouble invoked on an int (DMI_LONG_BITS_TO_DOUBLE_INVOKED_ON_INT)- - -The Double.longBitsToDouble method is invoked, but a 32 bit int value is passed - as an argument. This almostly certainly is not intended and is unlikely - to give the intended result. - - - -DMI: Vacuous call to collections (DMI_VACUOUS_SELF_COLLECTION_CALL)- - - This call doesn't make sense. For any collection Dm: Can't use reflection to check for presence of annotation without runtime retention (DMI_ANNOTATION_IS_NOT_VISIBLE_TO_REFLECTION)- - -Unless an annotation has itself been annotated with @Retention(RetentionPolicy.RUNTIME), the annotation can't be observed using reflection -(e.g., by using the isAnnotationPresent method). - . - - -Dm: Futile attempt to change max pool size of ScheduledThreadPoolExecutor (DMI_FUTILE_ATTEMPT_TO_CHANGE_MAXPOOL_SIZE_OF_SCHEDULED_THREAD_POOL_EXECUTOR)- - -(Javadoc) -While ScheduledThreadPoolExecutor inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. - - - - -Dm: Creation of ScheduledThreadPoolExecutor with zero core threads (DMI_SCHEDULED_THREAD_POOL_EXECUTOR_WITH_ZERO_CORE_THREADS)- - -(Javadoc) -A ScheduledThreadPoolExecutor with zero core threads will never execute anything; changes to the max pool size are ignored. - - - - -Dm: Useless/vacuous call to EasyMock method (DMI_VACUOUS_CALL_TO_EASYMOCK_METHOD)- - -This call doesn't pass any objects to the EasyMock method, so the call doesn't do anything. - - - - -EC: equals() used to compare array and nonarray (EC_ARRAY_AND_NONARRAY)- - --This method invokes the .equals(Object o) to compare an array and a reference that doesn't seem -to be an array. If things being compared are of different types, they are guaranteed to be unequal -and the comparison is almost certainly an error. Even if they are both arrays, the equals method -on arrays only determines of the two arrays are the same object. -To compare the -contents of the arrays, use java.util.Arrays.equals(Object[], Object[]). - - - -EC: Invocation of equals() on an array, which is equivalent to == (EC_BAD_ARRAY_COMPARE)- - -
-This method invokes the .equals(Object o) method on an array. Since arrays do not override the equals
-method of Object, calling equals on an array is the same as comparing their addresses. To compare the
-contents of the arrays, use EC: equals(...) used to compare incompatible arrays (EC_INCOMPATIBLE_ARRAY_COMPARE)- - --This method invokes the .equals(Object o) to compare two arrays, but the arrays of -of incompatible types (e.g., String[] and StringBuffer[], or String[] and int[]). -They will never be equal. In addition, when equals(...) is used to compare arrays it -only checks to see if they are the same array, and ignores the contents of the arrays. - - - -EC: Call to equals(null) (EC_NULL_ARG)- - - This method calls equals(Object), passing a null value as
-the argument. According to the contract of the equals() method,
-this call should always return EC: Call to equals() comparing unrelated class and interface (EC_UNRELATED_CLASS_AND_INTERFACE)- - --This method calls equals(Object) on two references, one of which is a class -and the other an interface, where neither the class nor any of its -non-abstract subclasses implement the interface. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Call to equals() comparing different interface types (EC_UNRELATED_INTERFACES)- - -This method calls equals(Object) on two references of unrelated -interface types, where neither is a subtype of the other, -and there are no known non-abstract classes which implement both interfaces. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Call to equals() comparing different types (EC_UNRELATED_TYPES)- - -This method calls equals(Object) on two references of different -class types with no common subclasses. -Therefore, the objects being compared -are unlikely to be members of the same class at runtime -(unless some application classes were not analyzed, or dynamic class -loading can occur at runtime). -According to the contract of equals(), -objects of different -classes should always compare as unequal; therefore, according to the -contract defined by java.lang.Object.equals(Object), -the result of this comparison will always be false at runtime. - - - -EC: Using pointer equality to compare different types (EC_UNRELATED_TYPES_USING_POINTER_EQUALITY)- - -This method uses using pointer equality to compare two references that seem to be of -different types. The result of this comparison will always be false at runtime. - - - -Eq: equals method always returns false (EQ_ALWAYS_FALSE)- - -This class defines an equals method that always returns false. This means that an object is not equal to itself, and it is impossible to create useful Maps or Sets of this class. More fundamentally, it means -that equals is not reflexive, one of the requirements of the equals method. -The likely intended semantics are object identity: that an object is equal to itself. This is the behavior inherited from class
-public boolean equals(Object o) { return this == o; }
-
-
-
-
-Eq: equals method always returns true (EQ_ALWAYS_TRUE)- - -This class defines an equals method that always returns true. This is imaginative, but not very smart. -Plus, it means that the equals method is not symmetric. - - - -Eq: equals method compares class names rather than class objects (EQ_COMPARING_CLASS_NAMES)- - -This method checks to see if two objects are the same class by checking to see if the names -of their classes are equal. You can have different classes with the same name if they are loaded by -different class loaders. Just check to see if the class objects are the same. - - - -Eq: Covariant equals() method defined for enum (EQ_DONT_DEFINE_EQUALS_FOR_ENUM)- - -This class defines an enumeration, and equality on enumerations are defined -using object identity. Defining a covariant equals method for an enumeration -value is exceptionally bad practice, since it would likely result -in having two different enumeration values that compare as equals using -the covariant enum method, and as not equal when compared normally. -Don't do it. - - - -Eq: equals() method defined that doesn't override equals(Object) (EQ_OTHER_NO_OBJECT)- - - This class defines an Eq: equals() method defined that doesn't override Object.equals(Object) (EQ_OTHER_USE_OBJECT)- - - This class defines an Eq: equals method overrides equals in superclass and may not be symmetric (EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC)- - - This class defines an equals method that overrides an equals method in a superclass. Both equals methods
-methods use Eq: Covariant equals() method defined, Object.equals(Object) inherited (EQ_SELF_USE_OBJECT)- - - This class defines a covariant version of the FE: Doomed test for equality to NaN (FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER)- - -
- This code checks to see if a floating point value is equal to the special
- Not A Number value (e.g., FS: Format string placeholder incompatible with passed argument (VA_FORMAT_STRING_BAD_ARGUMENT)- - -
-The format string placeholder is incompatible with the corresponding
-argument. For example,
- The %d placeholder requires a numeric argument, but a string value is -passed instead. -A runtime exception will occur when -this statement is executed. - - - -FS: The type of a supplied argument doesn't match format specifier (VA_FORMAT_STRING_BAD_CONVERSION)- - -
-One of the arguments is uncompatible with the corresponding format string specifier.
-As a result, this will generate a runtime exception when executed.
-For example, FS: MessageFormat supplied where printf style format expected (VA_FORMAT_STRING_EXPECTED_MESSAGE_FORMAT_SUPPLIED)- - --A method is called that expects a Java printf format string and a list of arguments. -However, the format string doesn't contain any format specifiers (e.g., %s) but -does contain message format elements (e.g., {0}). It is likely -that the code is supplying a MessageFormat string when a printf-style format string -is required. At runtime, all of the arguments will be ignored -and the format string will be returned exactly as provided without any formatting. - - - - -FS: More arguments are passed than are actually used in the format string (VA_FORMAT_STRING_EXTRA_ARGUMENTS_PASSED)- - --A format-string method with a variable number of arguments is called, -but more arguments are passed than are actually used by the format string. -This won't cause a runtime exception, but the code may be silently omitting -information that was intended to be included in the formatted string. - - - -FS: Illegal format string (VA_FORMAT_STRING_ILLEGAL)- - --The format string is syntactically invalid, -and a runtime exception will occur when -this statement is executed. - - - -FS: Format string references missing argument (VA_FORMAT_STRING_MISSING_ARGUMENT)- - --Not enough arguments are passed to satisfy a placeholder in the format string. -A runtime exception will occur when -this statement is executed. - - - -FS: No previous argument for format string (VA_FORMAT_STRING_NO_PREVIOUS_ARGUMENT)- - --The format string specifies a relative index to request that the argument for the previous format specifier -be reused. However, there is no previous argument. -For example, - -
would throw a MissingFormatArgumentException when executed. - - - -GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)- - -This call to a generic collection method contains an argument - with an incompatible class from that of the collection's parameter - (i.e., the type of the argument is neither a supertype nor a subtype - of the corresponding generic type argument). - Therefore, it is unlikely that the collection contains any objects - that are equal to the method argument used here. - Most likely, the wrong value is being passed to the method. -In general, instances of two unrelated classes are not equal.
- For example, if the In rare cases, people do define nonsymmetrical equals methods and still manage to make
- their code work. Although none of the APIs document or guarantee it, it is typically
- the case that if you check if a HE: Signature declares use of unhashable class in hashed construct (HE_SIGNATURE_DECLARES_HASHING_OF_UNHASHABLE_CLASS)- - -A method, field or class declares a generic signature where a non-hashable class -is used in context where a hashable class is required. -A class that declares an equals method but inherits a hashCode() method -from Object is unhashable, since it doesn't fulfill the requirement that -equal objects have equal hashCodes. - - - -HE: Use of class without a hashCode() method in a hashed data structure (HE_USE_OF_UNHASHABLE_CLASS)- - -A class defines an equals(Object) method but not a hashCode() method, -and thus doesn't fulfill the requirement that equal objects have equal hashCodes. -An instance of this class is used in a hash data structure, making the need to -fix this problem of highest importance. - - - ICAST: int value converted to long and used as absolute time (ICAST_INT_2_LONG_AS_INSTANT)- - --This code converts a 32-bit int value to a 64-bit long value, and then -passes that value for a method parameter that requires an absolute time value. -An absolute time value is the number -of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. -For example, the following method, intended to convert seconds since the epoc into a Date, is badly -broken: -
-Date getDate(int seconds) { return new Date(seconds * 1000); }
-
-The multiplication is done using 32-bit arithmetic, and then converted to a 64-bit value. -When a 32-bit value is converted to 64-bits and used to express an absolute time -value, only dates in December 1969 and January 1970 can be represented. - -Correct implementations for the above method are: - -
-// Fails for dates after 2037
-Date getDate(int seconds) { return new Date(seconds * 1000L); }
-
-// better, works for all dates
-Date getDate(long seconds) { return new Date(seconds * 1000); }
-
-
-
-ICAST: integral value cast to double and then passed to Math.ceil (ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL)- - --This code converts an integral value (e.g., int or long) -to a double precision -floating point number and then -passing the result to the Math.ceil() function, which rounds a double to -the next higher integer value. This operation should always be a no-op, -since the converting an integer to a double should give a number with no fractional part. -It is likely that the operation that generated the value to be passed -to Math.ceil was intended to be performed using double precision -floating point arithmetic. - - - - -ICAST: int value cast to float and then passed to Math.round (ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND)- - --This code converts an int value to a float precision -floating point number and then -passing the result to the Math.round() function, which returns the int/long closest -to the argument. This operation should always be a no-op, -since the converting an integer to a float should give a number with no fractional part. -It is likely that the operation that generated the value to be passed -to Math.round was intended to be performed using -floating point arithmetic. - - - - -IJU: JUnit assertion in run method will not be noticed by JUnit (IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD)- - -A JUnit assertion is performed in a run method. Failed JUnit assertions -just result in exceptions being thrown. -Thus, if this exception occurs in a thread other than the thread that invokes -the test method, the exception will terminate the thread but not result -in the test failing. - - - -IJU: TestCase declares a bad suite method (IJU_BAD_SUITE_METHOD)- - -Class is a JUnit TestCase and defines a suite() method. -However, the suite method needs to be declared as either - public static junit.framework.Test suite()-or - public static junit.framework.TestSuite suite()- - - - IJU: TestCase has no tests (IJU_NO_TESTS)- - -Class is a JUnit TestCase but has not implemented any test methods - - -IJU: TestCase defines setUp that doesn't call super.setUp() (IJU_SETUP_NO_SUPER)- - -Class is a JUnit TestCase and implements the setUp method. The setUp method should call -super.setUp(), but doesn't. - - -IJU: TestCase implements a non-static suite method (IJU_SUITE_NOT_STATIC)- - -Class is a JUnit TestCase and implements the suite() method. - The suite method should be declared as being static, but isn't. - - -IJU: TestCase defines tearDown that doesn't call super.tearDown() (IJU_TEARDOWN_NO_SUPER)- - -Class is a JUnit TestCase and implements the tearDown method. The tearDown method should call -super.tearDown(), but doesn't. - - -IL: A collection is added to itself (IL_CONTAINER_ADDED_TO_ITSELF)- - -A collection is added to itself. As a result, computing the hashCode of this -set will throw a StackOverflowException. - - - -IL: An apparent infinite loop (IL_INFINITE_LOOP)- - -This loop doesn't seem to have a way to terminate (other than by perhaps -throwing an exception). - - -IL: An apparent infinite recursive loop (IL_INFINITE_RECURSIVE_LOOP)- - -This method unconditionally invokes itself. This would seem to indicate -an infinite recursive loop that will result in a stack overflow. - - -IM: Integer multiply of result of integer remainder (IM_MULTIPLYING_RESULT_OF_IREM)- - --The code multiplies the result of an integer remaining by an integer constant. -Be sure you don't have your operator precedence confused. For example -i % 60 * 1000 is (i % 60) * 1000, not i % (60 * 1000). - - - -INT: Bad comparison of int value with long constant (INT_BAD_COMPARISON_WITH_INT_VALUE)- - -This code compares an int value with a long constant that is outside -the range of values that can be represented as an int value. -This comparison is vacuous and possibily to be incorrect. - - - -INT: Bad comparison of nonnegative value with negative constant (INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE)- - -This code compares a value that is guaranteed to be non-negative with a negative constant. - - - -INT: Bad comparison of signed byte (INT_BAD_COMPARISON_WITH_SIGNED_BYTE)- - - Signed bytes can only have a value in the range -128 to 127. Comparing
-a signed byte with a value outside that range is vacuous and likely to be incorrect.
-To convert a signed byte IO: Doomed attempt to append to an object output stream (IO_APPENDING_TO_OBJECT_OUTPUT_STREAM)- - -- This code opens a file in append mode and then wraps the result in an object output stream. - This won't allow you to append to an existing object output stream stored in a file. If you want to be - able to append to an object output stream, you need to keep the object output stream open. - -The only situation in which opening a file in append mode and the writing an object output stream - could work is if on reading the file you plan to open it in random access mode and seek to the byte offset - where the append started. - - -- TODO: example. - - - -IP: A parameter is dead upon entry to a method but overwritten (IP_PARAMETER_IS_DEAD_BUT_OVERWRITTEN)- - --The initial value of this parameter is ignored, and the parameter -is overwritten here. This often indicates a mistaken belief that -the write to the parameter will be conveyed back to -the caller. - - - -MF: Class defines field that masks a superclass field (MF_CLASS_MASKS_FIELD)- - -This class defines a field with the same name as a visible -instance field in a superclass. This is confusing, and -may indicate an error if methods update or access one of -the fields when they wanted the other. - - -MF: Method defines a variable that obscures a field (MF_METHOD_MASKS_FIELD)- - -This method defines a local variable with the same name as a field -in this class or a superclass. This may cause the method to -read an uninitialized value from the field, leave the field uninitialized, -or both. - - -NP: Null pointer dereference (NP_ALWAYS_NULL)- - - A null pointer is dereferenced here. This will lead to a
- NP: Null pointer dereference in method on exception path (NP_ALWAYS_NULL_EXCEPTION)- - - A pointer which is null on an exception path is dereferenced here.
-This will lead to a Also note that FindBugs considers the default case of a switch statement to -be an exception path, since the default case is often infeasible. - - -NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)- - -- A parameter to this method has been identified as a value that should - always be checked to see whether or not it is null, but it is being dereferenced - without a preceding null check. - - - -NP: close() invoked on a value that is always null (NP_CLOSING_NULL)- - -close() is being invoked on a value that is always null. If this statement is executed, -a null pointer exception will occur. But the big risk here you never close -something that should be closed. - - - NP: Null value is guaranteed to be dereferenced (NP_GUARANTEED_DEREF)- - -- There is a statement or branch that if executed guarantees that - a value is null at this point, and that - value that is guaranteed to be dereferenced - (except on forward paths involving runtime exceptions). - -Note that a check such as
- NP: Value is null and guaranteed to be dereferenced on exception path (NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH)- - -- There is a statement or branch on an exception path - that if executed guarantees that - a value is null at this point, and that - value that is guaranteed to be dereferenced - (except on forward paths involving runtime exceptions). - - - -NP: Method call passes null to a nonnull parameter (NP_NONNULL_PARAM_VIOLATION)- - -- This method passes a null value as the parameter of a method which - must be nonnull. Either this parameter has been explicitly marked - as @Nonnull, or analysis has determined that this parameter is - always dereferenced. - - - -NP: Method may return null, but is declared @NonNull (NP_NONNULL_RETURN_VIOLATION)- - -- This method may return a null value, but the method (or a superclass method - which it overrides) is declared to return @NonNull. - - - -NP: A known null value is checked to see if it is an instance of a type (NP_NULL_INSTANCEOF)- - --This instanceof test will always return false, since the value being checked is guaranteed to be null. -Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. - - - -NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)- - - There is a branch of statement that, if executed, guarantees that
-a null value will be dereferenced, which
-would generate a NP: Possible null pointer dereference in method on exception path (NP_NULL_ON_SOME_PATH_EXCEPTION)- - - A reference value which is null on some exception control path is
-dereferenced here. This may lead to a Also note that FindBugs considers the default case of a switch statement to -be an exception path, since the default case is often infeasible. - - -NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF)- - -- This method call passes a null value for a nonnull method parameter. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS)- - -- A possibly-null value is passed at a call site where all known - target methods require the parameter to be nonnull. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Non-virtual method call passes null for nonnull parameter (NP_NULL_PARAM_DEREF_NONVIRTUAL)- - -- A possibly-null value is passed to a nonnull method parameter. - Either the parameter is annotated as a parameter that should - always be nonnull, or analysis has shown that it will always be - dereferenced. - - - -NP: Store of null value into field annotated NonNull (NP_STORE_INTO_NONNULL_FIELD)- - -A value that could be null is stored into a field that has been annotated as NonNull. - - -NP: Read of unwritten field (NP_UNWRITTEN_FIELD)- - -The program is dereferencing a field that does not seem to ever have a non-null value written to it. -Unless the field is initialized via some mechanism not seen by the analysis, -dereferencing this value will generate a null pointer exception. - - - -Nm: Class defines equal(Object); should it be equals(Object)? (NM_BAD_EQUAL)- - - This class defines a method Nm: Class defines hashcode(); should it be hashCode()? (NM_LCASE_HASHCODE)- - - This class defines a method called Nm: Class defines tostring(); should it be toString()? (NM_LCASE_TOSTRING)- - - This class defines a method called Nm: Apparent method/constructor confusion (NM_METHOD_CONSTRUCTOR_CONFUSION)- - -This regular method has the same name as the class it is defined in. It is likely that this was intended to be a constructor. - If it was intended to be a constructor, remove the declaration of a void return value. - If you had accidently defined this method, realized the mistake, defined a proper constructor - but can't get rid of this method due to backwards compatibility, deprecate the method. - - - -Nm: Very confusing method names (NM_VERY_CONFUSING)- - -The referenced methods have names that differ only by capitalization. -This is very confusing because if the capitalization were -identical then one of the methods would override the other. - - - -Nm: Method doesn't override method in superclass due to wrong package for parameter (NM_WRONG_PACKAGE)- - -The method in the subclass doesn't override a similar method in a superclass because the type of a parameter doesn't exactly match -the type of the corresponding parameter in the superclass. For example, if you have: - -
-
-
-The QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)- - -- This method assigns a literal boolean value (true or false) to a boolean variable inside - an if or while expression. Most probably this was supposed to be a boolean comparison using - ==, not an assignment using =. - - - -RC: Suspicious reference comparison (RC_REF_COMPARISON)- - -This method compares two reference values using the == or != operator, -where the correct way to compare instances of this type is generally -with the equals() method. -It is possible to create distinct instances that are equal but do not compare as == since -they are different objects. -Examples of classes which should generally -not be compared by reference are java.lang.Integer, java.lang.Float, etc. - - -RCN: Nullcheck of value previously dereferenced (RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE)- - -A value is checked here to see whether it is null, but this value can't -be null because it was previously dereferenced and if it were null a null pointer -exception would have occurred at the earlier dereference. -Essentially, this code and the previous dereference -disagree as to whether this value is allowed to be null. Either the check is redundant -or the previous dereference is erroneous. - - -RE: Invalid syntax for regular expression (RE_BAD_SYNTAX_FOR_REGULAR_EXPRESSION)- - --The code here uses a regular expression that is invalid according to the syntax -for regular expressions. This statement will throw a PatternSyntaxException when -executed. - - - -RE: File.separator used for regular expression (RE_CANT_USE_FILE_SEPARATOR_AS_REGULAR_EXPRESSION)- - -
-The code here uses RE: "." used for regular expression (RE_POSSIBLE_UNINTENDED_PATTERN)- - --A String function is being invoked and "." is being passed -to a parameter that takes a regular expression as an argument. Is this what you intended? -For example -s.replaceAll(".", "/") will return a String in which every -character has been replaced by a / character, -and s.split(".") always returns a zero length array of String. - - - -RV: Random value from 0 to 1 is coerced to the integer 0 (RV_01_TO_INT)- - -A random value from 0 to 1 is being coerced to the integer value 0. You probably
-want to multiple the random value by something else before coercing it to an integer, or use the RV: Bad attempt to compute absolute value of signed 32-bit hashcode (RV_ABSOLUTE_VALUE_OF_HASHCODE)- - - This code generates a hashcode and then computes
-the absolute value of that hashcode. If the hashcode
-is One out of 2^32 strings have a hashCode of Integer.MIN_VALUE, -including "polygenelubricants" "GydZG_" and ""DESIGNING WORKHOUSES". - - - -RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)- - - This code generates a random signed integer and then computes
-the absolute value of that random integer. If the number returned by the random number
-generator is RV: Code checks for specific values returned by compareTo (RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE)- - -This code invoked a compareTo or compare method, and checks to see if the return value is a specific value, -such as 1 or -1. When invoking these methods, you should only check the sign of the result, not for any specific -non-zero value. While many or most compareTo and compare methods only return -1, 0 or 1, some of them -will return other values. - - - RV: Exception created and dropped rather than thrown (RV_EXCEPTION_NOT_THROWN)- - -This code creates an exception (or error) object, but doesn't do anything with it. For example, -something like -
-
-It was probably the intent of the programmer to throw the created exception: -
-
-
-
-RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)- - -The return value of this method should be checked. One common -cause of this warning is to invoke a method on an immutable object, -thinking that it updates the object. For example, in the following code -fragment, ----String dateString = getHeaderField(name); -dateString.trim(); -- the programmer seems to be thinking that the trim() method will update -the String referenced by dateString. But since Strings are immutable, the trim() -function returns a new String value, which is being ignored here. The code -should be corrected to: --- - --String dateString = getHeaderField(name); -dateString = dateString.trim(); -- RpC: Repeated conditional tests (RpC_REPEATED_CONDITIONAL_TEST)- - -The code contains a conditional test is performed twice, one right after the other
-(e.g., SA: Self assignment of field (SA_FIELD_SELF_ASSIGNMENT)- - -This method contains a self assignment of a field; e.g. - -
- int x;
- public void foo() {
- x = x;
- }
-
-Such assignments are useless, and may indicate a logic error or typo. - - -SA: Self comparison of field with itself (SA_FIELD_SELF_COMPARISON)- - -This method compares a field with itself, and may indicate a typo or -a logic error. Make sure that you are comparing the right things. - - - -SA: Nonsensical self computation involving a field (e.g., x & x) (SA_FIELD_SELF_COMPUTATION)- - -This method performs a nonsensical computation of a field with another -reference to the same field (e.g., x&x or x-x). Because of the nature -of the computation, this operation doesn't seem to make sense, -and may indicate a typo or -a logic error. Double check the computation. - - - -SA: Self assignment of local rather than assignment to field (SA_LOCAL_SELF_ASSIGNMENT_INSTEAD_OF_FIELD)- - -This method contains a self assignment of a local variable, and there -is a field with an identical name. -assignment appears to have been ; e.g. -
- int foo;
- public void setFoo(int foo) {
- foo = foo;
- }
-
-The assignment is useless. Did you mean to assign to the field instead? - - -SA: Self comparison of value with itself (SA_LOCAL_SELF_COMPARISON)- - -This method compares a local variable with itself, and may indicate a typo or -a logic error. Make sure that you are comparing the right things. - - - -SA: Nonsensical self computation involving a variable (e.g., x & x) (SA_LOCAL_SELF_COMPUTATION)- - -This method performs a nonsensical computation of a local variable with another -reference to the same variable (e.g., x&x or x-x). Because of the nature -of the computation, this operation doesn't seem to make sense, -and may indicate a typo or -a logic error. Double check the computation. - - - -SF: Dead store due to switch statement fall through (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH)- - -A value stored in the previous switch case is overwritten here due to a switch fall through. It is likely that - you forgot to put a break or return at the end of the previous case. - - - -SF: Dead store due to switch statement fall through to throw (SF_DEAD_STORE_DUE_TO_SWITCH_FALLTHROUGH_TO_THROW)- - -A value stored in the previous switch case is ignored here due to a switch fall through to a place where - an exception is thrown. It is likely that - you forgot to put a break or return at the end of the previous case. - - - -SIC: Deadly embrace of non-static inner class and thread local (SIC_THREADLOCAL_DEADLY_EMBRACE)- - -This class is an inner class, but should probably be a static inner class. - As it is, there is a serious danger of a deadly embrace between the inner class - and the thread local in the outer class. Because the inner class isn't static, - it retains a reference to the outer class. - If the thread local contains a reference to an instance of the inner - class, the inner and outer instance will both be reachable - and not eligible for garbage collection. - - - -SIO: Unnecessary type check done using instanceof operator (SIO_SUPERFLUOUS_INSTANCEOF)- - -Type check performed using the instanceof operator where it can be statically determined whether the object -is of the type requested. - - -SQL: Method attempts to access a prepared statement parameter with index 0 (SQL_BAD_PREPARED_STATEMENT_ACCESS)- - -A call to a setXXX method of a prepared statement was made where the -parameter index is 0. As parameter indexes start at index 1, this is always a mistake. - - -SQL: Method attempts to access a result set field with index 0 (SQL_BAD_RESULTSET_ACCESS)- - -A call to getXXX or updateXXX methods of a result set was made where the -field index is 0. As ResultSet fields start at index 1, this is always a mistake. - - -STI: Unneeded use of currentThread() call, to call interrupted() (STI_INTERRUPTED_ON_CURRENTTHREAD)- - --This method invokes the Thread.currentThread() call, just to call the interrupted() method. As interrupted() is a -static method, is more simple and clear to use Thread.interrupted(). - - - -STI: Static Thread.interrupted() method invoked on thread instance (STI_INTERRUPTED_ON_UNKNOWNTHREAD)- - --This method invokes the Thread.interrupted() method on a Thread object that appears to be a Thread object that is -not the current thread. As the interrupted() method is static, the interrupted method will be called on a different -object than the one the author intended. - - - -Se: Method must be private in order for serialization to work (SE_METHOD_MUST_BE_PRIVATE)- - - This class implements the Se: The readResolve method must not be declared as a static method. (SE_READ_RESOLVE_IS_STATIC)- - -In order for the readResolve method to be recognized by the serialization -mechanism, it must not be declared as a static method. - - - -TQ: Value annotated as carrying a type qualifier used where a value that must not carry that qualifier is required (TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED)- - -- A value specified as carrying a type qualifier annotation is - consumed in a location or locations requiring that the value not - carry that annotation. - - -- More precisely, a value annotated with a type qualifier specifying when=ALWAYS - is guaranteed to reach a use or uses where the same type qualifier specifies when=NEVER. - - -- For example, say that @NonNegative is a nickname for - the type qualifier annotation @Negative(when=When.NEVER). - The following code will generate this warning because - the return statement requires a @NonNegative value, - but receives one that is marked as @Negative. - -
-
-
-
-TQ: Value that might not carry a type qualifier is always used in a way requires that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_ALWAYS_SINK)- - -- A value that is annotated as possibility not being an instance of - the values denoted by the type qualifier, and the value is guaranteed to be used - in a way that requires values denoted by that type qualifier. - - - -TQ: Value that might carry a type qualifier is always used in a way prohibits it from having that type qualifier (TQ_MAYBE_SOURCE_VALUE_REACHES_NEVER_SINK)- - -- A value that is annotated as possibility being an instance of - the values denoted by the type qualifier, and the value is guaranteed to be used - in a way that prohibits values denoted by that type qualifier. - - - -TQ: Value annotated as never carrying a type qualifier used where value carrying that qualifier is required (TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED)- - -- A value specified as not carrying a type qualifier annotation is guaranteed - to be consumed in a location or locations requiring that the value does - carry that annotation. - - -- More precisely, a value annotated with a type qualifier specifying when=NEVER - is guaranteed to reach a use or uses where the same type qualifier specifies when=ALWAYS. - - -- TODO: example - - - -UMAC: Uncallable method defined in anonymous class (UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS)- - -This anonymous class defined a method that is not directly invoked and does not override -a method in a superclass. Since methods in other classes cannot directly invoke methods -declared in an anonymous class, it seems that this method is uncallable. The method -might simply be dead code, but it is also possible that the method is intended to -override a method declared in a superclass, and due to an typo or other error the method does not, -in fact, override the method it is intended to. - - - -UR: Uninitialized read of field in constructor (UR_UNINIT_READ)- - -This constructor reads a field which has not yet been assigned a value. - This is often caused when the programmer mistakenly uses the field instead - of one of the constructor's parameters. - - -UR: Uninitialized read of field method called from constructor of superclass (UR_UNINIT_READ_CALLED_FROM_SUPER_CONSTRUCTOR)- - -This method is invoked in the constructor of of the superclass. At this point, - the fields of the class have not yet initialized. -To make this more concrete, consider the following classes: -abstract class A {
- int hashCode;
- abstract Object getValue();
- A() {
- hashCode = getValue().hashCode();
- }
- }
-class B extends A {
- Object value;
- B(Object v) {
- this.value = v;
- }
- Object getValue() {
- return value;
- }
- }
-When a USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY)- - --The code invokes toString on an (anonymous) array. Calling toString on an array generates a fairly useless result -such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable -String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. - - - -USELESS_STRING: Invocation of toString on an array (DMI_INVOKING_TOSTRING_ON_ARRAY)- - --The code invokes toString on an array, which will generate a fairly useless result -such as [C@16f0472. Consider using Arrays.toString to convert the array into a readable -String that gives the contents of the array. See Programming Puzzlers, chapter 3, puzzle 12. - - - -USELESS_STRING: Array formatted in useless way using format string (VA_FORMAT_STRING_BAD_CONVERSION_FROM_ARRAY)- - -
-One of the arguments being formatted with a format string is an array. This will be formatted
-using a fairly useless format, such as [I@304282, which doesn't actually show the contents
-of the array.
-Consider wrapping the array using UwF: Field only ever set to null (UWF_NULL_FIELD)- - -All writes to this field are of the constant value null, and thus -all reads of the field will return null. -Check for errors, or remove it if it is useless. - - -UwF: Unwritten field (UWF_UNWRITTEN_FIELD)- - -This field is never written. All reads of it will return the default -value. Check for errors (should it have been initialized?), or remove it if it is useless. - - -VA: Primitive array passed to function expecting a variable number of object arguments (VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG)- - --This code passes a primitive array to a function that takes a variable number of object arguments. -This creates an array of length one to hold the primitive array and passes it to the function. - - - -LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)- - -OpenJDK introduces a potential incompatibility. - In particular, the java.util.logging.Logger behavior has - changed. Instead of using strong references, it now uses weak references - internally. That's a reasonable change, but unfortunately some code relies on - the old behavior - when changing logger configuration, it simply drops the - logger reference. That means that the garbage collector is free to reclaim - that memory, which means that the logger configuration is lost. For example, -consider: - - -public static void initLogging() throws Exception {
- Logger logger = Logger.getLogger("edu.umd.cs");
- logger.addHandler(new FileHandler()); // call to change logger configuration
- logger.setUseParentHandlers(false); // another call to change logger configuration
-}
-
-The logger reference is lost at the end of the method (it doesn't -escape the method), so if you have a garbage collection cycle just -after the call to initLogging, the logger configuration is lost -(because Logger only keeps weak references). - -public static void main(String[] args) throws Exception {
- initLogging(); // adds a file handler to the logger
- System.gc(); // logger configuration lost
- Logger.getLogger("edu.umd.cs").info("Some message"); // this isn't logged to the file as expected
-}
-Ulf Ochsenfahrt and Eric Fellheimer - - -OBL: Method may fail to clean up stream or resource (OBL_UNSATISFIED_OBLIGATION)- - -- This method may fail to clean up (close, dispose of) a stream, - database object, or other - resource requiring an explicit cleanup operation. - - -- In general, if a method opens a stream or other resource, - the method should use a try/finally block to ensure that - the stream or resource is cleaned up before the method - returns. - - -- This bug pattern is essentially the same as the - OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE - bug patterns, but is based on a different - (and hopefully better) static analysis technique. - We are interested is getting feedback about the - usefulness of this bug pattern. - To send feedback, either: - -
- In particular, - the false-positive suppression heuristics for this - bug pattern have not been extensively tuned, so - reports about false positives are helpful to us. - - -- See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for - a description of the analysis technique. - - - -OBL: Method may fail to clean up stream or resource on checked exception (OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE)- - -- This method may fail to clean up (close, dispose of) a stream, - database object, or other - resource requiring an explicit cleanup operation. - - -- In general, if a method opens a stream or other resource, - the method should use a try/finally block to ensure that - the stream or resource is cleaned up before the method - returns. - - -- This bug pattern is essentially the same as the - OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE - bug patterns, but is based on a different - (and hopefully better) static analysis technique. - We are interested is getting feedback about the - usefulness of this bug pattern. - To send feedback, either: - -
- In particular, - the false-positive suppression heuristics for this - bug pattern have not been extensively tuned, so - reports about false positives are helpful to us. - - -- See Weimer and Necula, Finding and Preventing Run-Time Error Handling Mistakes, for - a description of the analysis technique. - - - -Dm: Consider using Locale parameterized version of invoked method (DM_CONVERT_CASE)- - -A String is being converted to upper or lowercase, using the platform's default encoding. This may - result in improper conversions when used with international characters. Use the -
versions instead. - - -Dm: Reliance on default encoding (DM_DEFAULT_ENCODING)- - -Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly. - - -DP: Classloaders should only be created inside doPrivileged block (DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED)- - -This code creates a classloader, which needs permission if a security manage is installed. - If this code might be invoked by code that does not - have security permissions, then the classloader creation needs to occur inside a doPrivileged block. - - -DP: Method invoked that should be only be invoked inside a doPrivileged block (DP_DO_INSIDE_DO_PRIVILEGED)- - -This code invokes a method that requires a security permission check. - If this code will be granted security permissions, but might be invoked by code that does not - have security permissions, then the invocation needs to occur inside a doPrivileged block. - - -EI: May expose internal representation by returning reference to mutable object (EI_EXPOSE_REP)- - -Returning a reference to a mutable object value stored in one of the object's fields - exposes the internal representation of the object. - If instances - are accessed by untrusted code, and unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Returning a new copy of the object is better approach in many situations. - - -EI2: May expose internal representation by incorporating reference to mutable object (EI_EXPOSE_REP2)- - -This code stores a reference to an externally mutable object into the - internal representation of the object. - If instances - are accessed by untrusted code, and unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Storing a copy of the object is better approach in many situations. - - -FI: Finalizer should be protected, not public (FI_PUBLIC_SHOULD_BE_PROTECTED)- - - A class's MS: May expose internal static state by storing a mutable object into a static field (EI_EXPOSE_STATIC_REP2)- - -This code stores a reference to an externally mutable object into a static - field. - If unchecked changes to - the mutable object would compromise security or other - important properties, you will need to do something different. - Storing a copy of the object is better approach in many situations. - - -MS: Field isn't final and can't be protected from malicious code (MS_CANNOT_BE_FINAL)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - Unfortunately, the way the field is used doesn't allow - any easy fix to this problem. - - -MS: Public static method may expose internal representation by returning array (MS_EXPOSE_REP)- - -A public static method returns a reference to - an array that is part of the static state of the class. - Any code that calls this method can freely modify - the underlying array. - One fix is to return a copy of the array. - - -MS: Field should be both final and package protected (MS_FINAL_PKGPROTECT)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - The field could be made package protected and/or made final - to avoid - this vulnerability. - - -MS: Field is a mutable array (MS_MUTABLE_ARRAY)- - -A final static field references an array - and can be accessed by malicious code or - by accident from another package. - This code can freely modify the contents of the array. - - -MS: Field is a mutable Hashtable (MS_MUTABLE_HASHTABLE)- - -A final static field references a Hashtable - and can be accessed by malicious code or - by accident from another package. - This code can freely modify the contents of the Hashtable. - - -MS: Field should be moved out of an interface and made package protected (MS_OOI_PKGPROTECT)- - -- A final static field that is -defined in an interface references a mutable - object such as an array or hashtable. - This mutable object could - be changed by malicious code or - by accident from another package. - To solve this, the field needs to be moved to a class - and made package protected - to avoid - this vulnerability. - - -MS: Field should be package protected (MS_PKGPROTECT)- - -A mutable static field could be changed by malicious code or - by accident. - The field could be made package protected to avoid - this vulnerability. - - -MS: Field isn't final but should be (MS_SHOULD_BE_FINAL)- - -- A mutable static field could be changed by malicious code or - by accident from another package. - The field could be made final to avoid - this vulnerability. - - -AT: Sequence of calls to concurrent abstraction may not be atomic (AT_OPERATION_SEQUENCE_ON_CONCURRENT_ABSTRACTION)- - -This code contains a sequence of calls to a concurrent abstraction - (such as a concurrent hash map). - These calls will not be executed atomically. - - - DC: Possible double check of field (DC_DOUBLECHECK)- - -This method may contain an instance of double-checked locking. - This idiom is not correct according to the semantics of the Java memory - model. For more information, see the web page - http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html. - - -DL: Synchronization on Boolean (DL_SYNCHRONIZATION_ON_BOOLEAN)- - -The code synchronizes on a boxed primitive constant, such as an Boolean. -
-private static Boolean inited = Boolean.FALSE;
-...
- synchronized(inited) {
- if (!inited) {
- init();
- inited = Boolean.TRUE;
- }
- }
-...
-
-
-Since there normally exist only two Boolean objects, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness -and possible deadlock -See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - -DL: Synchronization on boxed primitive (DL_SYNCHRONIZATION_ON_BOXED_PRIMITIVE)- - -The code synchronizes on a boxed primitive constant, such as an Integer. -
-private static Integer count = 0;
-...
- synchronized(count) {
- count++;
- }
-...
-
-
-Since Integer objects can be cached and shared, -this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness -and possible deadlock -See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - -DL: Synchronization on interned String (DL_SYNCHRONIZATION_ON_SHARED_CONSTANT)- - -The code synchronizes on interned String. -
-private static String LOCK = "LOCK";
-...
- synchronized(LOCK) { ...}
-...
-
-
-Constant Strings are interned and shared across all other classes loaded by the JVM. Thus, this could -is locking on something that other code might also be locking. This could result in very strange and hard to diagnose -blocking and deadlock behavior. See http://www.javalobby.org/java/forums/t96352.html and http://jira.codehaus.org/browse/JETTY-352. - See CERT CON08-J. Do not synchronize on objects that may be reused for more information. - - - -DL: Synchronization on boxed primitive values (DL_SYNCHRONIZATION_ON_UNSHARED_BOXED_PRIMITIVE)- - -The code synchronizes on an apparently unshared boxed primitive, -such as an Integer. -
-private static final Integer fileLock = new Integer(1);
-...
- synchronized(fileLock) {
- .. do something ..
- }
-...
-
-
-It would be much better, in this code, to redeclare fileLock as - -private static final Object fileLock = new Object(); --The existing code might be OK, but it is confusing and a -future refactoring, such as the "Remove Boxing" refactoring in IntelliJ, -might replace this with the use of an interned Integer object shared -throughout the JVM, leading to very confusing behavior and potential deadlock. - - - - Dm: Monitor wait() called on Condition (DM_MONITOR_WAIT_ON_CONDITION)- - -
- This method calls Dm: A thread was created using the default empty run method (DM_USELESS_THREAD)- - -This method creates a thread without specifying a run method either by deriving from the Thread class, or - by passing a Runnable object. This thread, then, does nothing but waste time. - - - -ESync: Empty synchronized block (ESync_EMPTY_SYNC)- - -The code contains an empty synchronized block: -
-synchronized() {}
-
-Empty synchronized blocks are far more subtle and hard to use correctly -than most people recognize, and empty synchronized blocks -are almost never a better solution -than less contrived solutions. - - - -IS: Inconsistent synchronization (IS2_INCONSISTENT_SYNC)- - -The fields of this class appear to be accessed inconsistently with respect - to synchronization. This bug report indicates that the bug pattern detector - judged that - -
A typical bug matching this bug pattern is forgetting to synchronize - one of the methods in a class that is intended to be thread-safe. - -You can select the nodes labeled "Unsynchronized access" to show the - code locations where the detector believed that a field was accessed - without synchronization. - -Note that there are various sources of inaccuracy in this detector; - for example, the detector cannot statically detect all situations in which - a lock is held. Also, even when the detector is accurate in - distinguishing locked vs. unlocked accesses, the code in question may still - be correct. - - - -IS: Field not guarded against concurrent access (IS_FIELD_NOT_GUARDED)- - -This field is annotated with net.jcip.annotations.GuardedBy, -but can be accessed in a way that seems to violate the annotation. - - -JLM: Synchronization performed on Lock (JLM_JSR166_LOCK_MONITORENTER)- - - This method performs synchronization an object that implements
-java.util.concurrent.locks.Lock. Such an object is locked/unlocked
-using
- JLM: Synchronization performed on util.concurrent instance (JLM_JSR166_UTILCONCURRENT_MONITORENTER)- - - This method performs synchronization an object that is an instance of
-a class from the java.util.concurrent package (or its subclasses). Instances
-of these classes have their own concurrency control mechanisms that are orthogonal to
-the synchronization provided by the Java keyword Such code may be correct, but should be carefully reviewed and documented, -and may confuse people who have to maintain the code at a later date. - - - -JLM: Using monitor style wait methods on util.concurrent abstraction (JML_JSR166_CALLING_WAIT_RATHER_THAN_AWAIT)- - - This method calls
- LI: Incorrect lazy initialization of static field (LI_LAZY_INIT_STATIC)- - -This method contains an unsynchronized lazy initialization of a non-volatile static field. -Because the compiler or processor may reorder instructions, -threads are not guaranteed to see a completely initialized object, -if the method can be called by multiple threads. -You can make the field volatile to correct the problem. -For more information, see the -Java Memory Model web site. - - - -LI: Incorrect lazy initialization and update of static field (LI_LAZY_INIT_UPDATE_STATIC)- - -This method contains an unsynchronized lazy initialization of a static field. -After the field is set, the object stored into that location is further updated or accessed. -The setting of the field is visible to other threads as soon as it is set. If the -futher accesses in the method that set the field serve to initialize the object, then -you have a very serious multithreading bug, unless something else prevents -any other thread from accessing the stored object until it is fully initialized. - -Even if you feel confident that the method is never called by multiple -threads, it might be better to not set the static field until the value -you are setting it to is fully populated/initialized. - - - ML: Synchronization on field in futile attempt to guard that field (ML_SYNC_ON_FIELD_TO_GUARD_CHANGING_THAT_FIELD)- - -This method synchronizes on a field in what appears to be an attempt -to guard against simultaneous updates to that field. But guarding a field -gets a lock on the referenced object, not on the field. This may not -provide the mutual exclusion you need, and other threads might -be obtaining locks on the referenced objects (for other purposes). An example -of this pattern would be: - -
-private Long myNtfSeqNbrCounter = new Long(0);
-private Long getNotificationSequenceNumber() {
- Long result = null;
- synchronized(myNtfSeqNbrCounter) {
- result = new Long(myNtfSeqNbrCounter.longValue() + 1);
- myNtfSeqNbrCounter = new Long(result.longValue());
- }
- return result;
- }
-
-
-
-
-
-
-ML: Method synchronizes on an updated field (ML_SYNC_ON_UPDATED_FIELD)- - -This method synchronizes on an object - referenced from a mutable field. - This is unlikely to have useful semantics, since different -threads may be synchronizing on different objects. - - -MSF: Mutable servlet field (MSF_MUTABLE_SERVLET_FIELD)- - -A web server generally only creates one instance of servlet or jsp class (i.e., treats -the class as a Singleton), -and will -have multiple threads invoke methods on that instance to service multiple -simultaneous requests. -Thus, having a mutable instance field generally creates race conditions. - - - MWN: Mismatched notify() (MWN_MISMATCHED_NOTIFY)- - - This method calls Object.notify() or Object.notifyAll() without obviously holding a lock
-on the object. Calling notify() or notifyAll() without a lock held will result in
-an MWN: Mismatched wait() (MWN_MISMATCHED_WAIT)- - - This method calls Object.wait() without obviously holding a lock
-on the object. Calling wait() without a lock held will result in
-an NN: Naked notify (NN_NAKED_NOTIFY)- - - A call to This bug does not necessarily indicate an error, since the change to - mutable object state may have taken place in a method which then called - the method containing the notification. - - -NP: Synchronize and null check on the same field. (NP_SYNC_AND_NULL_CHECK_FIELD)- - -Since the field is synchronized on, it seems not likely to be null. -If it is null and then synchronized on a NullPointerException will be -thrown and the check would be pointless. Better to synchronize on -another field. - - - -No: Using notify() rather than notifyAll() (NO_NOTIFY_NOT_NOTIFYALL)- - - This method calls RS: Class's readObject() method is synchronized (RS_READOBJECT_SYNC)- - - This serializable class defines a RV: Return value of putIfAbsent ignored, value passed to putIfAbsent reused (RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED)- - - TheputIfAbsent method is typically used to ensure that a
- single value is associated with a given key (the first value for which put
- if absent succeeds).
- If you ignore the return value and retain a reference to the value passed in,
- you run the risk of retaining a value that is not the one that is associated with the key in the map.
- If it matters which one you use and you use the one that isn't stored in the map,
- your program will behave incorrectly.
-
-
-Ru: Invokes run on a thread (did you mean to start it instead?) (RU_INVOKE_RUN)- - - This method explicitly invokes SC: Constructor invokes Thread.start() (SC_START_IN_CTOR)- - -The constructor starts a thread. This is likely to be wrong if - the class is ever extended/subclassed, since the thread will be started - before the subclass constructor is started. - - -SP: Method spins on field (SP_SPIN_ON_FIELD)- - -This method spins in a loop which reads a field. The compiler - may legally hoist the read out of the loop, turning the code into an - infinite loop. The class should be changed so it uses proper - synchronization (including wait and notify calls). - - -STCAL: Call to static Calendar (STCAL_INVOKE_ON_STATIC_CALENDAR_INSTANCE)- - -Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. -The detector has found a call to an instance of Calendar that has been obtained via a static -field. This looks suspicous. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Call to static DateFormat (STCAL_INVOKE_ON_STATIC_DATE_FORMAT_INSTANCE)- - -As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. -The detector has found a call to an instance of DateFormat that has been obtained via a static -field. This looks suspicous. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Static Calendar field (STCAL_STATIC_CALENDAR_INSTANCE)- - -Even though the JavaDoc does not contain a hint about it, Calendars are inherently unsafe for multihtreaded use. -Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the -application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see -random ArrayIndexOutOfBoundsExceptions or IndexOutOfBoundsExceptions in sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate(). -You may also experience serialization problems. -Using an instance field is recommended. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -STCAL: Static DateFormat (STCAL_STATIC_SIMPLE_DATE_FORMAT_INSTANCE)- - -As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. -Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the -application. -You may also experience serialization problems. -Using an instance field is recommended. -For more information on this see Sun Bug #6231579 -and Sun Bug #6178997. - - -SWL: Method calls Thread.sleep() with a lock held (SWL_SLEEP_WITH_LOCK_HELD)- - -- This method calls Thread.sleep() with a lock held. This may result - in very poor performance and scalability, or a deadlock, since other threads may - be waiting to acquire the lock. It is a much better idea to call - wait() on the lock, which releases the lock and allows other threads - to run. - - - -TLW: Wait with two locks held (TLW_TWO_LOCK_WAIT)- - -Waiting on a monitor while two locks are held may cause - deadlock. - - Performing a wait only releases the lock on the object - being waited on, not any other locks. - -This not necessarily a bug, but is worth examining - closely. - - -UG: Unsynchronized get method, synchronized set method (UG_SYNC_SET_UNSYNC_GET)- - -This class contains similarly-named get and set - methods where the set method is synchronized and the get method is not. - This may result in incorrect behavior at runtime, as callers of the get - method will not necessarily see a consistent state for the object. - The get method should be made synchronized. - - -UL: Method does not release lock on all paths (UL_UNRELEASED_LOCK)- - - This method acquires a JSR-166 (
- Lock l = ...;
- l.lock();
- try {
- // do something
- } finally {
- l.unlock();
- }
-
-
-
-UL: Method does not release lock on all exception paths (UL_UNRELEASED_LOCK_EXCEPTION_PATH)- - - This method acquires a JSR-166 (
- Lock l = ...;
- l.lock();
- try {
- // do something
- } finally {
- l.unlock();
- }
-
-
-
-UW: Unconditional wait (UW_UNCOND_WAIT)- - - This method contains a call to VO: An increment to a volatile field isn't atomic (VO_VOLATILE_INCREMENT)- - -This code increments a volatile field. Increments of volatile fields aren't -atomic. If more than one thread is incrementing the field at the same time, -increments could be lost. - - - -VO: A volatile reference to an array doesn't treat the array elements as volatile (VO_VOLATILE_REFERENCE_TO_ARRAY)- - -This declares a volatile reference to an array, which might not be what -you want. With a volatile reference to an array, reads and writes of -the reference to the array are treated as volatile, but the array elements -are non-volatile. To get volatile array elements, you will need to use -one of the atomic array classes in java.util.concurrent (provided -in Java 5.0). - - -WL: Synchronization on getClass rather than class literal (WL_USING_GETCLASS_RATHER_THAN_CLASS_LITERAL)- - -
- This instance method synchronizes on
- private static final String base = "label";
- private static int nameCounter = 0;
- String constructComponentName() {
- synchronized (getClass()) {
- return base + nameCounter++;
- }
- }
-
- Subclasses of
- private static final String base = "label";
- private static int nameCounter = 0;
- String constructComponentName() {
- synchronized (Label.class) {
- return base + nameCounter++;
- }
- }
-
- Bug pattern contributed by Jason Mehrens - - -WS: Class's writeObject() method is synchronized but nothing else is (WS_WRITEOBJECT_SYNC)- - - This class has a Wa: Condition.await() not in loop (WA_AWAIT_NOT_IN_LOOP)- - - This method contains a call to Wa: Wait not in loop (WA_NOT_IN_LOOP)- - - This method contains a call to Bx: Primitive value is boxed and then immediately unboxed (BX_BOXING_IMMEDIATELY_UNBOXED)- - -A primitive is boxed, and then immediately unboxed. This probably is due to a manual - boxing in a place where an unboxed value is required, thus forcing the compiler -to immediately undo the work of the boxing. - - - -Bx: Primitive value is boxed then unboxed to perform primitive coercion (BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION)- - -A primitive boxed value constructed and then immediately converted into a different primitive type
-(e.g., Bx: Boxed value is unboxed and then immediately reboxed (BX_UNBOXING_IMMEDIATELY_REBOXED)- - -A boxed value is unboxed and then immediately reboxed. - - - -Bx: Method allocates a boxed primitive just to call toString (DM_BOXED_PRIMITIVE_TOSTRING)- - -A boxed primitive is allocated just to call toString(). It is more effective to just use the static - form of toString which takes the primitive value. So, -
Bx: Method invokes inefficient floating-point Number constructor; use static valueOf instead (DM_FP_NUMBER_CTOR)- - -
- Using
- Unless the class must be compatible with JVMs predating Java 1.5,
- use either autoboxing or the Bx: Method invokes inefficient Number constructor; use static valueOf instead (DM_NUMBER_CTOR)- - -
- Using
- Values between -128 and 127 are guaranteed to have corresponding cached instances
- and using
- Unless the class must be compatible with JVMs predating Java 1.5,
- use either autoboxing or the Dm: The equals and hashCode methods of URL are blocking (DMI_BLOCKING_METHODS_ON_URL)- - - The equals and hashCode
-method of URL perform domain name resolution, this can result in a big performance hit.
-See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
-Consider using Dm: Maps and sets of URLs can be performance hogs (DMI_COLLECTION_OF_URLS)- - - This method or field is or uses a Map or Set of URLs. Since both the equals and hashCode
-method of URL perform domain name resolution, this can result in a big performance hit.
-See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html for more information.
-Consider using Dm: Method invokes inefficient Boolean constructor; use Boolean.valueOf(...) instead (DM_BOOLEAN_CTOR)- - - Creating new instances of Dm: Explicit garbage collection; extremely dubious except in benchmarking code (DM_GC)- - -Code explicitly invokes garbage collection. - Except for specific use in benchmarking, this is very dubious. -In the past, situations where people have explicitly invoked - the garbage collector in routines such as close or finalize methods - has led to huge performance black holes. Garbage collection - can be expensive. Any situation that forces hundreds or thousands - of garbage collections will bring the machine to a crawl. - - -Dm: Method allocates an object, only to get the class object (DM_NEW_FOR_GETCLASS)- - -This method allocates an object just to call getClass() on it, in order to - retrieve the Class object for it. It is simpler to just access the .class property of the class. - - -Dm: Use the nextInt method of Random rather than nextDouble to generate a random integer (DM_NEXTINT_VIA_NEXTDOUBLE)- - -If The argument to nextInt must be positive. If, for example, you want to generate a random
-value from -99 to 0, use Dm: Method invokes inefficient new String(String) constructor (DM_STRING_CTOR)- - - Using the Dm: Method invokes toString() method on a String (DM_STRING_TOSTRING)- - - Calling Dm: Method invokes inefficient new String() constructor (DM_STRING_VOID_CTOR)- - - Creating a new HSC: Huge string constants is duplicated across multiple class files (HSC_HUGE_SHARED_STRING_CONSTANT)- - -- A large String constant is duplicated across multiple class files. - This is likely because a final field is initialized to a String constant, and the Java language - mandates that all references to a final field from other classes be inlined into -that classfile. See JDK bug 6447475 - for a description of an occurrence of this bug in the JDK and how resolving it reduced - the size of the JDK by 1 megabyte. - - - -ITA: Method uses toArray() with zero-length array argument (ITA_INEFFICIENT_TO_ARRAY)- - - This method uses the toArray() method of a collection derived class, and passes
-in a zero-length prototype array argument. It is more efficient to use
- SBSC: Method concatenates strings using + in a loop (SBSC_USE_STRINGBUFFER_CONCATENATION)- - -The method seems to be building a String using concatenation in a loop. -In each iteration, the String is converted to a StringBuffer/StringBuilder, - appended to, and converted back to a String. - This can lead to a cost quadratic in the number of iterations, - as the growing string is recopied in each iteration. - -Better performance can be obtained by using -a StringBuffer (or StringBuilder in Java 1.5) explicitly. - -For example: -
- // This is bad
- String s = "";
- for (int i = 0; i < field.length; ++i) {
- s = s + field[i];
- }
-
- // This is better
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < field.length; ++i) {
- buf.append(field[i]);
- }
- String s = buf.toString();
-
-
-
-SIC: Should be a static inner class (SIC_INNER_SHOULD_BE_STATIC)- - -This class is an inner class, but does not use its embedded reference - to the object which created it. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made static. - - - -SIC: Could be refactored into a named static inner class (SIC_INNER_SHOULD_BE_STATIC_ANON)- - -This class is an inner class, but does not use its embedded reference - to the object which created it. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made into a static inner class. Since anonymous inner -classes cannot be marked as static, doing this will require refactoring -the inner class so that it is a named inner class. - - -SIC: Could be refactored into a static inner class (SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS)- - -This class is an inner class, but does not use its embedded reference - to the object which created it except during construction of the -inner object. This reference makes the instances - of the class larger, and may keep the reference to the creator object - alive longer than necessary. If possible, the class should be - made into a static inner class. Since the reference to the - outer object is required during construction of the inner instance, - the inner class will need to be refactored so as to - pass a reference to the outer instance to the constructor - for the inner class. - - -SS: Unread field: should this field be static? (SS_SHOULD_BE_STATIC)- - -This class contains an instance final field that - is initialized to a compile-time static value. - Consider making the field static. - - -UM: Method calls static Math class method on a constant value (UM_UNNECESSARY_MATH)- - -This method uses a static method from java.lang.Math on a constant value. This method's -result in this case, can be determined statically, and is faster and sometimes more accurate to -just use the constant. Methods detected are: - -
UPM: Private method is never called (UPM_UNCALLED_PRIVATE_METHOD)- - -This private method is never called. Although it is -possible that the method will be invoked through reflection, -it is more likely that the method is never used, and should be -removed. - - - -UrF: Unread field (URF_UNREAD_FIELD)- - -This field is never read. Consider removing it from the class. - - -UuF: Unused field (UUF_UNUSED_FIELD)- - -This field is never used. Consider removing it from the class. - - -WMI: Inefficient use of keySet iterator instead of entrySet iterator (WMI_WRONG_MAP_ITERATOR)- - -This method accesses the value of a Map entry, using a key that was retrieved from -a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the -Map.get(key) lookup. - - -Dm: Hardcoded constant database password (DMI_CONSTANT_DB_PASSWORD)- - -This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can - easily learn the password. - - - - -Dm: Empty database password (DMI_EMPTY_DB_PASSWORD)- - -This code creates a database connect using a blank or empty password. This indicates that the database is not protected by a password. - - - - -HRS: HTTP cookie formed from untrusted input (HRS_REQUEST_PARAMETER_TO_COOKIE)- - -This code constructs an HTTP Cookie using an untrusted HTTP parameter. If this cookie is added to an HTTP response, it will allow a HTTP response splitting -vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting -for more information. -FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. -If FindBugs found any, you almost certainly have more -vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -HRS: HTTP Response splitting vulnerability (HRS_REQUEST_PARAMETER_TO_HTTP_HEADER)- - -This code directly writes an HTTP parameter to an HTTP header, which allows for a HTTP response splitting -vulnerability. See http://en.wikipedia.org/wiki/HTTP_response_splitting -for more information. -FindBugs looks only for the most blatant, obvious cases of HTTP response splitting. -If FindBugs found any, you almost certainly have more -vulnerabilities that FindBugs doesn't report. If you are concerned about HTTP response splitting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -SQL: Nonconstant string passed to execute method on an SQL statement (SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE)- - -The method invokes the execute method on an SQL statement with a String that seems -to be dynamically generated. Consider using -a prepared statement instead. It is more efficient and less vulnerable to -SQL injection attacks. - - - -SQL: A prepared statement is generated from a nonconstant String (SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)- - -The code creates an SQL prepared statement from a nonconstant String. -If unchecked, tainted data from a user is used in building this String, SQL injection could -be used to make the prepared statement do something unexpected and undesirable. - - - -XSS: JSP reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_JSP_WRITER)- - -This code directly writes an HTTP parameter to JSP output, which allows for a cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - -XSS: Servlet reflected cross site scripting vulnerability in error page (XSS_REQUEST_PARAMETER_TO_SEND_ERROR)- - -This code directly writes an HTTP parameter to a Server error page (using HttpServletResponse.sendError). Echoing this untrusted input allows -for a reflected cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -XSS: Servlet reflected cross site scripting vulnerability (XSS_REQUEST_PARAMETER_TO_SERVLET_WRITER)- - -This code directly writes an HTTP parameter to Servlet output, which allows for a reflected cross site scripting -vulnerability. See http://en.wikipedia.org/wiki/Cross-site_scripting -for more information. -FindBugs looks only for the most blatant, obvious cases of cross site scripting. -If FindBugs found any, you almost certainly have more cross site scripting -vulnerabilities that FindBugs doesn't report. If you are concerned about cross site scripting, you should seriously -consider using a commercial static analysis or pen-testing tool. - - - - -BC: Questionable cast to abstract collection (BC_BAD_CAST_TO_ABSTRACT_COLLECTION)- - -
-This code casts a Collection to an abstract collection
-(such as BC: Questionable cast to concrete collection (BC_BAD_CAST_TO_CONCRETE_COLLECTION)- - --This code casts an abstract collection (such as a Collection, List, or Set) -to a specific concrete implementation (such as an ArrayList or HashSet). -This might not be correct, and it may make your code fragile, since -it makes it harder to switch to other concrete implementations at a future -point. Unless you have a particular reason to do so, just use the abstract -collection class. - - - -BC: Unchecked/unconfirmed cast (BC_UNCONFIRMED_CAST)- - --This cast is unchecked, and not all instances of the type casted from can be cast to -the type it is being cast to. Ensure that your program logic ensures that this -cast will not fail. - - - -BC: instanceof will always return true (BC_VACUOUS_INSTANCEOF)- - --This instanceof test will always return true (unless the value being tested is null). -Although this is safe, make sure it isn't -an indication of some misunderstanding or some other logic error. -If you really want to test the value for being null, perhaps it would be clearer to do -better to do a null test rather than an instanceof test. - - - -BSHIFT: Unsigned right shift cast to short/byte (ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT)- - --The code performs an unsigned right shift, whose result is then -cast to a short or byte, which discards the upper bits of the result. -Since the upper bits are discarded, there may be no difference between -a signed and unsigned right shift (depending upon the size of the shift). - - - -CI: Class is final but declares protected field (CI_CONFUSED_INHERITANCE)- - -- This class is declared to be final, but declares fields to be protected. Since the class - is final, it can not be derived from, and the use of protected is confusing. The access - modifier for the field should be changed to private or public to represent the true - use for the field. - - - -DB: Method uses the same code for two branches (DB_DUPLICATE_BRANCHES)- - -- This method uses the same code to implement two branches of a conditional branch. - Check to ensure that this isn't a coding mistake. - - - -DB: Method uses the same code for two switch clauses (DB_DUPLICATE_SWITCH_CLAUSES)- - -- This method uses the same code to implement two clauses of a switch statement. - This could be a case of duplicate code, but it might also indicate - a coding mistake. - - - -DLS: Dead store to local variable (DLS_DEAD_LOCAL_STORE)- - --This instruction assigns a value to a local variable, -but the value is not read or used in any subsequent instruction. -Often, this indicates an error, because the value computed is never -used. - --Note that Sun's javac compiler often generates dead stores for -final local variables. Because FindBugs is a bytecode-based tool, -there is no easy way to eliminate these false positives. - - - -DLS: Useless assignment in return statement (DLS_DEAD_LOCAL_STORE_IN_RETURN)- - --This statement assigns to a local variable in a return statement. This assignment -has effect. Please verify that this statement does the right thing. - - - -DLS: Dead store of null to local variable (DLS_DEAD_LOCAL_STORE_OF_NULL)- - -The code stores null into a local variable, and the stored value is not -read. This store may have been introduced to assist the garbage collector, but -as of Java SE 6.0, this is no longer needed or useful. - - - -DLS: Dead store to local variable that shadows field (DLS_DEAD_LOCAL_STORE_SHADOWS_FIELD)- - --This instruction assigns a value to a local variable, -but the value is not read or used in any subsequent instruction. -Often, this indicates an error, because the value computed is never -used. There is a field with the same name as the local variable. Did you -mean to assign to that variable instead? - - - -DMI: Code contains a hard coded reference to an absolute pathname (DMI_HARDCODED_ABSOLUTE_FILENAME)- - -This code constructs a File object using a hard coded to an absolute pathname
-(e.g., DMI: Non serializable object written to ObjectOutput (DMI_NONSERIALIZABLE_OBJECT_WRITTEN)- - --This code seems to be passing a non-serializable object to the ObjectOutput.writeObject method. -If the object is, indeed, non-serializable, an error will result. - - - -DMI: Invocation of substring(0), which returns the original value (DMI_USELESS_SUBSTRING)- - --This code invokes substring(0) on a String, which returns the original value. - - - -Dm: Thread passed where Runnable expected (DMI_THREAD_PASSED_WHERE_RUNNABLE_EXPECTED)- - -A Thread object is passed as a parameter to a method where -a Runnable is expected. This is rather unusual, and may indicate a logic error -or cause unexpected behavior. - - - -Eq: Class doesn't override equals in superclass (EQ_DOESNT_OVERRIDE_EQUALS)- - -This class extends a class that defines an equals method and adds fields, but doesn't -define an equals method itself. Thus, equality on instances of this class will -ignore the identity of the subclass and the added fields. Be sure this is what is intended, -and that you don't need to override the equals method. Even if you don't need to override -the equals method, consider overriding it anyway to document the fact -that the equals method for the subclass just return the result of -invoking super.equals(o). - - - -Eq: Unusual equals method (EQ_UNUSUAL)- - - This class doesn't do any of the patterns we recognize for checking that the type of the argument
-is compatible with the type of the FE: Test for floating point equality (FE_FLOATING_POINT_EQUALITY)- - -
- This operation compares two floating point values for equality.
- Because floating point calculations may involve rounding,
- calculated float and double values may not be accurate.
- For values that must be precise, such as monetary values,
- consider using a fixed-precision type such as BigDecimal.
- For values that need not be precise, consider comparing for equality
- within some range, for example:
- FS: Non-Boolean argument formatted using %b format specifier (VA_FORMAT_STRING_BAD_CONVERSION_TO_BOOLEAN)- - --An argument not of type Boolean is being formatted with a %b format specifier. This won't throw an -exception; instead, it will print true for any nonnull value, and false for null. -This feature of format strings is strange, and may not be what you intended. - - - -IA: Ambiguous invocation of either an inherited or outer method (IA_AMBIGUOUS_INVOCATION_OF_INHERITED_OR_OUTER_METHOD)- - -An inner class is invoking a method that could be resolved to either a inherited method or a method defined in an outer class. By the Java semantics, -it will be resolved to invoke the inherited method, but this may not be want -you intend. If you really intend to invoke the inherited method, -invoke it by invoking the method on super (e.g., invoke super.foo(17)), and -thus it will be clear to other readers of your code and to FindBugs -that you want to invoke the inherited method, not the method in the outer class. - - - -IC: Initialization circularity (IC_INIT_CIRCULARITY)- - -A circularity was detected in the static initializers of the two - classes referenced by the bug instance. Many kinds of unexpected - behavior may arise from such circularity. - - -ICAST: integral division result cast to double or float (ICAST_IDIV_CAST_TO_DOUBLE)- - --This code casts the result of an integral division (e.g., int or long division) -operation to double or -float. -Doing division on integers truncates the result -to the integer value closest to zero. The fact that the result -was cast to double suggests that this precision should have been retained. -What was probably meant was to cast one or both of the operands to -double before performing the division. Here is an example: - --- - --int x = 2; -int y = 5; -// Wrong: yields result 0.0 -double value1 = x / y; - -// Right: yields result 0.4 -double value2 = x / (double) y; -- ICAST: Result of integer multiplication cast to long (ICAST_INTEGER_MULTIPLY_CAST_TO_LONG)- - -
-This code performs integer multiply and then converts the result to a long,
-as in:
- IM: Computation of average could overflow (IM_AVERAGE_COMPUTATION_COULD_OVERFLOW)- - -The code computes the average of two integers using either division or signed right shift,
-and then uses the result as the index of an array.
-If the values being averaged are very large, this can overflow (resulting in the computation
-of a negative average). Assuming that the result is intended to be nonnegative, you
-can use an unsigned right shift instead. In other words, rather that using This bug exists in many earlier implementations of binary search and merge sort. -Martin Buchholz found and fixed it -in the JDK libraries, and Joshua Bloch -widely -publicized the bug pattern. - - - -IM: Check for oddness that won't work for negative numbers (IM_BAD_CHECK_FOR_ODD)- - --The code uses x % 2 == 1 to check to see if a value is odd, but this won't work -for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check -for oddness, consider using x & 1 == 1, or x % 2 != 0. - - - -INT: Integer remainder modulo 1 (INT_BAD_REM_BY_1)- - -Any expression (exp % 1) is guaranteed to always return zero. -Did you mean (exp & 1) or (exp % 2) instead? - - - -INT: Vacuous bit mask operation on integer value (INT_VACUOUS_BIT_OPERATION)- - - This is an integer bit operation (and, or, or exclusive or) that doesn't do any useful work
-(e.g., INT: Vacuous comparison of integer value (INT_VACUOUS_COMPARISON)- - -There is an integer comparison that always returns -the same value (e.g., x <= Integer.MAX_VALUE). - - - -MTIA: Class extends Servlet class and uses instance variables (MTIA_SUSPECT_SERVLET_INSTANCE_FIELD)- - -- This class extends from a Servlet class, and uses an instance member variable. Since only - one instance of a Servlet class is created by the J2EE framework, and used in a - multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider - only using method local variables. - - - -MTIA: Class extends Struts Action class and uses instance variables (MTIA_SUSPECT_STRUTS_INSTANCE_FIELD)- - -- This class extends from a Struts Action class, and uses an instance member variable. Since only - one instance of a struts Action class is created by the Struts framework, and used in a - multithreaded way, this paradigm is highly discouraged and most likely problematic. Consider - only using method local variables. Only instance fields that are written outside of a monitor - are reported. - - - -NP: Dereference of the result of readLine() without nullcheck (NP_DEREFERENCE_OF_READLINE_VALUE)- - -The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text -to read, readLine() will return null and dereferencing that will generate a null pointer exception. - - - -NP: Immediate dereference of the result of readLine() (NP_IMMEDIATE_DEREFERENCE_OF_READLINE)- - -The result of invoking readLine() is immediately dereferenced. If there are no more lines of text -to read, readLine() will return null and dereferencing that will generate a null pointer exception. - - - -NP: Load of known null value (NP_LOAD_OF_KNOWN_NULL_VALUE)- - -The variable referenced at this point is known to be null due to an earlier - check against null. Although this is valid, it might be a mistake (perhaps you -intended to refer to a different variable, or perhaps the earlier check to see if the -variable is null should have been a check to see if it was nonnull). - - - -NP: Possible null pointer dereference due to return value of called method (NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)- - - The return value from a method is dereferenced without a null check,
-and the return value of that method is one that should generally be checked
-for null. This may lead to a NP: Possible null pointer dereference on branch that might be infeasible (NP_NULL_ON_SOME_PATH_MIGHT_BE_INFEASIBLE)- - - There is a branch of statement that, if executed, guarantees that
-a null value will be dereferenced, which
-would generate a NP: Parameter must be nonnull but is marked as nullable (NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE)- - -This parameter is always used in a way that requires it to be nonnull, -but the parameter is explicitly annotated as being Nullable. Either the use -of the parameter or the annotation is wrong. - - - -NP: Read of unwritten public or protected field (NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)- - -The program is dereferencing a public or protected -field that does not seem to ever have a non-null value written to it. -Unless the field is initialized via some mechanism not seen by the analysis, -dereferencing this value will generate a null pointer exception. - - - -NS: Potentially dangerous use of non-short-circuit logic (NS_DANGEROUS_NON_SHORT_CIRCUIT)- - -This code seems to be using non-short-circuit logic (e.g., & -or |) -rather than short-circuit logic (&& or ||). In addition, -it seem possible that, depending on the value of the left hand side, you might not -want to evaluate the right hand side (because it would have side effects, could cause an exception -or could be expensive. --Non-short-circuit logic causes both sides of the expression -to be evaluated even when the result can be inferred from -knowing the left-hand side. This can be less efficient and -can result in errors if the left-hand side guards cases -when evaluating the right-hand side can generate an error. - - -See the Java -Language Specification for details - - - - -NS: Questionable use of non-short-circuit logic (NS_NON_SHORT_CIRCUIT)- - -This code seems to be using non-short-circuit logic (e.g., & -or |) -rather than short-circuit logic (&& or ||). -Non-short-circuit logic causes both sides of the expression -to be evaluated even when the result can be inferred from -knowing the left-hand side. This can be less efficient and -can result in errors if the left-hand side guards cases -when evaluating the right-hand side can generate an error. - - See the Java -Language Specification for details - - - - -PZLA: Consider returning a zero length array rather than null (PZLA_PREFER_ZERO_LENGTH_ARRAYS)- - -It is often a better design to -return a length zero array rather than a null reference to indicate that there -are no results (i.e., an empty list of results). -This way, no explicit check for null is needed by clients of the method. - -On the other hand, using null to indicate
-"there is no answer to this question" is probably appropriate.
-For example, QF: Complicated, subtle or wrong increment in for-loop (QF_QUESTIONABLE_FOR_LOOP)- - -Are you sure this for loop is incrementing the correct variable? - It appears that another variable is being initialized and checked - by the for loop. - - - -RCN: Redundant comparison of non-null value to null (RCN_REDUNDANT_COMPARISON_OF_NULL_AND_NONNULL_VALUE)- - -This method contains a reference known to be non-null with another reference -known to be null. - - -RCN: Redundant comparison of two null values (RCN_REDUNDANT_COMPARISON_TWO_NULL_VALUES)- - -This method contains a redundant comparison of two references known to -both be definitely null. - - -RCN: Redundant nullcheck of value known to be non-null (RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE)- - -This method contains a redundant check of a known non-null value against -the constant null. - - -RCN: Redundant nullcheck of value known to be null (RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE)- - -This method contains a redundant check of a known null value against -the constant null. - - -REC: Exception is caught when Exception is not thrown (REC_CATCH_EXCEPTION)- - -- This method uses a try-catch block that catches Exception objects, but Exception is not - thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to - say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception - each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, - masking potential bugs. - - - -RI: Class implements same interface as superclass (RI_REDUNDANT_INTERFACES)- - -- This class declares that it implements an interface that is also implemented by a superclass. - This is redundant because once a superclass implements an interface, all subclasses by default also - implement this interface. It may point out that the inheritance hierarchy has changed since - this class was created, and consideration should be given to the ownership of - the interface's implementation. - - - -RV: Method checks to see if result of String.indexOf is positive (RV_CHECK_FOR_POSITIVE_INDEXOF)- - -The method invokes String.indexOf and checks to see if the result is positive or non-positive. - It is much more typical to check to see if the result is negative or non-negative. It is - positive only if the substring checked for occurs at some place other than at the beginning of - the String. - - -RV: Method discards result of readLine after checking if it is nonnull (RV_DONT_JUST_NULL_CHECK_READLINE)- - -The value returned by readLine is discarded after checking to see if the return -value is non-null. In almost all situations, if the result is non-null, you will want -to use that non-null value. Calling readLine again will give you a different line. - - -RV: Remainder of hashCode could be negative (RV_REM_OF_HASHCODE)- - -This code computes a hashCode, and then computes -the remainder of that value modulo another value. Since the hashCode -can be negative, the result of the remainder operation -can also be negative. - Assuming you want to ensure that the result of your computation is nonnegative,
-you may need to change your code.
-If you know the divisor is a power of 2,
-you can use a bitwise and operator instead (i.e., instead of
-using RV: Remainder of 32-bit signed random integer (RV_REM_OF_RANDOM_INT)- - -This code generates a random signed integer and then computes -the remainder of that value modulo another value. Since the random -number can be negative, the result of the remainder operation -can also be negative. Be sure this is intended, and strongly -consider using the Random.nextInt(int) method instead. - - - -RV: Method ignores return value, is this OK? (RV_RETURN_VALUE_IGNORED_INFERRED)- - -This code calls a method and ignores the return value. The return value
-is the same type as the type the method is invoked on, and from our analysis it looks
-like the return value might be important (e.g., like ignoring the
-return value of We are guessing that ignoring the return value might be a bad idea just from -a simple analysis of the body of the method. You can use a @CheckReturnValue annotation -to instruct FindBugs as to whether ignoring the return value of this method -is important or acceptable. - -Please investigate this closely to decide whether it is OK to ignore the return value. - - - -SA: Double assignment of field (SA_FIELD_DOUBLE_ASSIGNMENT)- - -This method contains a double assignment of a field; e.g. - -
- int x,y;
- public void foo() {
- x = x = 17;
- }
-
-Assigning to a field twice is useless, and may indicate a logic error or typo. - - -SA: Double assignment of local variable (SA_LOCAL_DOUBLE_ASSIGNMENT)- - -This method contains a double assignment of a local variable; e.g. - -
- public void foo() {
- int x,y;
- x = x = 17;
- }
-
-Assigning the same value to a variable twice is useless, and may indicate a logic error or typo. - - -SA: Self assignment of local variable (SA_LOCAL_SELF_ASSIGNMENT)- - -This method contains a self assignment of a local variable; e.g. -
- public void foo() {
- int x = 3;
- x = x;
- }
-
--Such assignments are useless, and may indicate a logic error or typo. - - - -SF: Switch statement found where one case falls through to the next case (SF_SWITCH_FALLTHROUGH)- - -This method contains a switch statement where one case branch will fall through to the next case. - Usually you need to end this case with a break or return. - - -SF: Switch statement found where default case is missing (SF_SWITCH_NO_DEFAULT)- - -This method contains a switch statement where default case is missing. - Usually you need to provide a default case. - - -ST: Write to static field from instance method (ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD)- - -This instance method writes to a static field. This is tricky to get -correct if multiple instances are being manipulated, -and generally bad practice. - - - -Se: private readResolve method not inherited by subclasses (SE_PRIVATE_READ_RESOLVE_NOT_INHERITED)- - -This class defines a private readResolve method. Since it is private, it won't be inherited by subclasses. -This might be intentional and OK, but should be reviewed to ensure it is what is intended. - - - -Se: Transient field of class that isn't Serializable. (SE_TRANSIENT_FIELD_OF_NONSERIALIZABLE_CLASS)- - -The field is marked as transient, but the class isn't Serializable, so marking it as transient -has absolutely no effect. -This may be leftover marking from a previous version of the code in which the class was transient, or -it may indicate a misunderstanding of how serialization works. - - - -TQ: Value required to have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK)- - -- A value is used in a way that requires it to be always be a value denoted by a type qualifier, but - there is an explicit annotation stating that it is not known where the value is required to have that type qualifier. - Either the usage or the annotation is incorrect. - - - -TQ: Value required to not have type qualifier, but marked as unknown (TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK)- - -- A value is used in a way that requires it to be never be a value denoted by a type qualifier, but - there is an explicit annotation stating that it is not known where the value is prohibited from having that type qualifier. - Either the usage or the annotation is incorrect. - - - -UCF: Useless control flow (UCF_USELESS_CONTROL_FLOW)- - - This method contains a useless control flow statement, where
-control flow continues onto the same place regardless of whether or not
-the branch is taken. For example,
-this is caused by having an empty statement
-block for an
- if (argv.length == 0) {
- // TODO: handle this case
- }
-
-
-
-UCF: Useless control flow to next line (UCF_USELESS_CONTROL_FLOW_NEXT_LINE)- - - This method contains a useless control flow statement in which control
-flow follows to the same or following line regardless of whether or not
-the branch is taken.
-Often, this is caused by inadvertently using an empty statement as the
-body of an
- if (argv.length == 1);
- System.out.println("Hello, " + argv[0]);
-
-
-
-UrF: Unread public/protected field (URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD)- - -This field is never read.  -The field is public or protected, so perhaps - it is intended to be used with classes not seen as part of the analysis. If not, -consider removing it from the class. - - -UuF: Unused public or protected field (UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD)- - -This field is never used. -The field is public or protected, so perhaps - it is intended to be used with classes not seen as part of the analysis. If not, -consider removing it from the class. - - -UwF: Field not initialized in constructor but dereferenced without null check (UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)- - -This field is never initialized within any constructor, and is therefore could be null after -the object is constructed. Elsewhere, it is loaded and dereferenced without a null check. -This could be a either an error or a questionable design, since -it means a null pointer exception will be generated if that field is dereferenced -before being initialized. - - - -UwF: Unwritten public or protected field (UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD)- - -No writes were seen to this public/protected field. All reads of it will return the default -value. Check for errors (should it have been initialized?), or remove it if it is useless. - - -XFB: Method directly allocates a specific implementation of xml interfaces (XFB_XML_FACTORY_BYPASS)- - -- This method allocates a specific implementation of an xml interface. It is preferable to use - the supplied factory classes to create these objects so that the implementation can be - changed at runtime. See - -
for details. - - - - -- - Send comments to findbugs@cs.umd.edu - |
-
|
-
-
-
-Contributing to FindBugs- -If you have a bug fix or feature enhancement you would like to contribute, -we would be happy to consider it for inclusion. - -Import FindBugs code as Eclipse projects- -The preferred way to get the FindBugs source code and create the patch is to use Eclipse + SVN. -You can easily import FindBugs code into Eclipse by following the steps described -here: Import Eclipse projects -. - - -Preparing a patch- -The best way to -send an enhancement is to create a patch against the latest code -in the FindBugs Subversion repository -at http://findbugs.googlecode.com/svn/trunk/ -(those people who have been given commit priviledges should use -https://findbugs.googlecode.com/svn/trunk/). - - -To create a patch from Eclipse, please right click the [findbugs] or [findBugsEclipsePlugin] project -and choose [Team | Create Patch...] context menu. - - -Please follow these guidelines when preparing your patch: -
Following these guidelines makes it much easier for us -to incorporate new code. - - How to submit a patch- -Patches may be submitted through the -Patches tracker on the -sourceforge project page. - - - - - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
--FindBugs 1.2 demo and results -- -If you just want to try running FindBugs against your -own code, you can -run FindBugs using Java Webstart. -This will use our new gui under Java 1.5+ and our old gui under Java 1.4. -The new gui provides a number of new features, but requires Java 1.5+. -Both use exactly the same analysis engine. - - This web page provides results of running FindBugs 1.2.0 -against several open source applications. We provide a summary -of the number of bugs we found, as well as a generated HTML listing -of the bugs and -a Java -WebStart demo of the new GUI we've introduced in FindBugs version 1.1, -displaying the warnings and the relevant source. - - - The applications and versions of them we report on -are somewhat arbitrary. In some cases, they are release versions, -in other cases nightly builds. We find lots of bugs in every large code -base we examine; these applications are certainly not the worst we have seen. -I have been allowed to confidentially examine the results of running FindBugs -against several closed commercial code bases by well respected companies; -the results I've seen there are not significantly different from -what I've observed in open source code bases. - - - Experimental details: These results are from running -FindBugs 1.2.0 at standard effort level. Our results do not include -any low priority warnings or any warnings about vulnerabilities to -malicious code. Although we have (repeatedly) manually audited the results, -we haven't manually filtered out false positives from these warnings, -so that you can get a feeling for the quality of the warnings generated -by FindBugs. - Some of the bugs contain audit comments: they are marked as to whether -we thought the warning indicated a bug that should or must be fixed, or whether it was not, in fact, a bug. - In the webstart versions, we've only included the bugs for which -we were able to identify source files. The number of lines of non-commenting source -statements in the table below (KNCSS) is derived from the same files -that we analyzed and in which we report bugs; we actually compute -KNCSS from the classfiles, not the source files. - - Vulnerability disclosure: Thankfully, Java isn't C or C++. Dereferencing -a null pointer or accessing outside the bounds of an array generates a runtime -exception rather than a shell exploit. We do not believe that any of the -warnings here represents a security vulnerability, although we have not audited -them to verify that. These projects are all aware of the existence of -FindBugs, and FindBugs is already open source and available -for use both by developers and attackers, we don't believe that making -these results available constitutes a reckless disclosure. - - - Recommendations: First, review the correctness warnings. - We feel confident that developers -would want to fix most of the high and medium priority correctness warnings we report. -Once you've reviewed those, -you might want to look at some of the other categories. - -In other categories, -such as Bad practice and Dodgy code, we accept more false positives. You -might decide that a pattern bug pattern isn't relevant for your code -base (e.g., you never use Serialization for persistent storage, -so you never care about the fact that you didn't define a serializationUID), -and even for the bug patterns relevant to your code base, -perhaps only a minority will reflect problems serious enough to -convince you to change your code. - - Please be patient The Web start versions not only have to download the applications, - they need to download about 10 megabytes of data and source files. Please - be patient. Sorry we don't have a progress bar for the data and source download; - the ability to remotely download a data and source archive is a little bit of - a hack. We've provided small versions of some of the data sets that include - only the correctness bugs and the source files containing those warnings. The small - datasets are about a quarter of the sizes of the full datasets. - --
KNCSS - Thousands of lines of non-commenting source statements - - Bug categories-
- - Send comments to findbugs@cs.umd.edu - | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-
|
-
-
-
-FindBugs downloads- -This page contains links to downloads -of Findbugs version 2.0.0, -released on 21:17:55 EST, 20 December, 2011. Download links -for all FindBugs versions and files -are available -on the sourceforge download page. - -
|
-
-
-
|
-
-
-
-FindBugs™ Fact Sheet- -FindBugs looks for bugs in Java programs. It is based -on the concept of bug patterns. A bug pattern is a code -idiom that is often an error. Bug patterns arise for a variety -of reasons: - - -
FindBugs uses static analysis to inspect Java bytecode -for occurrences of bug patterns. -Static analysis means that FindBugs can find bugs by simply inspecting -a program's code: executing the program is not necessary. -This makes FindBugs very easy to use: in general, you should be -able to use it to look for bugs in your code within a few minutes of downloading it. -FindBugs works by analyzing Java bytecode (compiled class files), -so you don't even need the program's source code to use it. -Because its analysis is -sometimes imprecise, FindBugs can report false warnings, -which are warnings that do not indicate real errors. -In practice, the rate of false warnings reported by FindBugs -is less than 50%. - - --FindBugs supports a plugin architecture allowing anyone to add new -bug detectors. The publications page -contains links to articles describing how to write a new detector -for FindBugs. If you are familiar with Java bytecode -you can write a new FindBugs detector in as little as a few minutes. - - -FindBugs is free software, available under the terms of the -Lesser GNU Public License. -It is written in Java, and can be run with any virtual machine compatible -with Sun's JDK 1.5. It can analyze programs written for any version -of Java. FindBugs was originally developed by Bill Pugh and David Hovemeyer. -It is maintained by Bill Pugh, and -a team of volunteers. - - -FindBugs uses BCEL to -analyze Java bytecode. -As of version 1.1, FindBugs also supports bug detectors written using -the ASM bytecode framework. -FindBugs uses dom4j -for XML manipulation. - - - -- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-
-
FindBugs 2- -This page describes the major changes in FindBugs 2. We are well aware that the documentation on - the new features in FindBugs 2.0 have not kept up with the implementation. We will be working to - improve the documentation, but don't want to hold up the release any longer to improve the - documentation. -Anyone currently using FindBugs 1.3.9 should find FindBugs 2.0 to largely be a drop-in - replacement that offers better accuracy and performance. - - -- Also check out http://code.google.com/p/findbugs/w/list - for more information about some recent features/changes in FindBugs. - - -The major new features in FindBug 2 are as follows: -
Cloud storage of issue evaluations-For many years, you could store evaluations of FindBugs issues within the XML containing the - analysis results. However, this approach did not work well for a team of distributed developers. - Instead, we now provide a cloud based mechanism for storing this information. We are providing a - free communal cloud (hostied by Google appengine) for storing evaluations of FindBugs issues. You - can set up your own private cloud for storing issues, but at the moment this checking out a copy of - FindBugs, making some modifications and building the cloud storage plugin from source. We hope to - make it easier to have your own private cloud in FindBugs 2.0.1. -We have analyzed several large open source projects, and provide Java web start links to allow - you to view the results. We'd be happy to work with projects to make the results available from a - continuous build: -
FindBugs update checks-- FindBugs now checks to see if a new version of FindBugs or a plugin has been released. We make use - of this check to collect statistics on the operating system, java version, locale and FindBugs entry - point (e.g., ant, command line, GUI). More information is - available, including information about how to disable update checks if your organization has a - policy against allowing the collection of such information. No information about the code being - analyzed is reported. - - - -Plugins-FindBugs 2.0 makes it much easier to customize FindBugs with plugins. -FindBugs looks for plugins in two places: your personal home directory, and in FindBugs home - (plugins installed in your home directory take precedence). In both places, it looks in two places: - the plugin directory, which contains plugins that are enabled by default, and the optionalPlugin - directory, which contains plugins that are disabled by default but can be enabled for a particular - project. -The FindBugs project includes several plugins: -
Performance Improvements/regressions-- In our own testing, we've seen an overall improvement of 9% in - FindBugs performance from 1.3.9 to 2.0.0, with the majority of benchmarks seeing improvements. A - few users have reported significant performance regressions and we are asking - for more information from anyone seeing significant performance regressions. - - -New Bug patterns-
|
-
-
|
-
-
-
-
-
FindBugs™ - Find Bugs in Java Programs- -- This is the web page for FindBugs, a program which uses static analysis to look for bugs in Java - code. It is free software, distributed under the terms of the Lesser GNU Public License. The name - FindBugs™ and the FindBugs logo are trademarked by The University of Maryland. FindBugs has been downloaded more than - a million times. - - -The current version of FindBugs is 2.0.0. - -- FindBugs requires JRE (or JDK) 1.5.0 or later to run. However, it can analyze programs - compiled for any version of Java, from 1.0 to 1.8. The current version of FindBugs is 2.0.0, - released on 21:17:55 EST, 20 December, 2011. We are very interested in getting - feedback on how to improve FindBugs. File bug reports on our - sourceforge bug tracker - - -- Changes | Talks | Papers | Sponsors | Support - -FindBugs 2.0 Release-After many delays, we have released FindBugs 2.0. We are pretty happy and confident about the - functionality, although we know the documentation of the changes in 2.0 is lacking. We decided that - releasing 2.0 took precedence over fixing the documentation. Anyone currently using FindBugs 1.3.9 - should find FindBugs 2.0 to largely be a drop-in replacement that offers better accuracy and - performance. - -- Also check out http://code.google.com/p/findbugs/w/list - for more information about some recent features/changes in FindBugs. - - - -- Major changes in FindBugs 2.0 --
Ways to run FindBugs-Here are various ways to run FindBugs. For plugins not supported by the FindBugs team, check to - see what version of FindBugs they provide; it might take a little while for the plugins to update to - FindBugs 2.0. -
New-
Experience with FindBugs-On May 13-14, Google held a global fixit for UMD's FindBugs tool a static analysis tool for - finding coding mistakes in Java software. The focus of the fixit was to get feedback on the - 4,000 highest confidence issues found by FindBugs at Google, and let Google engineers decide - which issues, if any, needed fixing. -More than 700 engineers ran FindBugs from dozens of offices. More than 250 of them entered - more than 8,000 reviews of the issues. A review is a classification of an issue as must-fix, - should-fix, mostly-harmless, not-a-bug, and several other categories. More than 75% of the - reviews classified issues as must fix, should fix or I will fix. Many of the scariest issues - received more than 10 reviews each. -Engineers have already submitted changes that made more than 1,100 of the 3,800 issues go - away. Engineers filed more than 1,700 bug reports, of which 600 have already been marked as - fixed Work continues on addressing the issues raised by the fixit, and on supporting the - integration of FindBugs into the software development process at Google. -The fixit at Google showcased new capabilities of FindBugs that provide a cloud computing / - social networking backdrop. Reviews of issues are immediately persisted into a central store, - where they can be seen by other developers, and FindBugs is integrated into the internal Google - tools for filing and viewing bug reports and for viewing the version control history of source - files. For the Fixit, FindBugs was configured in a mode where engineers could not see reviews - from other engineers until they had entered their own; after the fixit, the configuration will - be changed to a more open configuration where engineers can see reviews from others without - having to provide their own review first. These capabilities have all been contributed to UMD's - open source FindBugs tool, although a fair bit of engineering remains to prepare the - capabilities for general release and make sure they can integrate into systems outside of - Google. The new capabilities are expected to be ready for general release in Fall 2009. - Talks about FindBugs --
- Mistakes That Matter, JavaOne, - 2009 - -- Papers about FindBugs --
- Contributors and Sponsors --- The current development team consists of Bill Pugh and Andrey Loskutov. - -Current funding for FindBugs comes from a Google Faculty Research Awards. We'd be interested in - any offers of support or sponsorship. -- Additional Support --- Numerous people have made significant contributions to the FindBugs - project, including founding work by David Hovemeyer - and the web cloud infrastructure by Keith Lea. - -- YourKit is kindly supporting open source projects with its full-featured Java Profiler. YourKit, LLC - is creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look - at YourKit's leading software products: YourKit - Java Profiler and YourKit .NET - Profiler. - -- The FindBugs project also uses FishEye and - Clover, which are generously provided by Cenqua/Atlassian. - -- Additional financial support for the FindBugs project was provided by National - Science Foundation grants ASC9720199 and CCR-0098162, - -Any opinions, findings and conclusions or recommendations expressed in this material are those of - the author(s) and do not necessarily reflect the views of the National Science Foundation (NSF). - - - - Send comments to findbugs@cs.umd.edu - - |
-
FindBugs was originally written by Bill Pugh (<pugh@cs.umd.edu>).
-David Hovemeyer (<daveho@cs.umd.edu>) implemented some of the
-detectors, added the Swing GUI, and is a co-maintainer.
Mike Fagan (<mfagan@tde.com>) contributed the Ant build script,
-the Ant task, and several enhancements and bug fixes to the GUI.
Germano Leichsenring contributed Japanese translations of the bug -summaries.
David Li contributed the Emacs bug report format.
Peter D. Stout contributed recursive detection of Class-Path -attributes in analyzed Jar files, German translations of -text used in the Swing GUI, and other fixes.
Peter Friese wrote the FindBugs Eclipse plugin.
Rohan Lloyd contributed several Mac OS X enhancements, -bug detector improvements, -and maintains the Fink package for FindBugs.
Hiroshi Okugawa translated the FindBugs manual and -more of the bug summaries into Japanese.
Phil Crosby enhanced the Eclipse plugin to add a view -to display the bug details.
Dave Brosius fixed a number of bugs, added user preferences -to the Swing GUI, improved several bug detectors, and -contributed the string concatenation detector.
Thomas Klaeger contributed a number of bug fixes and -bug detector improvements.
Andrei Loskutov made a number of improvements to the -Eclipse plugin.
Brian Goetz contributed a major refactoring of the -visitor classes to improve readability and understandability.
Pete Angstadt fixed several problems in the Swing GUI.
Francis Lalonde provided a task resource file for the -FindBugs Ant task.
Garvin LeClaire contributed support for output in -Xdocs format, for use by Maven.
Holger Stenzhorn contributed improved German translations of items -in the Swing GUI.
Juha Knuutila contributed Finnish translations of items -in the Swing GUI.
Tanel Lebedev contributed Estonian translations of items -in the Swing GUI.
Hanai Shisei (ruimo) contributed full Japanese translations of -bug messages, and text used in the Swing GUI.
David Cotton contributed Fresh translations for bug -messages and for the Swing GUI.
Michael Tamm contributed support for the "errorProperty" attribute -in the Ant task.
Thomas Kuehne improved the German translation of the Swing GUI.
Len Trigg improved source file support for the Emacs output mode.
Greg Bentz provided a fix for the hashcode/equals detector.
K. Hashimoto contributed internationalization fixes and several other - bug fixes.
- Glenn Boysko contributed support for ignoring specified local - variables in the dead local store detector. -
- Jay Dunning contributed a detector to find equality comparisons - of floating-point values, and overhauled the analysis summary - report and its representation in the saved XML format. -
- Olivier Parent contributed updated French translations for bug descriptions and - Swing GUI. -
- Chris Nappin contributed the plain.xsl
- stylesheet.
-
- Etienne Giraudy contributed the fancy.xsl and fancy-hist.xsl
- stylesheets, and made improvements to the -xml:withMessages
- option.
-
- Takashi Okamoto fixed bugs in the project preferences dialog - in the Eclipse plugin, and contributed to its internationalization and localization. -
Thomas Einwaller fixed bugs in the project preferences dialog in the Eclipse plugin.
Jeff Knox contributed support for the warningsProperty attribute -in the Ant task.
Peter Hendriks extended the Eclipse plugin preferences, -and fixed a bug related to renaming the Eclipse plugin ID.
Mark McKay contributed an Ant task to launch the findbugs frame.
Dieter von Holten (dvholten) contributed -some German improvements to findbugs_de.properties.
If you have contributed to FindBugs, but aren't mentioned above,
-please send email to <findbugs@cs.umd.edu> (and also accept
-our humble apologies).
FindBugs は、いくつかのオープンソースソフトウェアパッケージを使用しています。これらがなければ、 FindBugs の開発は、より一層困難なものになったことでしょう。
FindBugs includes software developed by the Apache Software Foundation -(http://www.apache.org/). -Specifically, it uses the Byte Code -Engineering Library.
FindBugs uses the ASM -bytecode framework, which is distributed under the following license:
-Copyright (c) 2000-2005 INRIA, France Telecom -All rights reserved. -
-Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: -
- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -
- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -
- Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. -
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. -
FindBugs uses DOM4J, which is -distributed under the following license:
-Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. -
-Redistribution and use of this software and associated documentation -("Software"), with or without modification, are permitted provided that -the following conditions are met: -
- Redistributions of source code must retain copyright statements and - notices. Redistributions must also contain a copy of this document. -
- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -
- The name "DOM4J" must not be used to endorse or promote products - derived from this Software without prior written permission - of MetaStuff, Ltd. For written permission, please contact -
<dom4j-info@metastuff.com>. -- Products derived from this Software may not be called "DOM4J" nor may - "DOM4J" appear in their names without prior written permission of - MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. -
- Due credit should be given to the DOM4J Project (http://dom4j.org/). -
-THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' -AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -
FindBugs は分析する場合にいくつかの観点を持っています。そして、観点をカスタマイズして実行することができます。システムプロパティーを使って、それらのオプションを設定します。この章では、分析オプションの設定方法を説明します。
分析オプションの主な目的は、 2 つあります。1 番目は、 FindBugs に対して分析されるアプリケーションのメソッドの意味を伝えることです。そうすることで FindBugs がより正確な結果を出すことができ、誤検出を減らすことができます。2 番目に、分析を行うに当たりその精度を設定できるようにすることです。分析の精度を落とすことで、メモリ使用量と分析時間を減らすことができます。ただし、本当のバグを見逃したり、誤検出の数が増えるという代償があります。
コマンドラインオプション -property を使って、分析オプションを設定することができます。次に、例を示します:
-$findbugs -textui -property "cfg.noprune=true"myApp.jar-
-
設定することができる分析オプションの一覧を 表9.1「設定可能な分析プロパティー」 に示します。
表9.1 設定可能な分析プロパティー
| プロパティー名 | 設定値 | 目的 |
|---|---|---|
| findbugs.assertionmethods | コンマ区切りの完全修飾メソッド名リスト : 例、 "com.foo.MyClass.checkAssertion" | このプロパティーには、プログラムが正しいことをチェックするために使われるメソッドを指定します。これらのメソッドを指定することで、 チェックメソッドで確認した値に対する null 参照アクセスディテクタの誤検出を回避できます。 |
| findbugs.de.comment | true または false | true に設定すると、 DroppedException (無視された例外) ディテクタは空の catch ブロック にコメントが無いか探します。そして、コメントがみつかった場合には警告が報告されません。 |
| findbugs.maskedfields.locals | true または false | true に設定すると、フィールドを隠蔽しているローカル変数に対して優先度(低)の警告が発行されます。デフォルトは、 false です。 |
| findbugs.nullderef.assumensp | true または false | 使用されません。 (意図 : true に設定すると、null 参照アクセスディテクタはメソッドからの戻り値、または、メソッドに受け渡される引数を null であると仮定します。デフォルトは、 false です。このプロパティーを有効にすると、大量の誤検出が生成されるであろうことに注意してください。) |
| findbugs.refcomp.reportAll | true または false | true に設定すると、 == および != 演算子を使っている疑わしい参照比較がすべて報告されます。 false に設定すると、同様の警告は 1 メソッドにつき 1 つしか発行されません。デフォルトは、 false です。 |
| findbugs.sf.comment | true または false | true に設定すると、 SwitchFallthrough ディテクタはソースコードに「fall」または「nobreak」という単語を含んだコメントを記載していない caseラベル に限り警告を報告します。(この機能が正しく動作するためには、正確なソースパスが必要です。) これにより、意図的ではない switch 文の fallthrough を発見し易くなります。 |
FindBugs はいくつかのアノテーションをサポートしています。開発者の意図を明確にすることで、 FindBugs はより的確に警告を発行することができます。アノテーションを使用するためには Java 5 が必要であり、 annotations.jar および jsr305.jar ファイルをコンパイル時のクラスパスに含める必要があります。
アノテーションをつけた要素は、 null である可能性があります。したがって、当該要素を使用する際は null チェックをするべきです。このアノテーションをメソッドに適用すると、メソッドの戻り値に適用されます。
- priority: 警告の優先度を指定します (HIGH, MEDIUM, LOW, IGNORE) 。デフォルト値 :MEDIUM。
- explanation:戻り値をチェックしなけばならない理由をテキストで説明します。デフォルト値 :""。
このアノテーションを使用して、呼出し後に戻り値をチェックすべきメソッドを表すことができます。
- value:アノテーションクラスのclassオブジェクト。複数のクラスを指定することができます。
- priority:省略時の優先度を指定します (HIGH, MEDIUM, LOW, IGNORE) 。デフォルト値 :MEDIUM。
-Indicates that all members of the class or package should be annotated with the default -value of the supplied annotation classes. This would be used for behavior annotations -such as @NonNull, @CheckForNull, or @CheckReturnValue. In particular, you can use -@DefaultAnnotation(NonNull.class) on a class or package, and then use @Nullable only -on those parameters, methods or fields that you want to allow to be null. -
- value:アノテーションクラスのclassオブジェクト。複数のクラスを指定することができます。
- priority:省略時の優先度を指定します (HIGH, MEDIUM, LOW, IGNORE) 。デフォルト値 :MEDIUM。
-This is same as the DefaultAnnotation except it only applys to fields. -
- value:アノテーションクラスのclassオブジェクト。複数のクラスを指定することができます。
- priority:省略時の優先度を指定します (HIGH, MEDIUM, LOW, IGNORE) 。デフォルト値 :MEDIUM。
-This is same as the DefaultAnnotation except it only applys to methods. -
- value:アノテーションクラスのclassオブジェクト。複数のクラスを指定することができます。
- priority:省略時の優先度を指定します (HIGH, MEDIUM, LOW, IGNORE) 。デフォルト値 :MEDIUM。
-This is same as the DefaultAnnotation except it only applys to method parameters. -
アノテーションをつけた要素は、 null であってはいけません。アノテーションをつけたフィールドは、構築完了後 null であってはいけません。アノテーションをつけたメソッドは、 null ではない値を戻り値としなければなりません。
アノテーションをつけた要素は、 null であってはいけません。In general, this means developers will have to read the documentation to determine when a null value is acceptable and whether it is neccessary to check for a null value. FindBugs will treat the annotated items as though they had no annotation.
-In pratice this annotation is useful only for overriding an overarching NonNull -annotation. -
- value:Specify when the super invocation should be - performed (FIRST, ANYTIME, LAST). Default value:ANYTIME. -
-Used to annotate a method that, if overridden, must (or should) be invoke super -in the overriding method. Examples of such methods include finalize() and clone(). -The argument to the method indicates when the super invocation should occur: -at any time, at the beginning of the overriding method, or at the end of the overriding method. -(This anotation is not implmemented in FindBugs as of September 8, 2006). -
-This annotation is deprecated. Use CheckForNull instead. -
- value:The name of the warning. More than one name can be specified. -
- justification:Reason why the warning should be ignored. デフォルト値 :""。
-The set of warnings that are to be suppressed by the compiler in the annotated element. -Duplicate names are permitted. The second and successive occurrences of a name are ignored. -The presence of unrecognized warning names is not an error: Compilers -must ignore any warning names they do not recognize. They are, however, free to emit a -warning if an annotation contains an unrecognized warning name. Compiler vendors should -document the warning names they support in conjunction with this annotation type. They -are encouraged to cooperate to ensure that the same names work across multiple compilers. -
-Used to indicate that the nullness of the target is unknown, or my vary in unknown ways in subclasses. -
-Used to indicate that the nullness of the target is unknown, or my vary in unknown ways in subclasses. -
また、 FindBugs 次に示すアノテーションもサポートしています。 :
-
Java Concurrency in Practice の API ドキュメント を参照してください。
この章では、 FindBugs を Ant のビルドスクリプトに組み入れる方法について説明します。 Ant は、ビルドや配備を行うことができる Java でよく使用されるツールです。FindBugs Ant タスクを使用すると、 ビルドスクリプトを作成して機械的に FindBugs による Java コードの分析を実行することができます。
この Ant タスクは、 Mike Fagan 氏の多大な貢献によるものです。
Ant タスクのインストールは、 を Ant インストールディレクトリーの$FINDBUGS_HOME/lib/findbugs-ant.jarlib サブディレクトリーにコピーするだけです。
![]() | 注記 |
|---|---|
使用する Ant タスクと FindBugs 本体は、同梱されていた同じバージョンのものを使用することを強く推奨します。別のバージョンの FindBugs に含まれていた Ant タスク Jar ファイルでの動作は保証しません。 |
-
FindBugs を build.xml (Ant ビルドスクリプト) に組み入れるためにはまず、タスク定義を記述する必要があります。タスク定義は次のように記述します。:
- <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask"/> -
タスク定義は、 findbugs 要素を build.xml 上に記述したとき、そのタスクの実行に使用されるクラスを指定します。
タスク定義の記述をすれば、findbugs タスクを使ってターゲットを定義できます。次に示すのは、 Apache BCEL ライブラリーを分析する場合を想定した build.xml の記述例です。
- <property name="findbugs.home" value="/export/home/daveho/work/findbugs" />
-
- <target name="findbugs" depends="jar">
- <findbugs home="${findbugs.home}"
- output="xml"
- outputFile="bcel-fb.xml" >
- <auxClasspath path="${basedir}/lib/Regex.jar" />
- <sourcePath path="${basedir}/src/java" />
- <class location="${basedir}/bin/bcel.jar" />
- </findbugs>
- </target>
-findbugs 要素には、 home 属性が必須です。 FindBugs のインストールディレクトリーすなわち $FINDBUGS_HOME の値を設定します。2章FindBugs™ のインストール を参照してください。
このターゲットは bcel.jar に対して FindBugs を実行します。この Jar ファイルは、 BCEL ビルドスクリプトによって作成されるものです。(上記のターゲットが「jar」ターゲットに依存している (depends) と設定することにより、 FindBugs が実行される前に当該ライブラリーが完全にコンパイルされていることを保証しています。) FindBugs の出力は、 XML 形式で bcel-fb.xml ファイルに保存されます。補助 Jar ファイル Regex.jar を aux classpath に記述しています。なぜなら、当該 Jar ファイルが BCEL メイン・ライブラリーから参照されるからです。source path を指定することで、保存されるバグデータに BCEL ソースコードへの正確な参照が記述されます。
コマンドラインから Ant を起動する例を次に示します。前述の findbugs ターゲットを使用しています。
- [daveho@noir]$ ant findbugs
- Buildfile: build.xml
-
- init:
-
- compile:
-
- examples:
-
- jar:
-
- findbugs:
- [findbugs] Running FindBugs...
- [findbugs] Bugs were found
- [findbugs] Output saved to bcel-fb.xml
-
- BUILD SUCCESSFUL
- Total time: 35 seconds
-この事例においては、XML ファイルでバグ検索結果を保存しているので、 FindBugs GUI を使って結果を参照することができます。 4章FindBugs™ の実行 を参照してください。
このセクションでは、 FindBugs タスクを使用する際に、指定することができるパラメーターについて説明します。
class分析の対象となるクラス群を指定するためのネストされる要素です。class 要素には location 属性の指定が必須です。分析対象となるアーカイブファイル (jar, zip, 他)、ディレクトリーまたはクラスファイルの名前を記述します。1 つの findbugs 要素に対して、複数の class 子要素を指定することができます。
auxClasspath任意指定のネストされる要素です。分析対象のライブラリーまたはアプリケーションによって使用されているが分析の対象にはしたくないクラスを含んでいるクラスパス (Jar ファイルまたはディレクトリー) を指定します。 Ant の Java タスクにある classpath 要素 と同じ方法で指定することができます。
sourcePath任意指定のネストされる要素です。分析対象 Java コードのコンパイル時に使用したソースファイルを含んでいるソースディレクトリーへのパスを指定します。ソースパスを指定することにより、生成される XML のバグ出力結果に完全なソース情報をもたせることができ、後になって GUI で参照することができます。
home必須属性です。FindBugs がインストールされているディレクトリー名を設定します。
quietErrors任意指定のブール値属性です。true を設定すると、深刻な分析エラー発生やクラスがみつからないといった情報が FindBugs 出力に記録されません。デフォルトは、 false です。
reportLevel任意指定の属性です。報告されるバグの優先度のしきい値を指定します。「low」に設定すると、すべてのバグが報告されます。「medium」 (デフォルト) に設定すると、優先度 (中)および優先度 (高)のバグが報告されます。「high」に設定すると、優先度 (高) のバグのみが報告されます。
output任意指定の属性です。出力形式を指定します。「xml」 (デフォルト) に設定すると、出力は XML 形式になります。「xml:withMessages」 に設定すると、出力は人間が読めるメッセージ が追加された XML 形式になります。(XSL スタイルシートを使ってレポートを作成することを計画している場合はこの形式を使用してください。) 「html」に設定すると、出力は HTML 形式(デフォルトのスタイルシートは default.xsl) になります。 「text」に設定すると、出力は特別なテキスト形式になります。「emacs」に設定すると、出力は Emacs エラーメッセージ形式になります。「xdocs」に設定すると、出力は Apache Maven で使用できる xdoc XML になります。
stylesheet任意指定の属性です。output 属性 に html を指定した場合に、 HTML 出力作成に使用されるスタイルシートを指定します。FindBugs 配布物に含まれているスタイルシートは、 default.xsl、 fancy.xsl 、 fancy-hist.xsl 、 plain.xsl および summary.xsl です。デフォルト値は default.xsl です。
sort任意指定の属性です。output 属性に「text」を指定した場合に、バグの報告をクラス順にソートするかどうかを sort 属性で指定します。デフォルトは、 true です。
outputFile任意指定の属性です。指定した場合、FindBugs の出力はその名前のファイルへと保存されます。省略時、出力は Ant によって直接表示されます。
debug任意指定のブール値属性です。true に設定すると、 FindBugs は 診断情報を出力します。どのクラスを分析しているか、どのパグパターンディテクタが実行されているか、という情報が表示されます。デフォルトは、 false です。
effort分析の活動レベルを設定します。min 、default または max のいずれかの値を設定してください。分析レベルの設定に関する詳細情報は、 「コマンドラインオプション」 を参照してください。
conserveSpaceeffort="min" と同義です。
workHardeffort="max" と同義です。
visitors任意指定の属性です。どのバグディテクタを実行するかをコンマ区切りのリストで指定します。バグディテクタはパッケージ指定なしのクラス名で指定します。省略時、デフォルトで無効化されているものを除くすべてのディテクタが実行されます。
omitVisitors任意指定の属性です。visitors 属性と似ていますが、こちらは 実行されない ディテクタを指定します。
excludeFilter任意指定の属性です。フィルターファイル名を指定します。報告から除外されるバグを指定します。8章フィルターファイル を参照してください。
includeFilter任意指定の属性です。フィルターファイル名を指定します。報告されるバグを指定します。8章フィルターファイル を参照してください。
projectFile任意指定の属性です。プロジェクトファイル名を指定します。プロジェクトファイルは、 FindBugs GUI で作成します。分析されるクラス、および、補助クラスパス、ソースディレクトリーが記入されてます。プロジェクトファイルを指定した場合は、 class 要素・ auxClasspath 属性および sourcePath 属性を設定する必要はありません。プロジェクトの作成方法は、 4章FindBugs™ の実行 を参照してください。
jvmargs任意指定の属性です。FindBugs を実行している Java 仮想マシンに対して受け渡される引数を指定します。巨大なプログラムを分析する場合に、 JVM が使用するメモリ容量を増やす指定をするためにこの引数を利用する必要があるかもしれません。
systemProperty任意指定のネストされる要素です。指定した場合、Java システムプロパティーを定義します。name 属性にはシステムプロパティーの名前を指定します。そして、 value 属性にはシステムプロパティの値を指定します。
timeout任意指定の属性です。FindBugs を実行している Java プロセス の実行許容時間をミリ秒単位で指定します。時間を超過するとハングアップしていると判断してプロセスが終了されます。デフォルトは、 600,000 ミリ秒 (10 分) です。巨大なプログラムの場合は、 FindBugs が分析を完了するまでに 10 分 以上掛かる可能性があることに注意してください。
failOnError任意指定のブール値属性です。FindBugs の実行中にエラーがあった場合に、ビルドプロセス自体を打ち切って異常終了させるかどうかを指定します。デフォルトは、「false」です。
errorProperty任意指定の属性です。FindBugs の実行中にエラーが発生した場合に、「true」が設定されるプロパティーの名前を指定します。
warningsProperty任意指定の属性です。FindBugs が分析したプログラムにバグ報告が 1 件でもある場合に、「true」が設定されるプロパティーの名前を指定します。
- - -
この章では、 FindBugs をソースコードからビルドする方法を説明します。FindBugs を修正することに興味がないのであれば、 次の章 に進んでください。
ソースから FindBugs をコンパイルするためには、以下のものが必要です。
- Apache Ant, バージョン 1.6.3 またはそれ以降
-
![]() | 警告 |
|---|---|
Redhat Linux システムの |
体裁の整った FindBugs のドキュメントを生成したい場合は、以下のソフトウェアも必要となります:
DocBook XSL スタイルシート。FindBugs のマニュアルを HTML に変換するのに必要です。
Saxon XSLT プロセッサー。(同様に、 FindBugs のマニュアルを HTML に変換するのに必要です。)
-
ソース配布物をダウンロードした後に、それを作業用ディレクトリーに展開する必要があります。通常は、次のようなコマンドで展開を行います:
-$ unzip findbugs-2.0.0-source.zip
-- -
FindBugs のドキュメントをビルドするためには、 local.properties ファイルを修正する必要があります。このファイルは、 FindBugs をビルドする際に Ant build.xml ファイルが参照します。FindBugs のドキュメントをビルドしない場合は、このファイルは無視してもかまいません。
local.properties での定義は、 build.properties ファイルでの定義に優先します。build.properties は次のような内容です:
-
-# User Configuration:
-# This section must be modified to reflect your system.
-
-local.software.home =/export/home/daveho/linux
-
-# Set this to the directory containing the DocBook Modular XSL Stylesheets
-# from http://docbook.sourceforge.net/projects/xsl/
-
-xsl.stylesheet.home =${local.software.home}/docbook/docbook-xsl-1.71.1
-
-# Set this to the directory where Saxon (http://saxon.sourceforge.net/)
-# is installed.
-
-saxon.home =${local.software.home}/java/saxon-6.5.5
-
--
xsl.stylesheet.home プロパティーには、DocBook Modular XSL スタイルシートがインストールしてあるディレクトリーの絶対パスを指定します。FindBugs ドキュメントを生成しようと考えている場合にのみ、このプロパティーを指定する必要があります。
saxon.home プロパティーには、Saxon XSLT プロセッサーがインストールしてあるディレクトリーの絶対パスを指定します。FindBugs ドキュメントを生成しようと考えている場合にのみ、このプロパティーを指定する必要があります。
ソース配布物の展開、 Ant のインストール、build.properties(local.properties) の修正 (これは任意) およびツール (Saxon など)の環境構築ができれば、 FindBugs をビルドするための準備は完了です。Ant の起動する方法は、単にコマンドを実行するだけです。
-$anttarget-
target には以下のいずれかを指定します:
このターゲットは、 FindBugs のコードをコンパイルします。これは、デフォルトのターゲットです。
このターゲットは、ドキュメントの整形を行います(また、副作用としていくつかのソースのコンパイルも行います。)
このターゲットは、コンパイルを行い FindBugs が持っている JUnit テストを実行します。ユニットテストが失敗した場合は、エラーメッセージが表示されます。
FindBugs のバイナリ配布物を構築します。このターゲットは、 .zip および .tar.gz のアーカイブをそれぞれ作成します。
-
Ant コマンドの実行後、次のような出力が表示されるはずです。 (この前に Ant が実行したタスクに関するメッセージもいくらか出力されます。):
-
-BUILD SUCCESSFUL
-Total time: 17 seconds
-
--
build ターゲットの実行が終了すると、バイナリ配布物と同様の状態が作業ディレクトリーに構築されるように FindBugs のAnt ビルドスクリプトは記述されています。したがって、4章FindBugs™ の実行 の FindBugs の実行に関する情報はソース配布物の場合にも応用できます。
バグデータベースへの高機能の問い合わせ機能、および、調査対象のコードの複数のバージョンにわたる警告の追跡記録機能を、 FindBugs は内蔵しています。これらを使って次のようなことができます。すなわち、いつバグが最初持ち込まれたかを捜し出すこと、最終リリース以後持ち込まれた警告の分析を行うこと、または、無限再起ループの数を時間軸でグラフにすることです。
これらの技術は、 FindBugs が警告の保存に使う XML 書式を使用します。これらの XML ファイルは、通常、特定の 1 分析に対する警告が入れられています。しかしそれらには、一連のソフトウェアのビルドやバージョンに対する分析結果を格納することもできます。
すべての FindBugs XML バグデータベースには、バージョン名とタイム・スタンプ が入れられています。FindBugs は分析が行われるファイルの更新時刻からタイム・スタンプを計算します (例えば、タイム・スタンプはクラスファイルの生成時刻になるようになっています。分析が行われた時刻ではありません) 。各々のバグデータベースには、バージョン名も入れられています。バージョン名とタイム・スタンプは、 setBugDatabaseInfo (「setBugDatabaseInfo」) コマンドを使用して手動で設定することもできます。
複数バージョンを格納するバグデータベースにおいては、分析されるコードの各バージョンごとにシーケンス番号が割り当てられます。これらのシーケンス番号は単に 0 から始まる連続する整数値です (例えば、 4 つのコードバージョンを格納するバグデータベースには、バージョン 0~3 が入れられます) 。バグデータベースにはまた、各バージョンの名前とタイム・スタンプがそれぞれ記録されます。filterBugs コマンドを使用すると、シーケンス番号、バージョン名またはタイム・スタンプからバージョンを参照することができます。
1 バージョンを格納するバグデータベースの集合から、 1 個の複数バージョンバグデータベースを作成することができます。また、複数バージョンバグデータベースに対して、それ以後に作成された 1 バージョンのバグデータベースを結合することができます。
これらのコマンドのいくつかは、 ant タスクとして実行することができます。コマンドの実行方法および属性・引数の詳細は、以下を参照してください。以下のすべての例においては、 findbugs.lib refid が正しく設定されていることを前提としています。設定方法の一例を次に示します :
-
- <!-- findbugs タスク定義 -->
- <property name="findbugs.home" value="/your/path/to/findbugs" />
- <path id="findbugs.lib">
- <fileset dir="${findbugs.home}/lib">
- <include name="findbugs-ant.jar"/>
- </fileset>
- </path>
-
-FindBugs データ・マイニング ツールはすべてコマンドラインから実行することができます。また、いくつかのより有用なコマンドは、 ant ビルドファイルから実行することができます。
コマンドラインツールについて簡単に説明します :
別のクラスに対する別個の分析結果を結合します。
複数バージョンから得られた複数のバグ警告を、マージして 1 個の複数バージョンバグデータベースにします。これを使って、既存の複数バージョンバグデータベースに更にバージョンを追加したり、 1 バージョンを格納するバグデータベースの集合から 1 個の複数バージョンバグデータベースを作成したり、できます。
リビジョン名やタイム・スタンプなどの情報を XML データベースに設定します。
XML データベースにあるリビジョン名やタイム・スタンプなどの情報を一覧表示します。
バグデータベースの部分集合を選択します。
複数バージョンバグデータベースの各バージョン毎の警告数を一覧にした表を作成します。
プロジェクト全体およびクラス毎・パッケージ毎の不良密度 (1000 NCSS 毎の警告数) に関する情報を一覧表示します。
XML 形式のバグ警告を、 1 行 1 バグのテキスト形式、または、HTML形式に変換します。
分析するのにアプリケーションの jar ファイルを分割している場合、このコマンドを使用することで、別個に生成された XML バグ警告ファイルをすべての警告を含んでいる 1 つの ファイルにすることができます。
同じファイルの異なるバージョンを分析した結果を結合する場合は、このコマンドを使用しないでください。代わりに computeBugHistory を使用してください。
XML ファイルは、コマンドラインで指定してください。結果は、標準出力に送られます。
このコマンドを使用することで、分析するソフトウェアの異なるビルドまたはバージョンの情報を含むバグデータベースを生成することができます入力として提供したファイルの 1 番目のファイルから履歴が取得されます。後に続くファイルは 1 バージョンのバグデータベースであるようにしてください (もし、履歴を持っていたとしても無視されます) 。
デフォルトでは、結果は標準出力に送られます。
この機能は、 ant からも使用することができます。まず次に示すように、ビルドファイルに computeBugHistory を taskdef で定義します :
- -<taskdef name="computeBugHistory" classname="edu.umd.cs.findbugs.anttask.ComputeBugHistoryTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
この ant タスクに指定できる属性を、下表に一覧で示します。入力ファイルを指定するには、 <datafile> 要素を入れ子にして入れてください。次に、例を示します:
-
-<computeBugHistory home="${findbugs.home}" ...>
- <datafile name="analyze1.xml"/>
- <datafile name="analyze2.xml"/>
-</computeBugHistory>
-
-表12.1 computeBugHistory コマンドのオプション一覧
| コマンドラインオプション | Ant 属性 | 目的 |
|---|---|---|
| -output <file> | output="<file>" | 出力結果を保存するファイル名を指定します。 (同時に入力ファイルにもなりえます) |
| -overrideRevisionNames[:truth] | overrideRevisionNames="[true|false]" | ファイル名から算出されるそれぞれのバージョン名を指定変更します。 |
| -noPackageMoves[:truth] | noPackageMoves="[true|false]" | パッケージを移動したクラスがある場合、当該クラスの警告は別の存在として扱われます。 |
| -preciseMatch[:truth] | preciseMatch="[true|false]" | バグパターンが正確に一致することを要求します。 |
| -precisePriorityMatch[:truth] | precisePriorityMatch="[true|false]" | 優先度が正確に一致した場合のみ警告が同一であると判断されます。 |
| -quiet[:truth] | quiet="[true|false]" | エラーが発生しない限り、標準出力には何も表示されません。 |
| -withMessages[:truth] | withMessages="[true|false]" | 出力 XML に人間が読むことができるバグメッセージが含まれます。 |
このコマンドを使用することで、 FindBugs XML 警告ファイルから一部分を選び出して新規 FindBugs 警告ファイルに選択された部分を書き込むことができます。
このコマンドには、オプション群に続いて 0 個から 2 個の findbugs xml バグファイルを指定することができます。
ファイル名をひとつも指定しない場合は、標準入力から読んで標準出力に出力されます。ファイル名を 1 個 指定した場合は、指定したファイルから読んで標準出力に出力されます。ファイル名を 2 個 指定した場合は、 1 番目に指定したファイルから読んで 2 番目に指定したファイルに出力されます。
この機能は、 ant からも使用することができます。まず次に示すように、ビルドファイルに filterBugs を taskdef で定義します :
- -<taskdef name="filterBugs" classname="edu.umd.cs.findbugs.anttask.FilterBugsTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
この ant タスクに指定できる属性を、下表に一覧で示します。入力ファイルを指定するには、 input 属性を使用するか、 <datafile> 要素を入れ子にして入れてください。次に、例を示します:
-
-<filterBugs home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</filterBugs>
-
-表12.2 filterBugs コマンドのオプション一覧
| コマンドラインオプション | Ant 属性 | 目的 |
|---|---|---|
| input="<file>" | 入力ファイルを指定します。 | |
| output="<file>" | 出力ファイルを指定します。 | |
| -not | not="[true|false]" | フィルターのスイッチを反転します。 |
| -withSource[:truth] | withSource="[true|false]" | ソースが入手可能な警告のみ出力されます。 |
| -exclude <filter file> | exclude="<filter file>" | フィルターに一致するバグが除外されます。 |
| -include <filter file> | include="<filter file>" | フィルターに一致するバグのみを含まれます。 |
| -annotation <text> | annotation="<text>" | 手で入力した注釈に指定した文言を含む警告のみ出力されます。 |
| -after <when> | after="<when>" | 指定したバージョンより後に初めて出現した警告のみ出力されます。 |
| -before <when> | before="<when>" | 指定したバージョンより前に初めて出現した警告のみ出力されます。 |
| -first <when> | first="<when>" | 指定したバージョンに初めて出現した警告のみ出力されます。 |
| -last <when> | last="<when>" | 指定したバージョンが出現した最後である警告のみ出力されます。 |
| -fixed <when> | fixed="<when>" | 指定したバージョンの前回のバージョンが出現した最後である警告のみ出力されます。 (-last に優先します)。 |
| -present <when> | present="<when>" | 指定したバージョンに存在する警告のみ出力されます。 |
| -absent <when> | absent="<when>" | 指定したバージョンに存在しない警告のみ出力されます。 |
| -active[:truth] | active="[true|false]" | 最終通番に存在する警告のみ出力されます。 |
| -introducedByChange[:truth] | introducedByChange="[true|false]" | 存在するクラスの変更によってもたらされた警告のみ出力されます。 |
| -removedByChange[:truth] | removedByChange="[true|false]" | 存在するクラスの変更によって除去された警告のみ出力されます。 |
| -newCode[:truth] | newCode="[true|false]" | 新クラスの追加によってもたらされた警告のみ出力されます。 |
| -removedCode[:truth] | removedCode="[true|false]" | クラスの削除によって除去された警告のみ出力されます。 |
| -priority <level> | priority="<level>" | 指定した優先度以上の優先度をもつ警告のみ出力されます。 |
| -class <pattern> | class="<class>" | 指定したパターンに一致する主クラスをもつ警告のみ出力されます。 |
| -bugPattern <pattern> | bugPattern="<pattern>" | 指定したパターンに一致するバグ種別をもつ警告のみ出力されます。 |
| -category <category> | category="<category>" | 指定した文字列で始まるカテゴリーの警告のみ出力されます。 |
| -designation <designation> | designation="<designation>" | 指定したバグ分類指定をもつ警告のみ出力されます。 (例、 -designation SHOULD_FIX) |
| -withMessages[:truth] | withMessages="[true|false]" | テキストメッセージを含んだ XML が生成されます。 |
このコマンドを使用することで、複数バージョンバグデータベースの各バージョン毎の警告数を一覧にした表を作成することができます。
この機能は、 ant からも使用することができます。まず次に示すように、ビルドファイルに mineBugHistory を taskdef で定義します :
- -<taskdef name="mineBugHistory" classname="edu.umd.cs.findbugs.anttask.MineBugHistoryTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
この ant タスクに指定できる属性を、下表に一覧で示します。入力ファイルを指定するには、 input 属性を使用するか、 <datafile> 要素を入れ子にして入れてください。次に、例を示します:
-
-<mineBugHistory home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</mineBugHistory>
-
-表12.3 mineBugHistory コマンドのオプション一覧
| コマンドラインオプション | Ant 属性 | 目的 |
|---|---|---|
| input="<file>" | 入力ファイルを指定します。 | |
| output="<file>" | 出力ファイルを指定します。 | |
| -formatDates | formatDates="[true|false]" | データがテキスト形式で描画されます。 |
| -noTabs | noTabs="[true|false]" | タブの代わりに複数スペースでカラムが区切られます (下記参照)。 |
| -summary | summary="[true|false]" | 最新 10 件の変更の要約が出力されます。 |
-noTabs 出力を使うことで、固定幅フォントのシェルで読み易くなります。数値カラムは右寄せされるので、スペースがカラム値の前に挿入されます。また、このオプションを使用した場合、 -formatDates を指定したときに要約の日付を描画するのに空白が埋め込まれなくなります。
出力される表は、 (-noTabs が無ければ) タブ区切りで次に示すカラムから成ります :
表12.4 mineBugHistory 出力のカラム一覧
| 表題 | 目的 |
|---|---|
| seq | シーケンス番号 (0 始まりの連続した整数値) |
| version | バージョン名 |
| time | リリースされた日時 |
| classes | 分析されたクラス数 |
| NCSS | コメント文を除いた命令数 (Non Commenting Source Statements) |
| added | 前回のバージョンに存在したクラスにおける新規警告数 |
| newCode | 前回のバージョンに存在しなかったクラスにおける新規警告数 |
| fixed | 現在のバージョンに存在するクラスにおける除去された警告数 |
| removed | 現在のバージョンに存在しないクラスの前回のバージョンにおける警告数 |
| retained | 現在のバージョンと前回のバージョンの両方に存在する警告の数 |
| dead | 以前のバージョンに存在したが現在のバージョンにも直前のバージョンにも存在しない警告の数 |
| active | 現在のバージョンに存在する警告総数 |
このコマンドを使用することで、プロジェクト全体およびクラス毎・パッケージ毎の不良密度 (1000 NCSS 毎の警告数) に関する情報を一覧表示できます。標準入力から読み込む場合はファイル指定なしで、そうでなければ、コマンドラインでファイルを指定して、このコマンドを実行します。
出力される表は、次に示すカラムから成ります。また、プロジェクト全体情報の行、および、4 個以上の警告を含んでいる各パッケージ情報または各クラス情報の行も出力されます。
表12.5 defectDensity 出力のカラム一覧
| 表題 | 目的 |
|---|---|
| kind | プロジェクト (project)、パッケージ (package) またはクラス (class) |
| name | プロジェクト、パッケージまたはクラスの名前 |
| density | 1000 NCSS 毎の警告数 |
| bugs | 警告数 |
| NCSS | コメント文を除いた命令数 (Non Commenting Source Statements) |
このコマンドを使用することで、XML 形式のバグ警告を、 1 行 1 バグのテキスト形式、または、HTML形式に変換することができます。
この機能は、 ant からも使用することができます。まず次に示すように、ビルドファイルに convertXmlToText を taskdef で定義します :
- -<taskdef name="convertXmlToText" classname="edu.umd.cs.findbugs.anttask.ConvertXmlToTextTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
この ant タスクに指定できる属性を、下表に一覧で示します。
表12.6 convertXmlToText コマンドのオプション一覧
| コマンドラインオプション | Ant 属性 | 目的 |
|---|---|---|
| input="<filename>" | 入力ファイルを指定します。 | |
| output="<filename>" | 出力ファイルを指定します。 | |
| -longBugCodes | longBugCodes="[true|false]" | 2 文字のバグ略称の代わりに、省略なしのバグパターンコードを使用します。 |
| format="text" | プレーンテキストの出力が作成されます。1 行につき 1 つのバグが出力されます。コマンドライン時のデフォルトです。 | |
| -html[:stylesheet] | format="html:<stylesheet>" | 指定されたスタイルシートを使用して出力が作成されます (下記参照) 。省略した場合は、 default.xsl が使用されます。 |
-html/format オプションには、plain.xsl 、 default.xsl 、 fancy.xsl 、 fancy-hist.xsl または ユーザ自身が作成した XSL スタイルシートのいずれかを指定することができます。オプション名をよそに、 html 以外の形式を出力するスタイルシートを指定することもできます。FindBugs に含まれているスタイルシート(上述)以外のスタイルシートを使用する場合は、オプション -html/format で当該スタイルシートへのパスまたは URL を指定してください。
このコマンドを使用することで、指定したバグ警告にメタ情報を設定することができます。このコマンドには次に示すオプションがあります:
この機能は、 ant からも使用することができます。まず次に示すように、ビルドファイルに setBugDatabaseInfo を taskdef で定義します :
- -<taskdef name="setBugDatabaseInfo" classname="edu.umd.cs.findbugs.anttask.SetBugDatabaseInfoTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
この ant タスクに指定できる属性を、下表に一覧で示します。入力ファイルを指定するには、 input 属性を使用するか、 <datafile> 要素を入れ子にして入れてください。次に、例を示します:
-
-<setBugDatabaseInfo home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</setBugDatabaseInfo>
-
-表12.7 setBugDatabaseInfo オプション一覧
| コマンドラインオプション | Ant 属性 | 目的 |
|---|---|---|
| input="<file>" | 入力ファイルを指定します。 | |
| output="<file>" | 出力ファイルを指定します。 | |
| -name <name> | name="<name>" | 最新リビジョンの名前を設定します。 |
| -timestamp <when> | timestamp="<when>" | 最新リビジョンのタイム・スタンプを設定します。 |
| -source <directory> | source="<directory>" | ソースを検索するディレクトリーを追加指定します。 |
| -findSource <directory> | findSource="<directory>" | 指定したディレクトリー内を検索して関連するソースの場所を追加します。 |
| -suppress <filter file> | suppress="<filter file>" | 指定したファイルに一致する警告を抑止します (以前に指定した抑止設定は置き換えられます)。 |
| -withMessages | withMessages="[true|false]" | XMLにテキストメッセージを追加します。 |
| -resetSource | resetSource="[true|false]" | ソース検索パスをすべて削除します。 |
このコマンドの実行においては、コマンドラインで 0 個以上の xml バグデータベースファイル名を指定します。ファイル名を1つも指定しなければ、標準出力から読み込みを行いテーブルのヘッダーは生成されません。
このコマンドには 1 つだけオプションがあります : -formatDates を指定するとテキスト形式でデータが描画されます。
出力される表は、各バグデータベースごとに行を持ち、次に示すカラムから成ります :
表12.8 listBugDatabaseInfo カラム一覧
| カラム | 目的 |
|---|---|
| version | バージョン名 |
| time | リリースされた日時 |
| classes | 分析されたクラス数 |
| NCSS | コメント文を除いた命令数 (Non Commenting Source Statements) |
| total | 全警告数 |
| high | 優先度(高)の警告の総数 |
| medium | 優先度(中)の警告の総数 |
| low | 優先度(低)の警告の総数 |
| filename | データベースのファイル名 |
以下はすべて、 jdk1.6.0-b12, jdk1.6.0-b13, ..., jdk1.6.0-b60 のディレクトリに対してコマンドを実行しています。
以下のコマンドを実行してみます :
-computeBugHistory jdk1.6.0-b* | filterBugs -bugPattern IL_ | mineBugHistory -formatDates -
すると、次のような出力が行われます :
-seq version time classes NCSS added newCode fixed removed retained dead active -0 jdk1.6.0-b12 "Thu Nov 11 09:07:20 EST 2004" 13128 811569 0 4 0 0 0 0 4 -1 jdk1.6.0-b13 "Thu Nov 18 06:02:06 EST 2004" 13128 811570 0 0 0 0 4 0 4 -2 jdk1.6.0-b14 "Thu Dec 02 06:12:26 EST 2004" 13145 811786 0 0 2 0 2 0 2 -3 jdk1.6.0-b15 "Thu Dec 09 06:07:04 EST 2004" 13174 811693 0 0 1 0 1 2 1 -4 jdk1.6.0-b16 "Thu Dec 16 06:21:28 EST 2004" 13175 811715 0 0 0 0 1 3 1 -5 jdk1.6.0-b17 "Thu Dec 23 06:27:22 EST 2004" 13176 811974 0 0 0 0 1 3 1 -6 jdk1.6.0-b19 "Thu Jan 13 06:41:16 EST 2005" 13176 812011 0 0 0 0 1 3 1 -7 jdk1.6.0-b21 "Thu Jan 27 05:57:52 EST 2005" 13177 812173 0 0 0 0 1 3 1 -8 jdk1.6.0-b23 "Thu Feb 10 05:44:36 EST 2005" 13179 812188 0 0 0 0 1 3 1 -9 jdk1.6.0-b26 "Thu Mar 03 06:04:02 EST 2005" 13199 811770 0 0 0 0 1 3 1 -10 jdk1.6.0-b27 "Thu Mar 10 04:48:38 EST 2005" 13189 812440 0 0 0 0 1 3 1 -11 jdk1.6.0-b28 "Thu Mar 17 02:54:22 EST 2005" 13185 812056 0 0 0 0 1 3 1 -12 jdk1.6.0-b29 "Thu Mar 24 03:09:20 EST 2005" 13117 809468 0 0 0 0 1 3 1 -13 jdk1.6.0-b30 "Thu Mar 31 02:53:32 EST 2005" 13118 809501 0 0 0 0 1 3 1 -14 jdk1.6.0-b31 "Thu Apr 07 03:00:14 EDT 2005" 13117 809572 0 0 0 0 1 3 1 -15 jdk1.6.0-b32 "Thu Apr 14 02:56:56 EDT 2005" 13169 811096 0 0 0 0 1 3 1 -16 jdk1.6.0-b33 "Thu Apr 21 02:46:22 EDT 2005" 13187 811942 0 0 0 0 1 3 1 -17 jdk1.6.0-b34 "Thu Apr 28 02:49:00 EDT 2005" 13195 813488 0 1 0 0 1 3 2 -18 jdk1.6.0-b35 "Thu May 05 02:49:04 EDT 2005" 13457 829837 0 0 0 0 2 3 2 -19 jdk1.6.0-b36 "Thu May 12 02:59:46 EDT 2005" 13462 831278 0 0 0 0 2 3 2 -20 jdk1.6.0-b37 "Thu May 19 02:55:08 EDT 2005" 13464 831971 0 0 0 0 2 3 2 -21 jdk1.6.0-b38 "Thu May 26 03:08:16 EDT 2005" 13564 836565 0 0 0 0 2 3 2 -22 jdk1.6.0-b39 "Fri Jun 03 03:10:48 EDT 2005" 13856 849992 0 1 0 0 2 3 3 -23 jdk1.6.0-b40 "Thu Jun 09 03:30:28 EDT 2005" 15972 959619 0 2 0 0 3 3 5 -24 jdk1.6.0-b41 "Thu Jun 16 03:19:22 EDT 2005" 15972 959619 0 0 0 0 5 3 5 -25 jdk1.6.0-b42 "Fri Jun 24 03:38:54 EDT 2005" 15966 958581 0 0 0 0 5 3 5 -26 jdk1.6.0-b43 "Thu Jul 14 03:09:34 EDT 2005" 16041 960544 0 0 0 0 5 3 5 -27 jdk1.6.0-b44 "Thu Jul 21 03:05:54 EDT 2005" 16041 960547 0 0 0 0 5 3 5 -28 jdk1.6.0-b45 "Thu Jul 28 03:26:10 EDT 2005" 16037 960606 0 0 1 0 4 3 4 -29 jdk1.6.0-b46 "Thu Aug 04 03:02:48 EDT 2005" 15936 951355 0 0 0 0 4 4 4 -30 jdk1.6.0-b47 "Thu Aug 11 03:18:56 EDT 2005" 15964 952387 0 0 1 0 3 4 3 -31 jdk1.6.0-b48 "Thu Aug 18 08:10:40 EDT 2005" 15970 953421 0 0 0 0 3 5 3 -32 jdk1.6.0-b49 "Thu Aug 25 03:24:38 EDT 2005" 16048 958940 0 0 0 0 3 5 3 -33 jdk1.6.0-b50 "Thu Sep 01 01:52:40 EDT 2005" 16287 974937 1 0 0 0 3 5 4 -34 jdk1.6.0-b51 "Thu Sep 08 01:55:36 EDT 2005" 16362 979377 0 0 0 0 4 5 4 -35 jdk1.6.0-b52 "Thu Sep 15 02:04:08 EDT 2005" 16477 979399 0 0 0 0 4 5 4 -36 jdk1.6.0-b53 "Thu Sep 22 02:00:28 EDT 2005" 16019 957900 0 0 1 0 3 5 3 -37 jdk1.6.0-b54 "Thu Sep 29 01:54:34 EDT 2005" 16019 957900 0 0 0 0 3 6 3 -38 jdk1.6.0-b55 "Thu Oct 06 01:54:14 EDT 2005" 16051 959014 0 0 0 0 3 6 3 -39 jdk1.6.0-b56 "Thu Oct 13 01:54:12 EDT 2005" 16211 970835 0 0 0 0 3 6 3 -40 jdk1.6.0-b57 "Thu Oct 20 01:55:26 EDT 2005" 16279 971627 0 0 0 0 3 6 3 -41 jdk1.6.0-b58 "Thu Oct 27 01:56:30 EDT 2005" 16283 971945 0 0 0 0 3 6 3 -42 jdk1.6.0-b59 "Thu Nov 03 01:56:58 EST 2005" 16232 972193 0 0 0 0 3 6 3 -43 jdk1.6.0-b60 "Thu Nov 10 01:54:18 EST 2005" 16235 972346 0 0 0 0 3 6 3 -
次に示すコマンドを実行すると、db.xml 中間ファイルを生成することなく直接同じ情報を作成できます。
-computeBugHistory jdk1.6.0-b*/jre/lib/rt.xml | filterBugs -bugPattern IL_ db.xml | mineBugHistory -formatDates -
この情報を使って、 Sun JDK1.6.0 の各ビルドにおいて FindBugs によって発見された無限再起ループの数を表すグラフを表示します。青色の領域は、当該ビルドにおける無限再起ループの数を表しています。その上に描かれている赤色の領域は、以前のバージョンには存在したが当該バージョンでは除去された無限再起ループの数を表しています。 (したがって、赤色の領域と青色の領域を足し合わせた高さは決して減少しないことが保証されています。そして、新たに無限再起ループのバグが持ち込まれた時点で増加します) 。赤色の領域の高さは、当該バージョンにおいて修正または削除されたバグ数の合計で算出されます。バージョン 13 および 14 において見られる減少は、 FindBugs を使用して見つかった JDK のバグの報告を Sun が受け取ったことによるものです。

db.xml ファイルは、 jdk1.6.0 のすべてのビルドに対する検索結果を保持しています。したがって、次に示すコマンドを実行することで、優先度(高)または優先度(低)の正確性に関する警告の履歴が表示されます :
-filterBugs -priority M -category C db.xml | mineBugHistory -formatDates -
作成される表の例 :
-seq version time classes NCSS added newCode fixed removed retained dead active -0 jdk1.6.0-b12 "Thu Nov 11 09:07:20 EST 2004" 13128 811569 0 1075 0 0 0 0 1075 -1 jdk1.6.0-b13 "Thu Nov 18 06:02:06 EST 2004" 13128 811570 0 0 0 0 1075 0 1075 -2 jdk1.6.0-b14 "Thu Dec 02 06:12:26 EST 2004" 13145 811786 3 0 6 0 1069 0 1072 -3 jdk1.6.0-b15 "Thu Dec 09 06:07:04 EST 2004" 13174 811693 2 1 3 0 1069 6 1072 -4 jdk1.6.0-b16 "Thu Dec 16 06:21:28 EST 2004" 13175 811715 0 0 1 0 1071 9 1071 -5 jdk1.6.0-b17 "Thu Dec 23 06:27:22 EST 2004" 13176 811974 0 0 1 0 1070 10 1070 -6 jdk1.6.0-b19 "Thu Jan 13 06:41:16 EST 2005" 13176 812011 0 0 0 0 1070 11 1070 -7 jdk1.6.0-b21 "Thu Jan 27 05:57:52 EST 2005" 13177 812173 0 0 1 0 1069 11 1069 -8 jdk1.6.0-b23 "Thu Feb 10 05:44:36 EST 2005" 13179 812188 0 0 0 0 1069 12 1069 -9 jdk1.6.0-b26 "Thu Mar 03 06:04:02 EST 2005" 13199 811770 0 0 2 1 1066 12 1066 -10 jdk1.6.0-b27 "Thu Mar 10 04:48:38 EST 2005" 13189 812440 1 0 1 1 1064 15 1065 -11 jdk1.6.0-b28 "Thu Mar 17 02:54:22 EST 2005" 13185 812056 0 0 0 0 1065 17 1065 -12 jdk1.6.0-b29 "Thu Mar 24 03:09:20 EST 2005" 13117 809468 3 0 8 26 1031 17 1034 -13 jdk1.6.0-b30 "Thu Mar 31 02:53:32 EST 2005" 13118 809501 0 0 0 0 1034 51 1034 -14 jdk1.6.0-b31 "Thu Apr 07 03:00:14 EDT 2005" 13117 809572 0 0 0 0 1034 51 1034 -15 jdk1.6.0-b32 "Thu Apr 14 02:56:56 EDT 2005" 13169 811096 1 1 0 1 1033 51 1035 -16 jdk1.6.0-b33 "Thu Apr 21 02:46:22 EDT 2005" 13187 811942 3 0 2 1 1032 52 1035 -17 jdk1.6.0-b34 "Thu Apr 28 02:49:00 EDT 2005" 13195 813488 0 1 0 0 1035 55 1036 -18 jdk1.6.0-b35 "Thu May 05 02:49:04 EDT 2005" 13457 829837 0 36 2 0 1034 55 1070 -19 jdk1.6.0-b36 "Thu May 12 02:59:46 EDT 2005" 13462 831278 0 0 0 0 1070 57 1070 -20 jdk1.6.0-b37 "Thu May 19 02:55:08 EDT 2005" 13464 831971 0 1 1 0 1069 57 1070 -21 jdk1.6.0-b38 "Thu May 26 03:08:16 EDT 2005" 13564 836565 1 7 2 6 1062 58 1070 -22 jdk1.6.0-b39 "Fri Jun 03 03:10:48 EDT 2005" 13856 849992 6 39 5 0 1065 66 1110 -23 jdk1.6.0-b40 "Thu Jun 09 03:30:28 EDT 2005" 15972 959619 7 147 11 0 1099 71 1253 -24 jdk1.6.0-b41 "Thu Jun 16 03:19:22 EDT 2005" 15972 959619 0 0 0 0 1253 82 1253 -25 jdk1.6.0-b42 "Fri Jun 24 03:38:54 EDT 2005" 15966 958581 3 0 1 2 1250 82 1253 -26 jdk1.6.0-b43 "Thu Jul 14 03:09:34 EDT 2005" 16041 960544 5 11 15 8 1230 85 1246 -27 jdk1.6.0-b44 "Thu Jul 21 03:05:54 EDT 2005" 16041 960547 0 0 0 0 1246 108 1246 -28 jdk1.6.0-b45 "Thu Jul 28 03:26:10 EDT 2005" 16037 960606 19 0 2 0 1244 108 1263 -29 jdk1.6.0-b46 "Thu Aug 04 03:02:48 EDT 2005" 15936 951355 13 1 1 32 1230 110 1244 -30 jdk1.6.0-b47 "Thu Aug 11 03:18:56 EDT 2005" 15964 952387 163 8 7 20 1217 143 1388 -31 jdk1.6.0-b48 "Thu Aug 18 08:10:40 EDT 2005" 15970 953421 0 0 0 0 1388 170 1388 -32 jdk1.6.0-b49 "Thu Aug 25 03:24:38 EDT 2005" 16048 958940 1 11 1 0 1387 170 1399 -33 jdk1.6.0-b50 "Thu Sep 01 01:52:40 EDT 2005" 16287 974937 19 27 16 7 1376 171 1422 -34 jdk1.6.0-b51 "Thu Sep 08 01:55:36 EDT 2005" 16362 979377 1 15 3 0 1419 194 1435 -35 jdk1.6.0-b52 "Thu Sep 15 02:04:08 EDT 2005" 16477 979399 0 0 1 1 1433 197 1433 -36 jdk1.6.0-b53 "Thu Sep 22 02:00:28 EDT 2005" 16019 957900 13 12 16 20 1397 199 1422 -37 jdk1.6.0-b54 "Thu Sep 29 01:54:34 EDT 2005" 16019 957900 0 0 0 0 1422 235 1422 -38 jdk1.6.0-b55 "Thu Oct 06 01:54:14 EDT 2005" 16051 959014 1 4 7 0 1415 235 1420 -39 jdk1.6.0-b56 "Thu Oct 13 01:54:12 EDT 2005" 16211 970835 6 8 37 0 1383 242 1397 -40 jdk1.6.0-b57 "Thu Oct 20 01:55:26 EDT 2005" 16279 971627 0 0 0 0 1397 279 1397 -41 jdk1.6.0-b58 "Thu Oct 27 01:56:30 EDT 2005" 16283 971945 0 1 1 0 1396 279 1397 -42 jdk1.6.0-b59 "Thu Nov 03 01:56:58 EST 2005" 16232 972193 6 0 5 0 1392 280 1398 -43 jdk1.6.0-b60 "Thu Nov 10 01:54:18 EST 2005" 16235 972346 0 0 0 0 1398 285 1398 -44 jdk1.6.0-b61 "Thu Nov 17 01:58:42 EST 2005" 16202 971134 2 0 4 0 1394 285 1396 -
findbugs の実行とその後のデータ・マイニングツールの活用の両方を実行している ant スクリプトの完全な例を以下に示します :
-
-<project name="analyze_asm_util" default="findbugs">
- <!-- findbugs タスク定義 -->
- <property name="findbugs.home" value="/Users/ben/Documents/workspace/findbugs/findbugs" />
- <property name="jvmargs" value="-server -Xss1m -Xmx800m -Duser.language=en -Duser.region=EN -Dfindbugs.home=${findbugs.home}" />
-
- <path id="findbugs.lib">
- <fileset dir="${findbugs.home}/lib">
- <include name="findbugs-ant.jar"/>
- </fileset>
- </path>
-
- <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="computeBugHistory" classname="edu.umd.cs.findbugs.anttask.ComputeBugHistoryTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="setBugDatabaseInfo" classname="edu.umd.cs.findbugs.anttask.SetBugDatabaseInfoTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="mineBugHistory" classname="edu.umd.cs.findbugs.anttask.MineBugHistoryTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <!-- findbugs タスク定義 -->
- <target name="findbugs">
- <antcall target="analyze" />
- <antcall target="mine" />
- </target>
-
- <!-- 分析を行うタスク-->
- <target name="analyze">
- <!-- asm-util に対して findbugs を実行する -->
- <findbugs home="${findbugs.home}"
- output="xml:withMessages"
- timeout="90000000"
- reportLevel="experimental"
- workHard="true"
- effort="max"
- adjustExperimental="true"
- jvmargs="${jvmargs}"
- failOnError="true"
- outputFile="out.xml"
- projectName="Findbugs"
- debug="false">
- <class location="asm-util-3.0.jar" />
- </findbugs>
- </target>
-
- <target name="mine">
-
- <!-- 最新の分析結果に情報を設定する -->
- <setBugDatabaseInfo home="${findbugs.home}"
- withMessages="true"
- name="asm-util-3.0.jar"
- input="out.xml"
- output="out-rel.xml"/>
-
- <!-- 履歴ファイル (out-hist.xml) が既に存在するかどうかを確認する -->
- <condition property="mining.historyfile.available">
- <available file="out-hist.xml"/>
- </condition>
- <condition property="mining.historyfile.notavailable">
- <not>
- <available file="out-hist.xml"/>
- </not>
- </condition>
-
- <!-- このターゲットは、履歴ファイルが存在しないとき (初回) だけ実行されます -->
- <antcall target="history-init">
- <param name="data.file" value="out-rel.xml" />
- <param name="hist.file" value="out-hist.xml" />
- </antcall>
- <!-- 上記以外の場合に実行されます -->
- <antcall target="history">
- <param name="data.file" value="out-rel.xml" />
- <param name="hist.file" value="out-hist.xml" />
- <param name="hist.summary.file" value="out-hist.txt" />
- </antcall>
- </target>
-
- <!-- 履歴ファイルを初期化します -->
- <target name="history-init" if="mining.historyfile.notavailable">
- <copy file="${data.file}" tofile="${hist.file}" />
- </target>
-
- <!-- バグ履歴を算出します -->
- <target name="history" if="mining.historyfile.available">
- <!-- ${data.file} を ${hist.file} にマージします -->
- <computeBugHistory home="${findbugs.home}"
- withMessages="true"
- output="${hist.file}">
- <dataFile name="${hist.file}"/>
- <dataFile name="${data.file}"/>
- </computeBugHistory>
-
- <!-- 履歴を算出して ${hist.summary.file} に出力します -->
- <mineBugHistory home="${findbugs.home}"
- formatDates="true"
- noTabs="true"
- input="${hist.file}"
- output="${hist.summary.file}"/>
- </target>
-
-</project>
-
-FindBugs Eclipse プラグインを使用することによって、 FindBugs を Eclipse IDE で使用することができるようになります。このFindBugs Eclipse プラグインは、 Peter Friese 氏の多大な貢献によるものです。Phil Crosby 氏 と Andrei Loskutov 氏は、プラグインの重要な改良に貢献しました。
FindBugs Eclipse Plugin を使用するためには、 Eclipse 3.3 あるいはそれ以降のバージョン、また、 JRE/JDK 1.5 あるいはそれ以降のバージョンが必要です。
更新サイトが提供されています。更新サイトを利用して、機械的に FindBugs を Eclipse にインストールできます。また自動的に、最新版のアップデートを照会してインストールすることもできます。内容の異なる 3 つの更新サイトが存在します。
FindBugs Eclipse 更新サイト一覧
FindBugs の公式リリース物を提供します。
FindBugsの公式リリース物に加えて、公式リリース候補版を提供します。
FindBugsの日次ビルド物を提供します。コンパイルができること以上のテストは行われていません。
また、次に示すリンクから手動でプラグインをダウンロードすることもできます : http://prdownloads.sourceforge.net/findbugs/edu.umd.cs.findbugs.plugin.eclipse_2.0.0.20111220.zip?download. 展開して Eclipse の「plugins」サブディレクトリーに入れてください。(そうすると、 <eclipse インストールディレクトリー >/plugins/edu.umd.cs.findbugs.plugin.eclipse_2.0.0.20111220/findbugs.png が FindBugs のロゴファイルへのパスになるはずです。)
プラグインの展開ができたら、 Eclipse を起動して → → を選択してください。「FindBugs Project」から提供された「FindBugs Plug-in」というプラグインがあることを確認してください。
実行するには、 Java プロジェクト上で右クリックして「Find Bugs」を選択します。FindBugs が実行されて、バグパターンの実例の可能性があると識別されたコード箇所に問題マーカーがつきます。 (ソース画面および Eclipse 問題ビューに表示されます。)
Java プロジェクトのプロパティーダイアログを開いて「Findbugs」プロパティーページを選択することで、 FindBugs の動作をカスタマイズすることができます。選択できる項目には次のようなものがあります :
「Run FindBugs Automatically」チェックボックスの設定。チェックすると、プロジェクト内の Java クラスが修正されるたびに FindBugs が実行されます。
優先度とバグカテゴリーの選択。これらのオプションは、どの警告を表示するかを選択します。例えば、優先度で 「Medium」 を選択すると、優先度 (中) および優先度 (高) の警告のみが表示されます。同様に、「Style」チェックボックスのチェックマークを外すと、Style カテゴリーに属する警告は表示されません。
ディテクタの選択。表からプロジェクトで有効にしたいディテクタを選択することができます。
FindBugs Eclipse プラグインは、まだ実験段階です。このセクションでは、プラグインに関する一般的な問題と (判明していれば) それらの問題の解決方法を記述します。
FindBugs 問題マーカーが (ソース画面および問題ビューに) 表示されない場合は、問題ビューのフィルター設定を変更してください。詳細情報は http://findbugs.sourceforge.net/FAQ.html#q7 を参照してください。
フィルターファイルを使用することで、特定のクラスやメソッドをバグ報告に含めたりバグ報告から除外したりすることができます。この章では、フィルターファイルの使用方法を説明します。
![]() | 計画されている機能 |
|---|---|
フィルターは現在、コマンドラインインタフェースでのみサポートされています。最終的には、フィルターのサポートは GUI にも追加される予定です。 |
-
概念的に言えば、フィルターはバグ検索結果をある基準と照合します。フィルターを定義することで、 特別な取り扱いをするバグ検索結果を選択することができます。例えば、あるバグ検索結果をバグ報告に含めたり、バグ報告から除外したりすることができます。
フィルターファイルは、 XML 文書です。最上位要素が FindBugsFilter 要素 であり、その子要素として Match 要素を複数個定義します。それぞれの Match 要素は、生成されたバグ検索結果に適用される述部にあたります。通常、フィルターはバグ検索結果を除外するために使用します。次に、例を示します:
-$findbugs -textui -excludemyExcludeFilter.xmlmyApp.jar-
また一方で、的をしぼった報告を得るためにバグ報告結果を選択するためにフィルターを使用することも考えられます :
-$findbugs -textui -includemyIncludeFilter.xmlmyApp.jar-
-
-Match 要素は子要素を持ちます。それらの子要素は論理積で述部になります。つまり、述部が真であるためには、すべての子要素が真である必要があります。
<Bug>この要素は、バグパターンを指定して照合します。pattern 属性には、コンマ区切りでバグパターン類型のリストを指定します。どの警告がどのバグパターン類型にあたるかは、 -xml オプションをつかって出力されたもの (BugInstance 要素の type 属性) を見るか、または、 バグ解説ドキュメントを参照してください。
もっと粒度の粗い照合を行いたいときは、 code 属性を使用してください。バグ略称のコンマ区切りのリストで指定できます。さらに粒度の粗い照合を行いたいときは、 category 属性を使用してください。次に示す、バグカテゴリー名のコンマ区切りのリストで指定できます : CORRECTNESS, MT_CORRECTNESS, BAD_PRACTICICE, PERFORMANCE, STYLE.
同じ <Bug> 要素に上記の属性を複数指定した場合は、バグパターン名、バグ略称、バグカテゴリーのいずれか1つでも該当すれば、バグパターンは合致すると判定されます。
下位互換性を持たせたい場合は、 <Bug> 要素の代わりに <BugPattern> 要素および <BugCode> 要素を使用してください。これらの要素はそれぞれ、 name 属性で値のリストを指定します。これらの要素は、将来サポートされなくなる可能性があります。
<Priority>この要素は、特定の優先度をもつ警告を照合します。value 属性には、整数値を指定します : 1 は優先度(高)、また、 2 は優先度(中) 、 3 は優先度(低) を示します。
<Package>この要素は、 name 属性で指定した特定のパッケージ内にあるクラスに関連した警告を照合します。入れ子のパッケージは含まれません (Java import 文に従っています) 。しかしながら、正規表現を使うと複数パッケージにマッチさせることは簡単にできます。
<Class>この要素は、特定のクラスに関連した警告を照合します。name 属性を使用して、照合するクラス名をクラス名そのものか、または、正規表現で指定します。
下位互換性を持たせたい場合は、この要素の代わりに Match 要素を使用してください。クラス名そのものの指定は class 属性を、クラス名を正規表現で指定する場合は classregex 属性をそれぞれ使用してください
もし Match 要素に Class 要素が無かったり、 class / classregex 属性が無かったりした場合は、すべてのクラスに適用されます。その場合、想定外に多くのバグ検索結果が一致してしまうことがあり得ます。その場合は、適当なメソッドやフィールドで絞り込んでください。
<Method>この要素は、メソッドを指定します。name 属性を使用して、照合するメソッド名をメソッド名そのものか、または、正規表現で指定します。params 属性には、コンマ区切りでメソッド引数の型のリストを指定します。returns 属性にはメソッドの戻り値の型を指定します。params および returns においては、クラス名は完全修飾名である必要があります。(例えば、単に "String" ではなく "java.lang.String" としてください。) params returns のどちらか一方を指定した場合は、もう一方の属性の指定も必須です。なぜならば、メソッドシグニチャーを構築のために必要だからです。name 属性、params 属性 および returns 属性または 3 つの 属性すべて、のどれかを条件とすることできることを意味しています。このように、名前とシグニチャーに基づく様々な種類の条件を規定できます。
<Field>この要素は、フィールドを指定します。name 属性を使用して、照合するフィールド名をフィールド名そのものか、または、正規表現で指定します。また、フィールドのシグニチャーに照らしたフィルタリングをすることができます。 type 属性を使用して、フィールドの型を完全修飾名で指定してください。名前とシグニチャーに基づく条件を規定するために、その2つの属性を両方とも指定することができます。
<Local>この要素は、ローカル変数を指定します。name 属性を使用して、照合するローカル変数名をローカル変数名そのものか、または、正規表現で指定します。ローカル変数とは、メソッド内で定義した変数です。
<Or>この要素は、論理和として Match 条項を結合します。すなわち、2つの Method 要素を Or 条項に入れることで、どちらか一方のメソッドでマッチさせることができます。
Class 、 Method または Field の name 属性が文字 ~ で始まっている場合は、属性値の残りの部分を Java の正規表現として解釈します。そうして、当該 Java 要素の名前に対しての照合が行われます。
パターンの照合は要素の名前全体に対して行われることに注意してください。そのため、部分一致照合を行いたい場合はパターン文字列の前後に .* を付加して使用する必要があります。
パターンの構文規則に関しては、 java.util.regex.Pattern のドキュメントを参照してください。
-Match 条項は、バグ検索結果に実際に含まれている情報にのみ一致します。すべてのバグ検索結果はクラスを持っています。したがって、一般的に言って、バグを除外するためにはクラスを用いて行うとうまくいくことが多いです。
バグ検索結果の中には、2個以上のクラスを保持しているものもあります。例えば、 DE (dropped exception : 例外の無視) バグは、 例外の無視が発生したメソッドを持っているクラスと、 無視された例外の型を表すクラスの両方を含んだ形で報告されます。Match 条項とは、 1番目 (主) のクラスのみが照合されます。したがって、例えば、クラス "com.foobar.A" 、 "com.foobar.B" 間での IC (initialization circularity : 初期化時の処理循環) バグ報告を抑止したい場合、以下に示すように 2つの Match 条項を使用します :
- <Match> - <Class name="com.foobar.A" /> - <Bug code="IC" /> - </Match> - - <Match> - <Class name="com.foobar.B" /> - <Bug code="IC" /> - </Match> -
明示的に両方のクラスで照合することによって、循環しているどちらのクラスがバグ検索結果の 1 番目になっているかに関係なく一致させることができます。(もちろんこの方法は、処理循環が "com.foobar.A" 、 "com.foobar.B" に加えて3番目のクラスも含んでいる場合は図らずも失敗してしまう恐れがあります。)
多くの種類のバグ報告は、自身が出現したメソッドを報告します。それらのバグ検索結果に対しては、 Method 条項を Match 要素に加えると期待通りの動作をするでしょう。
1. 特定のクラスに対するすべてのバグ報告に一致させます。
- - <Match> - <Class name="com.foobar.MyClass" /> - </Match> - -
- -
2. バグ略称を指定して、特定のクラスに対する特定の検査項目に一致させます。
- - <Match> - <Class name="com.foobar.MyClass"/ > - <Bug code="DE,UrF,SIC" /> - </Match> - -
-
3. バグ略称を指定して、すべてのクラスに対する特定の検査項目に一致させます。
- - <Match> - <Bug code="DE,UrF,SIC" /> - </Match> - -
-
4. バグカテゴリーを指定して、すべてのクラスに対する特定の検査項目に一致させます。
- - <Match> - <Bug category="PERFORMANCE" /> - </Match> - -
-
5. バグ略称を指定して、特定のクラスの指定されたメソッドに対する特定のバグ種別に一致させます。
- - <Match> - <Class name="com.foobar.MyClass" /> - <Or> - <Method name="frob" params="int,java.lang.String" returns="void" /> - <Method name="blat" params="" returns="boolean" /> - </Or> - <Bug code="DC" /> - </Match> - -
-
6. 特定のメソッドに対する特定のバグパターンに一致させます。
- - <!-- open stream に関する誤検出があるメソッド。--> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="writeDataToFile" /> - <Bug pattern="OS_OPEN_STREAM" /> - </Match> - -
-
7. 特定のメソッドに対する特定の優先度を付与された特定のバグパターンに一致させます。
- - <!-- dead local store (優先度 (中)) に関する誤検出があるメソッド。--> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="someMethod" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Priority value="2" /> - </Match> - -
-
8. AspectJ コンパイラーによって引き起こされるマイナーバグに一致させます (AspectJ の開発者でもない限り、それらのバグに関心を持つことはないと考えます)。
- - <Match> - <Class name="~.*\$AjcClosure\d+" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Method name="run" /> - </Match> - <Match> - <Bug pattern="UUF_UNUSED_FIELD" /> - <Field name="~ajc\$.*" /> - </Match> - -
-
9. 基盤コードの特定の部分に対するバグに一致させます
- - <!-- すべてのパッケージにある Messages クラスに対する unused fields 警告に一致。 --> - <Match> - <Class name="~.*\.Messages" /> - <Bug code="UUF" /> - </Match> - <!-- すべての internal パッケージ内の mutable statics 警告に一致。 --> - <Match> - <Package name="~.*\.internal" /> - <Bug code="MS" /> - </Match> - <!-- ui パッケージ階層内の anonymoous inner classes 警告に一致。 --> - <Match> - <Package name="~com\.foobar\.fooproject\.ui.*" /> - <Bug pattern="SIC_INNER_SHOULD_BE_STATIC_ANON" /> - </Match> - -
-
10. 特定のシグニチャーを持つフィールドまたはメソッドのバグに一致させます。
- - <!-- すべてのクラスの main(String[]) メソッドに対する System.exit(...) usage 警告に一致。 --> - <Match> - <Method returns="void" name="main" params="java.lang.String[]" /> - <Method pattern="DM_EXIT" /> - </Match> - <!-- すべてのクラスの com.foobar.DebugInfo 型のフィールドに対する UuF 警告に一致。 --> - <Match> - <Field type="com.foobar.DebugInfo" /> - <Bug code="UuF" /> - </Match> - -
- -
- -<FindBugsFilter> - <Match> - <Class name="com.foobar.ClassNotToBeAnalyzed" /> - </Match> - - <Match> - <Class name="com.foobar.ClassWithSomeBugsMatched" /> - <Bug code="DE,UrF,SIC" /> - </Match> - - <!-- XYZ 違反に一致。--> - <Match> - <Bug code="XYZ" /> - </Match> - - <!-- "AnotherClass" の特定のメソッドの doublecheck 違反に一致。--> - <Match> - <Class name="com.foobar.AnotherClass" /> - <Or> - <Method name="nonOverloadedMethod" /> - <Method name="frob" params="int,java.lang.String" returns="void" /> - <Method name="blat" params="" returns="boolean" /> - </Or> - <Bug code="DC" /> - </Match> - - <!-- dead local store (優先度 (中)) に関する誤検出があるメソッド。--> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="someMethod" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Priority value="2" /> - </Match> -</FindBugsFilter> - -
この章では、FindBugs グラフィカルユーザーインタフェース (GUI) の使用方法を説明します。
findbugs コマンドで FindBugs を起動してから、メニューで → を選択してください。そうすると、次のようなダイアログが表示されます:

-
「Class archives and directories to analyze」テキストフィールドの横にある 「Add」ボタンを押すと、バグを分析する java クラスを含んでいる Java アーカイブファイル (zip, jar, ear, or war file) を選択して指定できます。複数の アーカイブ/ディレクトリーを追加することが可能です。
また、分析を行う Java アーカイブのソースコードを含んだソースディレクトリーを指定することもできます。そうすると、バグの可能性があるソースコードの場所が、FindBugs 上でハイライトして表示されます。ソースディレクトリーは、Java パッケージ階層のルートディレクトリーを指定する必要があります。例えば、ユーザのアプリケーションが org.foobar.myapp パッケージの中にある場合は、 org ディレクトリーの親ディレクトリーをソースディレクトリーリストに指定する必要があります。
もうひとつ、任意指定の手順があります。それは、補助用の Jar ファイルおよびディレクトリーを 「Auxiliary classpath locations」のエントリーに追加することです。分析するアーカイブ/ディレクトリーにも標準の実行時クラスパスにも含まれていないクラスを、分析するアーカイブ/ディレクトリーが参照している場合は、この項目を設定した方がいいでしょう。クラス階層に関する情報を使用するバグディテクタが、 FindBugs にはいくつかあります。したがって、FindBugs が分析を行うクラスの完全なクラス階層を参照できれば、より正確な分析結果を取得することができます。
アーカイブ、ディレクトリーおよびソースディレクトリーの指定ができれば、「Finish」ボタンを押して Jar ファイルに含まれるクラスに対する分析を実行します。巨大なプロジェクトを古いコンピュータ上で実行すると、かなりの時間(数十分)がかかることに注意してください。大容量メモリである最近のコンピュータなら、大きなプログラムであっても数分程度で分析できます。
分析が完了すると、次のような画面が表示されます :

-
左上のペインにはバグ階層ツリーが表示されます。これは、分析でみつかったバグの検索結果が階層的に表示されたものです。
上部のペインでバグ検索結果を選択すると、下部の「Details」ペインにバグの詳細説明が表示されます。更に、ソースがみつかれば、右上のソースコードペインにバグの出現箇所に該当するソースコードが表示されます。上図の例で表示されているバグは、ストリームオブジェクトがクローズされていないというものです。ソースコード・ウィンドウにおいて当該ストリームオブジェクトを生成している行がハイライトされています。
バグの検索結果に対してテキストで注釈を入れることができます。階層ツリー図のすぐ下にあるテキストボックスに注釈を入力してください。記録しておきたい情報を何でも自由に入力することができます。バグ結果ファイルの保存および読み込みを行ったときに、注釈も保存されます。
メニュー項目から → を選択すると、ユーザーの作業結果を保存することができます。「Save as...」ダイアログにあるドロップダウン・リストの中から「FindBugs analysis results (.xml)」を選択ことで、ユーザーが指定した jar ファイルリストやバグ検索結果などの作業結果を保存することができます。また、jar ファイルリストのみを保存する選択肢 (「FindBugs project file (.fbp)」) やバグ検索結果のみを保存する選択肢 (「FindBugs analysis file (.fba)」) もあります。保存したファイルは、メニュー項目から → を選択することで、読み込むことができます。
製作著作 © 2003, 2004, 2005, 2006, 2008 University of Maryland
このマニュアルは、クリエイティブ・コモンズ表示-非営利-継承に基づく使用許諾がなされています。使用許諾書をご覧になる場合は、 http://creativecommons.org/licenses/by-nc-sa/1.0/ にアクセスするか、クリエイティブ・コモンズ(559 Nathan Abbott Way, Stanford, California 94305, USA)に書簡を送付してください。
名称「FindBugs」および FindBugs のロゴは、メリーランド大学の登録商標です。
21:17:55 EST, 20 December, 2011
目次
表の一覧
この章では、 FindBugs のインストール方法を説明します。
FindBugs をインストールする最も簡単な方法は、バイナリ配布物をダウンロードすることです。 バイナリ配布物は、 gzipped tar 形式 および zip 形式 がそれぞれ入手可能です。バイナリ配布物をダウンロードしてきたら、それを任意のディレクトリーに展開します。
gzipped tar 形式配布物の展開方法例:
-$ gunzip -c findbugs-2.0.0.tar.gz | tar xvf -
--
zip 形式配布物の展開方法例:
-C:\Software>unzip findbugs-2.0.0.zip
--
バイナリ配布物の展開すると、通常は findbugs-2.0.0 ディレクトリーが作成されます。例えば、ディレクトリー C:\Software でバイナリ配布物を展開すると、ディレクトリー C:\Software\findbugs-2.0.0 に FindBugs は展開されます。このディレクトリーが FindBugs のホームディレクトリーになります。このマニュアルでは、このホームディレクトリーを $FINDBUGS_HOME (Windowsでは %FINDBUGS_HOME%) を用いて参照します。
目次
FindBugs™ は、Java プログラムの中のバグを見つけるプログラムです。このプログラムは、「バグ パターン」の実例を探します。「バグ パターン」とは、エラーとなる可能性の高いコードの事例です。
この文書は、FindBugs バージョン 2.0.0 について説明してます。私たちは、 FindBugs に対するフィードバックを心待ちにしています。どうぞ、 FindBugs Web ページ にアクセスしてください。FindBugs についての最新情報、連絡先および FindBugs メーリングリストなどのサポート情報を入手することができます。
FindBugs を使用するには、 Java 2 Standard Edition, バージョン 1.5 以降のバージョンと互換性のあるランタイム環境が必要です。FindBugs は、プラットフォーム非依存であり、 GNU/Linux 、 Windows 、 MacOS X プラットフォーム上で動作することが知られています。
FindBugs を使用するためには、少なくとも 512 MB のメモリが必要です。巨大なプロジェクトを解析するためには、それより多くのメモリが必要とされることがあります。
名称「FindBugs」および FindBugs のロゴは、メリーランド大学の登録商標です。FindBugs はフリーソフトウェアであり、 Lesser GNU Public License の条件で配布されています。使用承諾書を入手したい場合は、 FindBugs 配布物に含まれる LICENSE.txt ファイルを参照してください。
最新バージョンの FindBugs および そのソースコードは FindBugs web ページ で入手できます。
プロジェクトに多くの jar ファイル があったり、 jar ファイルが多くのディレクトリに点在したりする場合は、 rejarForAnalysis スクリプトを使用すると FindBugs の実行が比較的簡単になります。このスクリプトは、数多い jar ファイルを集めて 1 つの大きな jar ファイルに結合します。そうすると、分析時にFindBugs に jar ファイルを設定することが比較的簡単になります。このスクリプトは、 unix システムの 'find' コマンドと組み合わせるととりわけ有用になります ; 次に例を示します。 find . -name '*.jar' | xargs rejarForAnalysis .
また、 rejarForAnalysis スクリプトは巨大なプロジェクトを複数の jar ファイルに分割することに使用できます。プロジェクトのクラスファイルは、複数の jar ファイルに均等に配分されます。これは、プロジェクト全体に対して FindBugs を実行すると時間とメモリ消費が著しい場合に有用です。プロジェクト全体に対して FindBugs を実行する代わりに、 rejarForAnalysis ですべてのクラスを含む大きな jar ファイルを構築します。続いて、 rejarForAnalysis を再び実行して複数の jar ファイルに分割します。そして、各々の jar ファイルに対して順に FindBugs を実行します。その際、 -auxclasspath に最初に 1 つにまとめた jar ファイルを指定してください。
rejarForAnalysis スクリプトに指定することができるオプションを以下に示します :
日数最後に更新された日からの経過時間を日単位で指定します (指定した日数より古い jar ファイルは無視されます)。
ファイル名jar ファイル名を記載したテキストファイルを指定します。
クラス数analysis*.jar ファイル 1 ファイルに対するクラスの最大数を指定します。
プレフィックス分析するクラス名のプレフィックスを指定します (例、 edu.umd.cs.) 。
FindBugs には2つのユーザーインタフェースがあります。すなわち、グラフィカルユーザーインタフェース (GUI) および コマンドラインインタフェースです。この章では、それぞれのインタフェースの実行方法について説明します。
![]() | 警告 |
|---|---|
この章は、現在書き直し中です。書き直しはまだ完了していません。 |
Windows システムで FindBugs を起動する場合は、 ファイルをダブルクリックしてください。 FindBugs GUI が起動します。%FINDBUGS_HOME%\lib\findbugs.jar
Unix 、 Linux または Mac OS X システムの場合は、 スクリプトを実行するか、以下のコマンドを実行します。$FINDBUGS_HOME/bin/findbugs
-java -jar $FINDBUGS_HOME/lib/findbugs.jarこれで、 FindBugs GUI が起動します。
GUI の使用方法については、 5章FindBugs GUI の使用方法 を参照してください。
このセクションでは、 FindBugs の起動方法を説明します。FindBugs を起動するには2つの方法があります。すなわち、直接起動する方法、および、ラップしているスクリプトを使用する方法です。
最初に述べる FindBugs の起動方法は、 を直接実行する方法です。JVM (java) 実行プログラムの -jar コマンドラインスイッチを使用します。(FindBugsのバージョンが 1.3.5 より前の場合は、ラップしているスクリプトを使用する必要があります。)$FINDBUGS_HOME/lib/findbugs.jar
FindBugs を直接起動するための、一般的な構文は以下のようになります。
- java [JVM 引数] -jar $FINDBUGS_HOME/lib/findbugs.jar オプション…
--
1 番目のコマンドラインオプションは、起動する FindBugs ユーザーインタフェースを選択するためのものです。指定可能な値は次の通りです:
- -gui: グラフィカルユーザーインタフェース (GUI) を起動します。
- -textui: コマンドラインインタフェースを起動します。
- -version: FindBugs のバージョン番号を表示します。
- -help: FindBugs コマンドラインインタフェースのヘルプ情報を表示します。
- -gui1: 最初に作成された FindBugs グラフィカルユーザーインタフェース(すでに廃止されサポートされていない)を起動します。
FindBugs を起動するもうひとつの方法は、ラップしているスクリプトを使用する方法です。
Unix 系のシステムにおいては、次のようなコマンドでラップしているスクリプトを起動します :
-$$FINDBUGS_HOME/bin/findbugsオプション…-
-
Windows システムにおいては、ラップしているスクリプトを起動するコマンドは次のようになります。
-C:\My Directory>%FINDBUGS_HOME%\bin\findbugs.batオプション…-
-
Unix 系システム および Windows システムのどちらにおいても、ディレクトリー を環境変数 $FINDBUGS_HOME/binPATH に追加するだけで、 findbugs コマンドを使用して FindBugs を起動することができます。
FindBugs のラップしているスクリプトは、次のようなコマンドラインオプションをサポートしています。これらのコマンドラインオプションは FindBugs プログラム 自体が操作するのではなく、どちらかといえば、ラップしているスクリプトの方が処理を行います。
引数JVM に受け渡される引数を指定します。例えば、次のような JVM プロパティが設定できます:
-$findbugs -textui -jvmArgs "-Duser.language=ja"myApp.jar-
-
ディレクトリーFindBugs の実行に使用する JRE (Java ランタイム環境) がインストールされているディレクトリーを指定します。
サイズJava ヒープサイズの最大値をメガバイト単位で指定します。デフォルトは、 256 です。巨大なプログラムやライブラリを分析するには、もっと大きなメモリー容量が必要になる可能性があります。
ディテクタ実行およびクラス分析のトレース情報が標準出力に出力されます。分析が予期せず失敗した際の、トラブルシューティングに有用です。
name=valueこのオプションを使用してシステムプロパティーを設定することができます。 FindBugs はシステムプロパティーを使用して分析特性の設定を行います。9章分析プロパティー を参照してください。このオプションを複数指定して、複数のシステムプロパティを設定することが可能です。注: Windows の多くのバージョンでは、 name=value 文字列を引用符で囲む必要があります。
このセクションでは、 FindBugs がサポートするコマンドラインオプションについて説明します。ここで示すコマンドラインオプションは、 FindBugs 直接起動、または、ラップしているスクリプトによる起動で使用できます。
ここで示すオプションは、 GUI および コマンドラインインタフェースの両方で使用できます。
このオプションを指定すると、精度を上げるために大量のメモリーを消費する分析が無効になります。FindBugs の実行時にメモリー不足になったり、分析を完了するまでに異常に長い時間がかかる場合に試してみてください。
精度が高く、より多くのバグを検出する分析を有効にします。ただし、多くのメモリー容量を必要とし、また、完了までの時間が多くかかる可能性があります。
project分析するプロジェクトを指定します。指定するプロジェクトファイルには、 GUI を使って作成したものを使用してください。ファイルの拡張子は、一般的には .fb または .fbp です。
ここで示すオプションは、グラフィカルユーザーインタフェースでのみ使用できます。
plastic|gtk|nativeSwing のルック・アンド・フィールを設定します。
-
ここで示すオプションは、テキストユーザーインタフェースでのみ使用できます。
報告されるバグ検索結果をクラス名でソートします。
filterFile.xmlfilterFile.xml で指定したフィルターに一致したバグ検索結果のみ報告されます。8章フィルターファイル を参照してください。
filterFile.xmlfilterFile.xml で指定したフィルターに一致したバグ検索結果は報告されません。8章フィルターファイル を参照してください。
com.foobar.MyClass,com.foobar.mypkg.*コンマ区切りで指定したクラスおよびパッケージのみに限定して、バグ検出の分析を行うようにします。フィルターと違って、このオプションを使うと一致しないクラスおよびパッケージに対する分析の実行を回避することができます。大きなプロジェクトにおいて、このオプションを活用すると分析にかかる時間を大きく削減することができる可能性があります。(しかしながら、アプリケーションの全体で実行していないために不正確な結果を出してしまうディテクタがある可能性もあります。) クラスはパッケージも含んだ完全な名前を指定する必要があります。また、パッケージは、 Java の import 文でパッケージ下のすべてのクラスをインポートするときと同じ方法で指定します。 (すなわち、パッケージの完全な名前に .* を付け加えた形です。).* の代わりに .- を指定すると、サブパッケージも含めてすべてが分析されます。
すべてのバグが報告されます。
優先度 (中) および優先度 (高) のバグが報告されます。これは、デフォルトの設定値です。
優先度 (高) のバグのみが報告されます。
手抜き報告モードです。このオプションを指定すると、多くのディテクタにおいて 誤検出を回避するためのヒューリスティック機能が抑止されます。
バグ報告が XML で作成されます。作成された XML データは 、後で GUI で見ることができます。このオプションは -xml:withMessages と指定することもできます。こうすると 出力 XML には 各バグに関して人間に読むことができるメッセージが含まれるようになります。このオプションで作成された XML ファイルは 報告書に変換するのが簡単です。
HTML 出力が生成されます。デフォルトでは FindBugs は default.xsl XSLT スタイルシートを使用して HTML 出力を生成します: このファイルは、 findbugs.jar の中、または、 FindBugs のソース配布物もしくはバイナリ配布物の中にあります。このオプションには、次のようなバリエーションも存在します。すなわち、 -html:plain.xsl 、 -html:fancy.xsl および -html:fancy-hist.xsl です。plain.xsl スタイルシートは Javascript や DOM を利用しません。したがって、古いWeb ブラウザ使用時や印刷時にも比較的うまく表示されるでしょう。fancy.xsl スタイルシートは DOM と Javascript を利用してナビゲーションを行います。また、ビジュアル表示に CSS を使用します。fancy-hist.xsl は fancy.xsl スタイルシートを更に進化させたものです。DOM や Javascript をふんだんに駆使して、バグの一覧を動的にフィルタリングします。
ユーザー自身の XSLT スタイルシートを用いて HTML への変換を行いたい場合は、 -html:myStylesheet.xsl のように指定してください。ここで、 myStylesheet.xsl はユーザーが使用したいスタイルシートのファイル名です。
バグ報告が Emacs 形式で作成されます。
バグ報告が xdoc XML 形式で作成されます。Apache Mavenで使用できます。
ファイル名指定したファイルに出力結果が作成されます。
ファイル名この引数は、使用すべきではありません。代わりに、 -output を使用してください。
[:true|false]このオプションは、ファイルやディレクトリーの中で入れ子になった jar および zip ファイルを分析するかどうかを指定します。デフォルトでは、入れ子になった jar および zip ファイルも分析します。入れ子になった jar および zip ファイルの分析するを無効にする場合は、 -nested:false をコマンドライン引数に追加してください。
クラスパス分析時に使用する補助クラスパスを設定します。分析するプログラムで使用するjarファイルやクラスディレクトリーをすべて指定してください。補助クラスパスに指定したクラスは分析の対象にはなりません。
-
|
-
-
-
-FindBugs Links- -This page contains links to related projects, -including tools that are similar to FindBugs. - - FindBugs Add-Ons- -
Similar Tools- -Open source tools- -
Commercial tools and services- -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-FindBugs Mailing Lists- -There are two mailing lists for FindBugs. -
- - Send comments to findbugs@cs.umd.edu - |
-
-
---Copyright (c) 2000-2005 INRIA, France Telecom -All rights reserved. - - --Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - -- - -- - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -
-- --Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. - - --Redistribution and use of this software and associated documentation -("Software"), with or without modification, are permitted provided that -the following conditions are met: - - -- - -- - Redistributions of source code must retain copyright statements and - notices. Redistributions must also contain a copy of this document. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - The name "DOM4J" must not be used to endorse or promote products - derived from this Software without prior written permission - of MetaStuff, Ltd. For written permission, please contact - dom4j-info@metastuff.com . -- - Products derived from this Software may not be called "DOM4J" nor may - "DOM4J" appear in their names without prior written permission of - MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. - - - Due credit should be given to the DOM4J Project ( http://dom4j.org/ ). --THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' -AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -
Table of Contents
FindBugs was originally written by Bill Pugh (<pugh@cs.umd.edu>).
-David Hovemeyer (<daveho@cs.umd.edu>) implemented some of the
-detectors, added the Swing GUI, and is a co-maintainer.
Mike Fagan (<mfagan@tde.com>) contributed the Ant build script,
-the Ant task, and several enhancements and bug fixes to the GUI.
Germano Leichsenring contributed Japanese translations of the bug -summaries.
David Li contributed the Emacs bug report format.
Peter D. Stout contributed recursive detection of Class-Path -attributes in analyzed Jar files, German translations of -text used in the Swing GUI, and other fixes.
Peter Friese wrote the FindBugs Eclipse plugin.
Rohan Lloyd contributed several Mac OS X enhancements, -bug detector improvements, -and maintains the Fink package for FindBugs.
Hiroshi Okugawa translated the FindBugs manual and -more of the bug summaries into Japanese.
Phil Crosby enhanced the Eclipse plugin to add a view -to display the bug details.
Dave Brosius fixed a number of bugs, added user preferences -to the Swing GUI, improved several bug detectors, and -contributed the string concatenation detector.
Thomas Klaeger contributed a number of bug fixes and -bug detector improvements.
Andrei Loskutov made a number of improvements to the -Eclipse plugin.
Brian Goetz contributed a major refactoring of the -visitor classes to improve readability and understandability.
Pete Angstadt fixed several problems in the Swing GUI.
Francis Lalonde provided a task resource file for the -FindBugs Ant task.
Garvin LeClaire contributed support for output in -Xdocs format, for use by Maven.
Holger Stenzhorn contributed improved German translations of items -in the Swing GUI.
Juha Knuutila contributed Finnish translations of items -in the Swing GUI.
Tanel Lebedev contributed Estonian translations of items -in the Swing GUI.
Hanai Shisei (ruimo) contributed full Japanese translations of -bug messages, and text used in the Swing GUI.
David Cotton contributed Fresh translations for bug -messages and for the Swing GUI.
Michael Tamm contributed support for the "errorProperty" attribute -in the Ant task.
Thomas Kuehne improved the German translation of the Swing GUI.
Len Trigg improved source file support for the Emacs output mode.
Greg Bentz provided a fix for the hashcode/equals detector.
K. Hashimoto contributed internationalization fixes and several other - bug fixes.
- Glenn Boysko contributed support for ignoring specified local - variables in the dead local store detector. -
- Jay Dunning contributed a detector to find equality comparisons - of floating-point values, and overhauled the analysis summary - report and its representation in the saved XML format. -
- Olivier Parent contributed updated French translations for bug descriptions and - Swing GUI. -
- Chris Nappin contributed the plain.xsl
- stylesheet.
-
- Etienne Giraudy contributed the fancy.xsl and fancy-hist.xsl
- stylesheets, and made improvements to the -xml:withMessages
- option.
-
- Takashi Okamoto fixed bugs in the project preferences dialog - in the Eclipse plugin, and contributed to its internationalization and localization. -
Thomas Einwaller fixed bugs in the project preferences dialog in the Eclipse plugin.
Jeff Knox contributed support for the warningsProperty attribute -in the Ant task.
Peter Hendriks extended the Eclipse plugin preferences, -and fixed a bug related to renaming the Eclipse plugin ID.
Mark McKay contributed an Ant task to launch the findbugs frame.
Dieter von Holten (dvholten) contributed -some German improvements to findbugs_de.properties.
If you have contributed to FindBugs, but aren't mentioned above,
-please send email to <findbugs@cs.umd.edu> (and also accept
-our humble apologies).
FindBugs uses several open-source software packages, without which its -development would have been much more difficult.
FindBugs includes software developed by the Apache Software Foundation -(http://www.apache.org/). -Specifically, it uses the Byte Code -Engineering Library.
FindBugs uses the ASM -bytecode framework, which is distributed under the following license:
-Copyright (c) 2000-2005 INRIA, France Telecom -All rights reserved. -
-Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: -
- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -
- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -
- Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. -
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. -
FindBugs uses DOM4J, which is -distributed under the following license:
-Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. -
-Redistribution and use of this software and associated documentation -("Software"), with or without modification, are permitted provided that -the following conditions are met: -
- Redistributions of source code must retain copyright statements and - notices. Redistributions must also contain a copy of this document. -
- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -
- The name "DOM4J" must not be used to endorse or promote products - derived from this Software without prior written permission - of MetaStuff, Ltd. For written permission, please contact -
<dom4j-info@metastuff.com>. -- Products derived from this Software may not be called "DOM4J" nor may - "DOM4J" appear in their names without prior written permission of - MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. -
- Due credit should be given to the DOM4J Project (http://dom4j.org/). -
-THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' -AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -
-FindBugs allows several aspects of the analyses it performs to be -customized. System properties are used to configure these options. -This chapter describes the configurable analysis options. -
-The analysis options have two main purposes. First, they allow you -to inform FindBugs about the meaning of methods in your application, -so that it can produce more accurate results, or produce fewer -false warnings. Second, they allow you to configure the precision -of the analysis performed. Reducing analysis precision can save -memory and analysis time, at the expense of missing some real bugs, -or producing more false warnings. -
-The analysis options are set using the -property -command line option. For example: -
-$findbugs -textui -property "cfg.noprune=true"myApp.jar-
-
-The list of configurable analysis properties is shown in -Table 9.1, “Configurable Analysis Properties”. -
Table 9.1. Configurable Analysis Properties
| Property Name | Value | Meaning |
|---|---|---|
| findbugs.assertionmethods | Comma-separated list of fully qualified method names: - e.g., "com.foo.MyClass.checkAssertion" | This property specifies the names of methods that are used - to check program assertions. Specifying these methods allows - the null pointer dereference bug detector to avoid reporting - false warnings for values which are checked by assertion - methods. |
| findbugs.de.comment | true or false | If true, the DroppedException detector scans source code - for empty catch blocks for a comment, and if one is found, does - not report a warning. |
| findbugs.maskedfields.locals | true or false | If true, emit low priority warnings for local variables - which obscure fields. Default is false. |
| findbugs.nullderef.assumensp | true or false | not used - (intention: If true, the null dereference detector assumes that any - reference value returned from a method or passed to a method - in a parameter might be null. Default is false. Note that - enabling this property will very likely cause a large number - of false warnings to be produced.) |
| findbugs.refcomp.reportAll | true or false | If true, all suspicious reference comparisons - using the == and != operators are reported. If false, - only one such warning is issued per method. Default - is false. |
| findbugs.sf.comment | true or false | If true, the SwitchFallthrough detector will only report - warnings for cases where the source code does not have a comment - containing the words "fall" or "nobreak". (An accurate source - path must be used for this feature to work correctly.) - This helps find cases where the switch fallthrough is likely - to be unintentional. |
-FindBugs supports several annotations to express the developer's intent -so that FindBugs can issue warnings more appropriately. You need to use -Java 5 to use annotations, and must place the annotations.jar and jsr305.jar -files in the classpath while compiling your program. -
-The annotated element might be null, and uses of the element should check for null. -When this annotation is applied to a method it applies to the method return value. -
- priority:The priority of the warning (HIGH, MEDIUM, LOW, IGNORE). Default value:MEDIUM. -
- explanation:A textual explaination of why the return value should be checked. Default value:"". -
-This annotation is used to denote a method whose return value should always be checked after invoking the method. -
- value:Annotation class objects. More than one class can be specified. -
- priority:Default priority(HIGH, MEDIUM, LOW, IGNORE). Default value:MEDIUM. -
-Indicates that all members of the class or package should be annotated with the default -value of the supplied annotation classes. This would be used for behavior annotations -such as @NonNull, @CheckForNull, or @CheckReturnValue. In particular, you can use -@DefaultAnnotation(NonNull.class) on a class or package, and then use @Nullable only -on those parameters, methods or fields that you want to allow to be null. -
- value:Annotation class objects. More than one class can be specified. -
- priority:Default priority(HIGH, MEDIUM, LOW, IGNORE). Default value:MEDIUM. -
-This is same as the DefaultAnnotation except it only applys to fields. -
- value:Annotation class objects. More than one class can be specified. -
- priority:Default priority(HIGH, MEDIUM, LOW, IGNORE). Default value:MEDIUM. -
-This is same as the DefaultAnnotation except it only applys to methods. -
- value:Annotation class objects. More than one class can be specified. -
- priority:Default priority(HIGH, MEDIUM, LOW, IGNORE). Default value:MEDIUM. -
-This is same as the DefaultAnnotation except it only applys to method parameters. -
-The annotated element must not be null. -Annotated fields must not be null after construction has completed. Annotated methods must have non-null return values. -
-The annotated element could be null under some circumstances. In general, this means -developers will have to read the documentation to determine when a null value is -acceptable and whether it is neccessary to check for a null value. FindBugs will -treat the annotated items as though they had no annotation. -
-In pratice this annotation is useful only for overriding an overarching NonNull -annotation. -
- value:Specify when the super invocation should be - performed (FIRST, ANYTIME, LAST). Default value:ANYTIME. -
-Used to annotate a method that, if overridden, must (or should) be invoke super -in the overriding method. Examples of such methods include finalize() and clone(). -The argument to the method indicates when the super invocation should occur: -at any time, at the beginning of the overriding method, or at the end of the overriding method. -(This anotation is not implmemented in FindBugs as of September 8, 2006). -
-This annotation is deprecated. Use CheckForNull instead. -
- value:The name of the warning. More than one name can be specified. -
- justification:Reason why the warning should be ignored. Default value:"". -
-The set of warnings that are to be suppressed by the compiler in the annotated element. -Duplicate names are permitted. The second and successive occurrences of a name are ignored. -The presence of unrecognized warning names is not an error: Compilers -must ignore any warning names they do not recognize. They are, however, free to emit a -warning if an annotation contains an unrecognized warning name. Compiler vendors should -document the warning names they support in conjunction with this annotation type. They -are encouraged to cooperate to ensure that the same names work across multiple compilers. -
-Used to indicate that the nullness of the target is unknown, or my vary in unknown ways in subclasses. -
-Used to indicate that the nullness of the target is unknown, or my vary in unknown ways in subclasses. -
- FindBugs also supports the following annotations: -
-
-You can refer the JCIP annotation -API documentation at Java Concurrency in Practice. -
-This chapter describes how to integrate FindBugs into a build script -for Ant, which is a popular Java build -and deployment tool. Using the FindBugs Ant task, your build script can -automatically run FindBugs on your Java code. -
-The Ant task was generously contributed by Mike Fagan. -
-To install the Ant task, simply copy
-into the $FINDBUGS_HOME/lib/findbugs-ant.jarlib subdirectory of your Ant installation.
-
-
![]() | Note |
|---|---|
It is strongly recommended that you use the Ant task with the version -of FindBugs it was included with. We do not guarantee that the Ant task Jar file -will work with any version of FindBugs other than the one it was included with. |
-
-To incorporate FindBugs into build.xml (the build script
-for Ant), you first need to add a task definition. This should appear as follows:
-
-
- <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask"/> -
-
-The task definition specifies that when a findbugs element is
-seen in build.xml, it should use the indicated class to execute the task.
-
-After you have added the task definition, you can define a target
-which uses the findbugs task. Here is an example
-which could be added to the build.xml for the
-Apache BCEL library.
-
-
- <property name="findbugs.home" value="/export/home/daveho/work/findbugs" />
-
- <target name="findbugs" depends="jar">
- <findbugs home="${findbugs.home}"
- output="xml"
- outputFile="bcel-fb.xml" >
- <auxClasspath path="${basedir}/lib/Regex.jar" />
- <sourcePath path="${basedir}/src/java" />
- <class location="${basedir}/bin/bcel.jar" />
- </findbugs>
- </target>
-
-
-The findbugs element must have the home
-attribute set to the directory in which FindBugs is installed; in other words,
-$FINDBUGS_HOME. See Chapter 2, Installing FindBugs™.
-
-This target will execute FindBugs on bcel.jar, which is the
-Jar file produced by BCEL's build script. (By making it depend on the "jar"
-target, we ensure that the library is fully compiled before running FindBugs on it.)
-The output of FindBugs will be saved in XML format to a file called
-bcel-fb.xml.
-An auxiliary Jar file, Regex.jar, is added to the aux classpath,
-because it is referenced by the main BCEL library. A source path is specified
-so that the saved bug data will have accurate references to the BCEL source code.
-
-Here is an example of invoking Ant from the command line, using the findbugs
-target defined above.
-
-
- [daveho@noir]$ ant findbugs
- Buildfile: build.xml
-
- init:
-
- compile:
-
- examples:
-
- jar:
-
- findbugs:
- [findbugs] Running FindBugs...
- [findbugs] Bugs were found
- [findbugs] Output saved to bcel-fb.xml
-
- BUILD SUCCESSFUL
- Total time: 35 seconds
-- -In this case, because we saved the bug results in an XML file, we can -use the FindBugs GUI to view the results; see Chapter 4, Running FindBugs™. -
This section describes the parameters that may be specified when -using the FindBugs task. - -
class
- A nested element specifying which classes to analyze. The class
- element must specify a location attribute which names the
- archive file (jar, zip, etc.), directory, or class file to be analyzed. Multiple class
- elements may be specified as children of a single findbugs element.
-
auxClasspath
- An optional nested element which specifies a classpath (Jar files or directories)
- containing classes used by the analyzed library or application, but which
- you don't want to analyze. It is specified the same way as
- Ant's classpath element for the Java task.
-
sourcePath- An optional nested element which specifies a source directory path - containing source files used to compile the Java code being analyzed. - By specifying a source path, any generated XML bug output will have - complete source information, which allows later viewing in the - GUI. -
home- A required attribute. - It must be set to the name of the directory where FindBugs is installed. -
quietErrors- An optional boolean attribute. - If true, reports of serious analysis errors and missing classes will - be suppressed in the FindBugs output. Default is false. -
reportLevel- An optional attribute. It specifies - the priority threshold for reporting bugs. If set to "low", all bugs are reported. - If set to "medium" (the default), medium and high priority bugs are reported. - If set to "high", only high priority bugs are reported. -
output- Optional attribute. - It specifies the output format. If set to "xml" (the default), output - is in XML format. - If set to "xml:withMessages", output is in XML format augmented with - human-readable messages. (You should use this format if you plan - to generate a report using an XSL stylesheet.) - If set to "html", output is in HTML formatted (default stylesheet is default.xsl). - If set to "text", output is in ad-hoc text format. - If set to "emacs", output is in Emacs error message format. - If set to "xdocs", output is xdoc XML for use with Apache Maven. -
stylesheet- Optional attribute. - It specifies the stylesheet to use to generate html output when the output is set to html. - Stylesheets included in the FindBugs distribution include default.xsl, fancy.xsl, fancy-hist.xsl, plain.xsl, and summary.xsl. - The default value, if no stylesheet attribute is provided, is default.xsl. - -
sort
- Optional attribute. If the output attribute
- is set to "text", then the sort attribute specifies
- whether or not reported bugs are sorted by class. Default is true.
-
outputFile- Optional attribute. If specified, names the output file in which the - FindBugs output will be saved. By default, the output is displayed - directly by Ant. -
debug- Optional boolean attribute. If set to true, FindBugs prints diagnostic - information about which classes are being analyzed, and which bug pattern - detectors are being run. Default is false. -
effort
- Set the analysis effort level. The value specified should be
- one of min, default,
- or max. See Section 3, “Command-line Options”
- for more information about setting the analysis level.
-
conserveSpaceSynonym for effort="min".
workHardSynonym for effort="max".
visitors- Optional attribute. It specifies a comma-separated list of bug detectors - which should be run. The bug detectors are specified by their class names, - without any package qualification. By default, all detectors which are - not disabled by default are run. -
omitVisitors
- Optional attribute. It is like the visitors attribute,
- except it specifies detectors which will not be run.
-
excludeFilter- Optional attribute. It specifies the filename of a filter specifying bugs - to exclude from being reported. See Chapter 8, Filter Files. -
includeFilter- Optional attribute. It specifies the filename of a filter specifying - which bugs are reported. See Chapter 8, Filter Files. -
projectFile
- Optional attribute. It specifies the name of a project file.
- Project files are created by the FindBugs GUI, and specify classes,
- aux classpath entries, and source directories. By naming a project,
- you don't need to specify any class elements,
- nor do you need to specify auxClasspath or
- sourcePath attributes.
- See Chapter 4, Running FindBugs™ for how to create a project.
-
jvmargs- Optional attribute. It specifies any arguments that should be passed - to the Java virtual machine used to run FindBugs. You may need to - use this attribute to specify flags to increase the amount of memory - the JVM may use if you are analyzing a very large program. -
systemProperty
- Optional nested element. If specified, defines a system property.
- The name attribute specifies the name of the
- system property, and the value attribute specifies
- the value of the system property.
-
timeout- Optional attribute. It specifies the amount of time, in milliseconds, - that the Java process executing FindBugs may run before it is - assumed to be hung and is terminated. The default is 600,000 - milliseconds, which is ten minutes. Note that for very large - programs, FindBugs may require more than ten minutes to complete its - analysis. -
failOnError- Optional boolean attribute. Whether to abort the build process if there is an - error running FindBugs. Defaults to "false" -
errorProperty- Optional attribute which specifies the name of a property that - will be set to "true" if an error occurs while running FindBugs. -
warningsProperty- Optional attribute which specifies the name of a property - that will be set to "true" if any warnings are reported by - FindBugs on the analyzed program. -
- - -
Table of Contents
-This chapter describes how to build FindBugs from source code. Unless you are -interesting in modifying FindBugs, you will probably want to skip to the -next chapter. -
-To compile FindBugs from source, you will need the following: -
- The FindBugs source distribution -
- Apache Ant, version 1.6.3 or later -
-
![]() | Warning |
|---|---|
- The version of Ant included as |
-If you want to be able to generate formatted versions of the FindBugs documentation, -you will also need the following software: -
- The DocBook XSL Stylesheets. - These are required to convert the FindBugs manual into HTML format. -
- The Saxon XSLT Processor. - (Also required for converting the FindBugs manual to HTML.) -
-
-After you download the source distribution, you'll need to extract it into -a working directory. A typical command to do this is: - -
-$ unzip findbugs-2.0.0-source.zip
-- -
-If you intend to build the FindBugs documentation,
-you will need to modify the local.properties file
-used by the Ant
-build.xml file to build FindBugs.
-If you do not want to build the FindBugs documentation, then you
-can ignore this file.
-
-The local.properties overrides definitions
-in the build.properties file.
-The build.properties file looks something like this:
-
-
-# User Configuration:
-# This section must be modified to reflect your system.
-
-local.software.home =/export/home/daveho/linux
-
-# Set this to the directory containing the DocBook Modular XSL Stylesheets
-# from http://docbook.sourceforge.net/projects/xsl/
-
-xsl.stylesheet.home =${local.software.home}/docbook/docbook-xsl-1.71.1
-
-# Set this to the directory where Saxon (http://saxon.sourceforge.net/)
-# is installed.
-
-saxon.home =${local.software.home}/java/saxon-6.5.5
-
--
-The xsl.stylesheet.home property specifies the full
-path to the directory where you have installed the
-DocBook Modular XSL
-Stylesheets. You only need to specify this property if you will be
-generating the FindBugs documentation.
-
-The saxon.home property is the full path to the
-directory where you installed the Saxon XSLT Processor.
-You only need to specify this property if you will be
-generating the FindBugs documentation.
-
-Once you have extracted the source distribution,
-made sure that Ant is installed,
-modified build.properties (optional),
-and configured the tools (such as Saxon),
-you are ready to build FindBugs. Invoking Ant is a simple matter
-of running the command
-
-$anttarget-
-where target is one of the following:
-
- This target compiles the code for FindBugs. It is the default target. -
- This target formats the documentation. (It also compiles some of - the source code as a side-effect.) -
- This target compiles and runs the internal JUnit tests included - in FindBugs. It will print an error message if any unit - tests fail. -
- Builds a binary distribution of FindBugs.
- The target creates both .zip and
- .tar.gz archives.
-
-
-After running an Ant command, you should see output similar to -the following (after some other messages regarding the tasks that -Ant is running): -
-
-BUILD SUCCESSFUL
-Total time: 17 seconds
-
--
-The Ant build script for FindBugs is written such that after -building the build target, the working directory -is set up just like a binary distribution. So, the information about -running FindBugs in Chapter 4, Running FindBugs™ -applies to source distributions, too. -
Table of Contents
-FindBugs incorporates an ability to perform sophisticated queries on bug -databases and track warnings across multiple versions of code being -studied, allowing you to do things such as seeing when a bug was first introduced, examining -just the warnings that have been introduced since the last release, or graphing the number -of infinite recursive loops in your code over time.
-These techniques all depend upon the XML format used by FindBugs for storing warnings. -These XML files usually contain just the warnings from one particular analysis run, but -they can also store the results from analyzing a sequence of software builds or versions. -
-Any FindBugs XML bug database contains a version name and timestamp. -FindBugs tries to compute a timestamp from the timestamps of the files that -are analyzed (e.g., the timestamp is intended to be the time the class files -were generated, not analyzed). Each bug database also contains a version name. -Both the version name and timestamp can be set manually using the -setBugDatabaseInfo (Section 1.7, “setBugDatabaseInfo”) command. -
A multiversion bug database assigns a sequence number to each version of -the analyzed code. These sequence numbers are simply successive integers, -starting at 0 (e.g., a bug database for 4 versions of the code will contain -versions 0..3). The bug database will also record the name and timestamp for -each version. The filterBugs command allows you to refer -to a version by sequence number, name or timestamp.
-You can take a sequence (or pair) of single version bug databases and create -from them a multiversion bug database, or combine a multiversion bug database -with a sequence of later single-version bug databases.
-Some of these commands can be invoked as ant tasks. See below for specifics
-on how to invoke them and what attributes and arguments they take. All of
-the examples assume that the findbugs.lib
-refid is set correctly. Here is one way to set it:
-
-
- <!-- findbugs task definition -->
- <property name="findbugs.home" value="/your/path/to/findbugs" />
- <path id="findbugs.lib">
- <fileset dir="${findbugs.home}/lib">
- <include name="findbugs-ant.jar"/>
- </fileset>
- </path>
-
--All tools for FindBugs data mining are can be invoked from the command line, -and some of the more useful tools can also be invoked from an -ant build file.
-Briefly, the command-line tools are:
- combine the results from separate analysis of disjoint - classes -
Merge bug warnings from multiple versions of - analyzed code into - a single multiversion bug database. This can either be used - to add more versions to an existing multiversion database, - or to create a multiversion database from a sequence of single version - bug warning databases.
Set information such as the revision name or -timestamp in an XML bug database
List information such as the revision name and -timestamp for a list of XML bug databases
Select a subset of a bug database
Generate a tabular listing of the number of warnings in each - version of a multiversion bug database
List information about defect density - (warnings per 1000 NCSS) - for the entire project and each class and package
Convert bug warnings in XML format to - a textual one-line-per-bug format, or to HTML
- If you have, for example, separately analyzing each jar file used in an application, - you can use this command to combine the separately generated xml bug warning files into - a single file containing all of the warnings.
Do not use this command to combine results from analyzing different versions of the same - file; use computeBugHistory instead.
Specify the xml files on the command line. The result is sent to standard output.
Use this command to generate a bug database containing information from different builds or versions -of software you are analyzing. -History is taken from the first file provided as input; any following -files should be single version bug databases (if they contain history, the history in those -files will be ignored).
By default, output is written to the standard output. -
This functionality may also can be accessed from ant. -First create a taskdef for computeBugHistory in your -build file: -
- -<taskdef name="computeBugHistory" classname="edu.umd.cs.findbugs.anttask.ComputeBugHistoryTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
Attributes for this ant task are listed in the following table.
-To specify input files, nest them inside with a
-<datafile> element. For example:
-
-
-<computeBugHistory home="${findbugs.home}" ...>
- <datafile name="analyze1.xml"/>
- <datafile name="analyze2.xml"/>
-</computeBugHistory>
-
-Table 12.1. Options for computeBugHistory command
| Command-line option | Ant attribute | Meaning |
|---|---|---|
| -output <file> | output="<file>" | save output in the named file (may also be an input file) |
| -overrideRevisionNames[:truth] | overrideRevisionNames="[true|false]" | override revision names for each version with names computed from the filenames |
| -noPackageMoves[:truth] | noPackageMoves="[true|false]" | if a class has moved to another package, treat warnings in that class as seperate |
| -preciseMatch[:truth] | preciseMatch="[true|false]" | require bug patterns to match precisely |
| -precisePriorityMatch[:truth] | precisePriorityMatch="[true|false]" | consider two warnings as the same only if priorities match exactly |
| -quiet[:truth] | quiet="[true|false]" | don't generate any output to standard out unless there is an error |
| -withMessages[:truth] | withMessages="[true|false]" | include human-readable messages describing the warnings in XML output |
This command is used to select a subset of warnings from a FindBugs XML warning file -and write the selected subset to a new FindBugs warning file.
-This command takes a sequence of options, and either zero, one or two -filenames of findbugs xml bug files on the command line.
If no file names are provided, the command reads from standard input -and writes to standard output. If one file name is provided, -it reads from the file and writes to standard output. -If two file names are provided, it reads from the first and writes the output -to the second file name.
This functionality may also can be accessed from ant. -First create a taskdef for filterBugs in your -build file: -
- -<taskdef name="filterBugs" classname="edu.umd.cs.findbugs.anttask.FilterBugsTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
Attributes for this ant task are listed in the following table.
-To specify an input file either use the input attribute or nest it inside
-the ant call with a <datafile> element. For example:
-
-
-<filterBugs home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</filterBugs>
-
-Table 12.2. Options for filterBugs command
| Command-line option | Ant attribute | Meaning |
|---|---|---|
| input="<file>" | use file as input | |
| output="<file>" | output results to file | |
| -not | not="[true|false]" | reverse (all) switches for the filter |
| -withSource[:truth] | withSource="[true|false]" | only warnings for switch source is available |
| -exclude <filter file> | exclude="<filter file>" | exclude bugs matching given filter |
| -include <filter file> | include="<filter file>" | include only bugs matching given filter |
| -annotation <text> | annotation="<text>" | allow only warnings containing this text in a manual annotation |
| -after <when> | after="<when>" | allow only warnings that first occurred after this version |
| -before <when> | before="<when>" | allow only warnings that first occurred before this version |
| -first <when> | first="<when>" | allow only warnings that first occurred in this version |
| -last <when> | last="<when>" | allow only warnings that last occurred in this version |
| -fixed <when> | fixed="<when>" | allow only warnings that last occurred in the previous version (clobbers -last) |
| -present <when> | present="<when>" | allow only warnings present in this version |
| -absent <when> | absent="<when>" | allow only warnings absent in this version |
| -active[:truth] | active="[true|false]" | allow only warnings alive in the last sequence number |
| -introducedByChange[:truth] | introducedByChange="[true|false]" | allow only warnings introduced by a change of an existing class |
| -removedByChange[:truth] | removedByChange="[true|false]" | allow only warnings removed by a change of a persisting class |
| -newCode[:truth] | newCode="[true|false]" | allow only warnings introduced by the addition of a new class |
| -removedCode[:truth] | removedCode="[true|false]" | allow only warnings removed by removal of a class |
| -priority <level> | priority="<level>" | allow only warnings with this priority or higher |
| -class <pattern> | class="<class>" | allow only bugs whose primary class name matches this pattern |
| -bugPattern <pattern> | bugPattern="<pattern>" | allow only bugs whose type matches this pattern |
| -category <category> | category="<category>" | allow only warnings with a category that starts with this string |
| -designation <designation> | designation="<designation>" | allow only warnings with this designation (e.g., -designation SHOULD_FIX) |
| -withMessages[:truth] | withMessages="[true|false]" | the generated XML should contain textual messages |
This command generates a table containing counts of the numbers of warnings -in each version of a multiversion bug database.
This functionality may also can be accessed from ant. -First create a taskdef for mineBugHistory in your -build file: -
- -<taskdef name="mineBugHistory" classname="edu.umd.cs.findbugs.anttask.MineBugHistoryTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
Attributes for this ant task are listed in the following table.
-To specify an input file either use the input
-attribute or nest it inside the ant call with a
-<datafile> element. For example:
-
-
-<mineBugHistory home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</mineBugHistory>
-
-Table 12.3. Options for mineBugHistory command
| Command-line option | Ant attribute | Meaning |
|---|---|---|
| input="<file>" | use file as input | |
| output="<file>" | write output to file | |
| -formatDates | formatDates="[true|false]" | render dates in textual form |
| -noTabs | noTabs="[true|false]" | delimit columns with groups of spaces instead of tabs (see below) |
| -summary | summary="[true|false]" | output terse summary of changes over the last ten entries |
- The -noTabs output can be easier to read from a shell
- with a fixed-width font.
- Because numeric columns are right-justified, spaces may precede the
- first column value. This option also causes -formatDates
- to render dates in terser format without embedded whitespace.
-
The table is a tab-separated (barring -noTabs)
- table with the following columns:
Table 12.4. Columns in mineBugHistory output
| Title | Meaning |
|---|---|
| seq | Sequence number (successive integers, starting at 0) |
| version | Version name |
| time | Release timestamp |
| classes | Number of classes analyzed |
| NCSS | Non Commenting Source Statements |
| added | Count of new warnings for a class that existed in the previous version |
| newCode | Count of new warnings for a class that did not exist in the previous version |
| fixed | Count of warnings removed from a class that remains in the current version |
| removed | Count of warnings in the previous version for a class that is not present in the current version |
| retained | Count of warnings that were in both the previous and current version |
| dead | Warnings that were present in earlier versions but in neither the current version or the immediately preceeding version |
| active | Total warnings present in the current version |
-This command lists information about defect density (warnings per 1000 NCSS) for the entire project and each class and package. -It can either be invoked with no files specified on the command line (in which case it reads from standard input) -or with one file specified on the command line.
It generates a table with the following columns, and with one -row for the entire project, and one row for each package or class that contains at least -4 warnings.
Table 12.5. Columns in defectDensity output
| Title | Meaning |
|---|---|
| kind | project, package or class |
| name | The name of the project, package or class |
| density | Number of warnings generated per 1000 lines of NCSS. |
| bugs | Number of warnings |
| NCSS | Calculated number of NCSS |
- This command converts a warning collection in XML format to a text - format with one line per warning, or to HTML. -
This functionality may also can be accessed from ant. -First create a taskdef for convertXmlToText in your -build file: -
- -<taskdef name="convertXmlToText" classname="edu.umd.cs.findbugs.anttask.ConvertXmlToTextTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
Attributes for this ant task are listed in the following table.
Table 12.6. Options for convertXmlToText command
| Command-line option | Ant attribute | Meaning |
|---|---|---|
| input="<filename>" | use file as input | |
| output="<filename>" | output results to file | |
| -longBugCodes | longBugCodes="[true|false]" | use the full bug pattern code instead of two-letter abbreviation |
| format="text" | generate plain text output with one bug per line (command-line default) | |
| -html[:stylesheet] | format="html:<stylesheet>" | generate output with specified stylesheet (see below), or default.xsl if unspecified |
- You may specify plain.xsl, default.xsl, fancy.xsl, fancy-hist.xsl, - or your own XSL stylesheet for the -html/format option. - Despite the name of this option, you may specify - a stylesheet that emits something other than html. - When applying a stylesheet other than those included - with FindBugs (listed above), the -html/format option should be used - with a path or URL to the stylesheet. -
- This command sets meta-information in a specified warning collection. - It takes the following options: -
This functionality may also can be accessed from ant. -First create a taskdef for setBugDatabaseInfo in your -build file: -
- -<taskdef name="setBugDatabaseInfo" classname="edu.umd.cs.findbugs.anttask.SetBugDatabaseInfoTask"> - <classpath refid="findbugs.lib" /> -</taskdef> - -
Attributes for this ant task are listed in the following table.
-To specify an input file either use the input
-attribute or nest it inside the ant call with a
-<datafile> element. For example:
-
-
-<setBugDatabaseInfo home="${findbugs.home}" ...>
- <datafile name="analyze.xml"/>
-</setBugDatabaseInfo>
-
-Table 12.7. setBugDatabaseInfo Options
| Command-line option | Ant attribute | Meaning |
|---|---|---|
| input="<file>" | use file as input | |
| output="<file>" | write output to file | |
| -name <name> | name="<name>" | set name for (last) revision |
| -timestamp <when> | timestamp="<when>" | set timestamp for (last) revision |
| -source <directory> | source="<directory>" | add specified directory to the source search path |
| -findSource <directory> | findSource="<directory>" | find and add all relevant source directions contained within specified directory |
| -suppress <filter file> | suppress="<filter file>" | suppress warnings matched by this file (replaces previous suppressions) |
| -withMessages | withMessages="[true|false]" | add textual messages to XML |
| -resetSource | resetSource="[true|false]" | remove all source search paths |
This command takes a list of zero or more xml bug database filenames on the command line. -If zero file names are provided, it reads from standard input and does not generate -a table header.
There is only one option: -formatDates renders dates
- in textual form.
-
The output is a table one row per bug database and the following columns:
Table 12.8. listBugDatabaseInfo Columns
| Column | Meaning |
|---|---|
| version | version name |
| time | Release timestamp |
| classes | Number of classes analyzed |
| NCSS | Non Commenting Source Statements analyzed |
| total | Total number of warnings of all kinds |
| high | Total number of high priority warnings of all kinds |
| medium | Total number of medium/normal priority warnings of all kinds |
| low | Total number of low priority warnings of all kinds |
| filename | filename of database |
In all of the following, the commands are given in a directory that contains -directories jdk1.6.0-b12, jdk1.6.0-b13, ..., jdk1.6.0-b60.
You can use the command:
-computeBugHistory jdk1.6.0-b* | filterBugs -bugPattern IL_ | mineBugHistory -formatDates -
to generate the following output:
-seq version time classes NCSS added newCode fixed removed retained dead active -0 jdk1.6.0-b12 "Thu Nov 11 09:07:20 EST 2004" 13128 811569 0 4 0 0 0 0 4 -1 jdk1.6.0-b13 "Thu Nov 18 06:02:06 EST 2004" 13128 811570 0 0 0 0 4 0 4 -2 jdk1.6.0-b14 "Thu Dec 02 06:12:26 EST 2004" 13145 811786 0 0 2 0 2 0 2 -3 jdk1.6.0-b15 "Thu Dec 09 06:07:04 EST 2004" 13174 811693 0 0 1 0 1 2 1 -4 jdk1.6.0-b16 "Thu Dec 16 06:21:28 EST 2004" 13175 811715 0 0 0 0 1 3 1 -5 jdk1.6.0-b17 "Thu Dec 23 06:27:22 EST 2004" 13176 811974 0 0 0 0 1 3 1 -6 jdk1.6.0-b19 "Thu Jan 13 06:41:16 EST 2005" 13176 812011 0 0 0 0 1 3 1 -7 jdk1.6.0-b21 "Thu Jan 27 05:57:52 EST 2005" 13177 812173 0 0 0 0 1 3 1 -8 jdk1.6.0-b23 "Thu Feb 10 05:44:36 EST 2005" 13179 812188 0 0 0 0 1 3 1 -9 jdk1.6.0-b26 "Thu Mar 03 06:04:02 EST 2005" 13199 811770 0 0 0 0 1 3 1 -10 jdk1.6.0-b27 "Thu Mar 10 04:48:38 EST 2005" 13189 812440 0 0 0 0 1 3 1 -11 jdk1.6.0-b28 "Thu Mar 17 02:54:22 EST 2005" 13185 812056 0 0 0 0 1 3 1 -12 jdk1.6.0-b29 "Thu Mar 24 03:09:20 EST 2005" 13117 809468 0 0 0 0 1 3 1 -13 jdk1.6.0-b30 "Thu Mar 31 02:53:32 EST 2005" 13118 809501 0 0 0 0 1 3 1 -14 jdk1.6.0-b31 "Thu Apr 07 03:00:14 EDT 2005" 13117 809572 0 0 0 0 1 3 1 -15 jdk1.6.0-b32 "Thu Apr 14 02:56:56 EDT 2005" 13169 811096 0 0 0 0 1 3 1 -16 jdk1.6.0-b33 "Thu Apr 21 02:46:22 EDT 2005" 13187 811942 0 0 0 0 1 3 1 -17 jdk1.6.0-b34 "Thu Apr 28 02:49:00 EDT 2005" 13195 813488 0 1 0 0 1 3 2 -18 jdk1.6.0-b35 "Thu May 05 02:49:04 EDT 2005" 13457 829837 0 0 0 0 2 3 2 -19 jdk1.6.0-b36 "Thu May 12 02:59:46 EDT 2005" 13462 831278 0 0 0 0 2 3 2 -20 jdk1.6.0-b37 "Thu May 19 02:55:08 EDT 2005" 13464 831971 0 0 0 0 2 3 2 -21 jdk1.6.0-b38 "Thu May 26 03:08:16 EDT 2005" 13564 836565 0 0 0 0 2 3 2 -22 jdk1.6.0-b39 "Fri Jun 03 03:10:48 EDT 2005" 13856 849992 0 1 0 0 2 3 3 -23 jdk1.6.0-b40 "Thu Jun 09 03:30:28 EDT 2005" 15972 959619 0 2 0 0 3 3 5 -24 jdk1.6.0-b41 "Thu Jun 16 03:19:22 EDT 2005" 15972 959619 0 0 0 0 5 3 5 -25 jdk1.6.0-b42 "Fri Jun 24 03:38:54 EDT 2005" 15966 958581 0 0 0 0 5 3 5 -26 jdk1.6.0-b43 "Thu Jul 14 03:09:34 EDT 2005" 16041 960544 0 0 0 0 5 3 5 -27 jdk1.6.0-b44 "Thu Jul 21 03:05:54 EDT 2005" 16041 960547 0 0 0 0 5 3 5 -28 jdk1.6.0-b45 "Thu Jul 28 03:26:10 EDT 2005" 16037 960606 0 0 1 0 4 3 4 -29 jdk1.6.0-b46 "Thu Aug 04 03:02:48 EDT 2005" 15936 951355 0 0 0 0 4 4 4 -30 jdk1.6.0-b47 "Thu Aug 11 03:18:56 EDT 2005" 15964 952387 0 0 1 0 3 4 3 -31 jdk1.6.0-b48 "Thu Aug 18 08:10:40 EDT 2005" 15970 953421 0 0 0 0 3 5 3 -32 jdk1.6.0-b49 "Thu Aug 25 03:24:38 EDT 2005" 16048 958940 0 0 0 0 3 5 3 -33 jdk1.6.0-b50 "Thu Sep 01 01:52:40 EDT 2005" 16287 974937 1 0 0 0 3 5 4 -34 jdk1.6.0-b51 "Thu Sep 08 01:55:36 EDT 2005" 16362 979377 0 0 0 0 4 5 4 -35 jdk1.6.0-b52 "Thu Sep 15 02:04:08 EDT 2005" 16477 979399 0 0 0 0 4 5 4 -36 jdk1.6.0-b53 "Thu Sep 22 02:00:28 EDT 2005" 16019 957900 0 0 1 0 3 5 3 -37 jdk1.6.0-b54 "Thu Sep 29 01:54:34 EDT 2005" 16019 957900 0 0 0 0 3 6 3 -38 jdk1.6.0-b55 "Thu Oct 06 01:54:14 EDT 2005" 16051 959014 0 0 0 0 3 6 3 -39 jdk1.6.0-b56 "Thu Oct 13 01:54:12 EDT 2005" 16211 970835 0 0 0 0 3 6 3 -40 jdk1.6.0-b57 "Thu Oct 20 01:55:26 EDT 2005" 16279 971627 0 0 0 0 3 6 3 -41 jdk1.6.0-b58 "Thu Oct 27 01:56:30 EDT 2005" 16283 971945 0 0 0 0 3 6 3 -42 jdk1.6.0-b59 "Thu Nov 03 01:56:58 EST 2005" 16232 972193 0 0 0 0 3 6 3 -43 jdk1.6.0-b60 "Thu Nov 10 01:54:18 EST 2005" 16235 972346 0 0 0 0 3 6 3 -
-We could also generate that information directly, without creating an intermediate db.xml file, using the command -
-computeBugHistory jdk1.6.0-b*/jre/lib/rt.xml | filterBugs -bugPattern IL_ db.xml | mineBugHistory -formatDates -
We can then use that information to display a graph showing the number of infinite recursive loops -found by FindBugs in each build of Sun's JDK1.6.0. The blue area indicates the number of infinite -recursive loops in that build, the red area above it indicates the number of infinite recursive loops that existed -in some previous version but not in the current version (thus, the combined height of the red and blue areas -is guaranteed to never decrease, and goes up whenever a new infinite recursive loop bug is introduced). The height -of the red area is computed as the sum of the fixed, removed and dead values for each version. -The reductions in builds 13 and 14 came after Sun was notified about the bugs found by FindBugs in the JDK. -

-Given the db.xml file that contains the results for all the jdk1.6.0 builds, the following command will show the history of high and medium priority correctness warnings: -
-filterBugs -priority M -category C db.xml | mineBugHistory -formatDates -
-generating the table: -
-seq version time classes NCSS added newCode fixed removed retained dead active -0 jdk1.6.0-b12 "Thu Nov 11 09:07:20 EST 2004" 13128 811569 0 1075 0 0 0 0 1075 -1 jdk1.6.0-b13 "Thu Nov 18 06:02:06 EST 2004" 13128 811570 0 0 0 0 1075 0 1075 -2 jdk1.6.0-b14 "Thu Dec 02 06:12:26 EST 2004" 13145 811786 3 0 6 0 1069 0 1072 -3 jdk1.6.0-b15 "Thu Dec 09 06:07:04 EST 2004" 13174 811693 2 1 3 0 1069 6 1072 -4 jdk1.6.0-b16 "Thu Dec 16 06:21:28 EST 2004" 13175 811715 0 0 1 0 1071 9 1071 -5 jdk1.6.0-b17 "Thu Dec 23 06:27:22 EST 2004" 13176 811974 0 0 1 0 1070 10 1070 -6 jdk1.6.0-b19 "Thu Jan 13 06:41:16 EST 2005" 13176 812011 0 0 0 0 1070 11 1070 -7 jdk1.6.0-b21 "Thu Jan 27 05:57:52 EST 2005" 13177 812173 0 0 1 0 1069 11 1069 -8 jdk1.6.0-b23 "Thu Feb 10 05:44:36 EST 2005" 13179 812188 0 0 0 0 1069 12 1069 -9 jdk1.6.0-b26 "Thu Mar 03 06:04:02 EST 2005" 13199 811770 0 0 2 1 1066 12 1066 -10 jdk1.6.0-b27 "Thu Mar 10 04:48:38 EST 2005" 13189 812440 1 0 1 1 1064 15 1065 -11 jdk1.6.0-b28 "Thu Mar 17 02:54:22 EST 2005" 13185 812056 0 0 0 0 1065 17 1065 -12 jdk1.6.0-b29 "Thu Mar 24 03:09:20 EST 2005" 13117 809468 3 0 8 26 1031 17 1034 -13 jdk1.6.0-b30 "Thu Mar 31 02:53:32 EST 2005" 13118 809501 0 0 0 0 1034 51 1034 -14 jdk1.6.0-b31 "Thu Apr 07 03:00:14 EDT 2005" 13117 809572 0 0 0 0 1034 51 1034 -15 jdk1.6.0-b32 "Thu Apr 14 02:56:56 EDT 2005" 13169 811096 1 1 0 1 1033 51 1035 -16 jdk1.6.0-b33 "Thu Apr 21 02:46:22 EDT 2005" 13187 811942 3 0 2 1 1032 52 1035 -17 jdk1.6.0-b34 "Thu Apr 28 02:49:00 EDT 2005" 13195 813488 0 1 0 0 1035 55 1036 -18 jdk1.6.0-b35 "Thu May 05 02:49:04 EDT 2005" 13457 829837 0 36 2 0 1034 55 1070 -19 jdk1.6.0-b36 "Thu May 12 02:59:46 EDT 2005" 13462 831278 0 0 0 0 1070 57 1070 -20 jdk1.6.0-b37 "Thu May 19 02:55:08 EDT 2005" 13464 831971 0 1 1 0 1069 57 1070 -21 jdk1.6.0-b38 "Thu May 26 03:08:16 EDT 2005" 13564 836565 1 7 2 6 1062 58 1070 -22 jdk1.6.0-b39 "Fri Jun 03 03:10:48 EDT 2005" 13856 849992 6 39 5 0 1065 66 1110 -23 jdk1.6.0-b40 "Thu Jun 09 03:30:28 EDT 2005" 15972 959619 7 147 11 0 1099 71 1253 -24 jdk1.6.0-b41 "Thu Jun 16 03:19:22 EDT 2005" 15972 959619 0 0 0 0 1253 82 1253 -25 jdk1.6.0-b42 "Fri Jun 24 03:38:54 EDT 2005" 15966 958581 3 0 1 2 1250 82 1253 -26 jdk1.6.0-b43 "Thu Jul 14 03:09:34 EDT 2005" 16041 960544 5 11 15 8 1230 85 1246 -27 jdk1.6.0-b44 "Thu Jul 21 03:05:54 EDT 2005" 16041 960547 0 0 0 0 1246 108 1246 -28 jdk1.6.0-b45 "Thu Jul 28 03:26:10 EDT 2005" 16037 960606 19 0 2 0 1244 108 1263 -29 jdk1.6.0-b46 "Thu Aug 04 03:02:48 EDT 2005" 15936 951355 13 1 1 32 1230 110 1244 -30 jdk1.6.0-b47 "Thu Aug 11 03:18:56 EDT 2005" 15964 952387 163 8 7 20 1217 143 1388 -31 jdk1.6.0-b48 "Thu Aug 18 08:10:40 EDT 2005" 15970 953421 0 0 0 0 1388 170 1388 -32 jdk1.6.0-b49 "Thu Aug 25 03:24:38 EDT 2005" 16048 958940 1 11 1 0 1387 170 1399 -33 jdk1.6.0-b50 "Thu Sep 01 01:52:40 EDT 2005" 16287 974937 19 27 16 7 1376 171 1422 -34 jdk1.6.0-b51 "Thu Sep 08 01:55:36 EDT 2005" 16362 979377 1 15 3 0 1419 194 1435 -35 jdk1.6.0-b52 "Thu Sep 15 02:04:08 EDT 2005" 16477 979399 0 0 1 1 1433 197 1433 -36 jdk1.6.0-b53 "Thu Sep 22 02:00:28 EDT 2005" 16019 957900 13 12 16 20 1397 199 1422 -37 jdk1.6.0-b54 "Thu Sep 29 01:54:34 EDT 2005" 16019 957900 0 0 0 0 1422 235 1422 -38 jdk1.6.0-b55 "Thu Oct 06 01:54:14 EDT 2005" 16051 959014 1 4 7 0 1415 235 1420 -39 jdk1.6.0-b56 "Thu Oct 13 01:54:12 EDT 2005" 16211 970835 6 8 37 0 1383 242 1397 -40 jdk1.6.0-b57 "Thu Oct 20 01:55:26 EDT 2005" 16279 971627 0 0 0 0 1397 279 1397 -41 jdk1.6.0-b58 "Thu Oct 27 01:56:30 EDT 2005" 16283 971945 0 1 1 0 1396 279 1397 -42 jdk1.6.0-b59 "Thu Nov 03 01:56:58 EST 2005" 16232 972193 6 0 5 0 1392 280 1398 -43 jdk1.6.0-b60 "Thu Nov 10 01:54:18 EST 2005" 16235 972346 0 0 0 0 1398 285 1398 -44 jdk1.6.0-b61 "Thu Nov 17 01:58:42 EST 2005" 16202 971134 2 0 4 0 1394 285 1396 -
-Here is a complete ant script example for both running findbugs and running a chain of data-mining tools afterward: -
-
-<project name="analyze_asm_util" default="findbugs">
- <!-- findbugs task definition -->
- <property name="findbugs.home" value="/Users/ben/Documents/workspace/findbugs/findbugs" />
- <property name="jvmargs" value="-server -Xss1m -Xmx800m -Duser.language=en -Duser.region=EN -Dfindbugs.home=${findbugs.home}" />
-
- <path id="findbugs.lib">
- <fileset dir="${findbugs.home}/lib">
- <include name="findbugs-ant.jar"/>
- </fileset>
- </path>
-
- <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="computeBugHistory" classname="edu.umd.cs.findbugs.anttask.ComputeBugHistoryTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="setBugDatabaseInfo" classname="edu.umd.cs.findbugs.anttask.SetBugDatabaseInfoTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <taskdef name="mineBugHistory" classname="edu.umd.cs.findbugs.anttask.MineBugHistoryTask">
- <classpath refid="findbugs.lib" />
- </taskdef>
-
- <!-- findbugs task definition -->
- <target name="findbugs">
- <antcall target="analyze" />
- <antcall target="mine" />
- </target>
-
- <!-- analyze task -->
- <target name="analyze">
- <!-- run findbugs against asm-util -->
- <findbugs home="${findbugs.home}"
- output="xml:withMessages"
- timeout="90000000"
- reportLevel="experimental"
- workHard="true"
- effort="max"
- adjustExperimental="true"
- jvmargs="${jvmargs}"
- failOnError="true"
- outputFile="out.xml"
- projectName="Findbugs"
- debug="false">
- <class location="asm-util-3.0.jar" />
- </findbugs>
- </target>
-
- <target name="mine">
-
- <!-- Set info to the latest analysis -->
- <setBugDatabaseInfo home="${findbugs.home}"
- withMessages="true"
- name="asm-util-3.0.jar"
- input="out.xml"
- output="out-rel.xml"/>
-
- <!-- Checking if history file already exists (out-hist.xml) -->
- <condition property="mining.historyfile.available">
- <available file="out-hist.xml"/>
- </condition>
- <condition property="mining.historyfile.notavailable">
- <not>
- <available file="out-hist.xml"/>
- </not>
- </condition>
-
- <!-- this target is executed if the history file do not exist (first run) -->
- <antcall target="history-init">
- <param name="data.file" value="out-rel.xml" />
- <param name="hist.file" value="out-hist.xml" />
- </antcall>
- <!-- else this one is executed -->
- <antcall target="history">
- <param name="data.file" value="out-rel.xml" />
- <param name="hist.file" value="out-hist.xml" />
- <param name="hist.summary.file" value="out-hist.txt" />
- </antcall>
- </target>
-
- <!-- Initializing history file -->
- <target name="history-init" if="mining.historyfile.notavailable">
- <copy file="${data.file}" tofile="${hist.file}" />
- </target>
-
- <!-- Computing bug history -->
- <target name="history" if="mining.historyfile.available">
- <!-- Merging ${data.file} into ${hist.file} -->
- <computeBugHistory home="${findbugs.home}"
- withMessages="true"
- output="${hist.file}">
- <dataFile name="${hist.file}"/>
- <dataFile name="${data.file}"/>
- </computeBugHistory>
-
- <!-- Compute history into ${hist.summary.file} -->
- <mineBugHistory home="${findbugs.home}"
- formatDates="true"
- noTabs="true"
- input="${hist.file}"
- output="${hist.summary.file}"/>
- </target>
-
-</project>
-
-Table of Contents
-The FindBugs Eclipse plugin allows FindBugs to be used within -the Eclipse IDE. -The FindBugs Eclipse plugin was generously contributed by Peter Friese. -Phil Crosby and Andrei Loskutov contributed major improvements -to the plugin. -
-To use the FindBugs Plugin for Eclipse, you need Eclipse 3.3 or later, -and JRE/JDK 1.5 or later. -
- We provide update sites that allow you to automatically install FindBugs into Eclipse and also query and install updates. - There are three different update sites
FindBugs Eclipse update sites
- Only provides official releases of FindBugs. -
- Provides official releases and release candidates of FindBugs. -
- Provides the daily build of FindBugs. No testing other than that it compiles. -
You can also manually -download the plugin from the following link: -http://prdownloads.sourceforge.net/findbugs/edu.umd.cs.findbugs.plugin.eclipse_2.0.0.20111220.zip?download. -Extract it in Eclipse's "plugins" subdirectory. -(So <eclipse_install_dir>/plugins/edu.umd.cs.findbugs.plugin.eclipse_2.0.0.20111220/findbugs.png -should be the path to the FindBugs logo.) - -
-Once the plugin is extracted, start Eclipse and choose - → → . -You should find a plugin called "FindBugs Plug-in" provided by "FindBugs Project". -
-To get started, right click on a Java project in Package Explorer, -and select the option labeled "Find Bugs". -FindBugs will run, and problem markers (displayed in source -windows, and also in the Eclipse Problems view) will point to -locations in your code which have been identified as potential instances -of bug patterns. -
-You can also run FindBugs on existing java archives (jar, ear, zip, war etc). Simply -create an empty Java project and attach archives to the project classpath. Having that, you -can now right click the archive node in Package Explorer and select the option labeled -"Find Bugs". If you additionally configure the source code locations for the binaries, -FindBugs will also link the generated warnings to the right source files. -
-You may customize how FindBugs runs by opening the Properties -dialog for a Java project, and choosing the "Findbugs" property page. -Options you may choose include: -
- Enable or disable the "Run FindBugs Automatically" checkbox. - When enabled, FindBugs will run every time you modify a Java class - within the project. -
- Choose minimum warning priority and enabled bug categories. - These options will choose which warnings are shown. - For example, if you select the "Medium" warning priority, - only Medium and High priority warnings will be shown. - Similarly, if you uncheck the "Style" checkbox, no warnings - in the Style category will be displayed. -
- Select detectors. The table allows you to select which detectors - you want to enable for your project. -
-Eclipse plugin supports contribution of custom FindBugs detectors (see also -AddingDetectors.txt -for more information). There are two ways to contribute custom plugins to the Eclipse: -
- Existing standard FindBugs detector packages can be configured via - → → → → → . - Simply specify there locations of any additional plugin libraries. -
- The benefit of this solution is that already existing detector packages can be - used "as is", and that you can quickly verify the quality of third party detectors. - The drawback is that you have to apply this settings in each - new Eclipse workspace, and this settings can't be shared between team members. -
- It is possible to contribute custom detectors via standard Eclipse extensions mechanism. -
- Please check the documentation of the - - findBugsEclipsePlugin/schema/detectorPlugins.exsd - extension point how to update the plugin.xml. Existing FindBugs detector plugins can - be easily "extended" to be full featured FindBugs AND Eclipse detector plugins. - Usually you only need to add META-INF/MANIFEST.MF and plugin.xml to the jar and - update your build scripts to not to override the MANIFEST.MF during the build. -
- The benefit of this solution is that for given (shared) Eclipse installation - each team member has exactly same detectors set, and there is no need to configure - anything anymore. The (really small) precondition - is that you have to convert your existing detectors package to the valid - Eclipse plugin. You can do this even for third-party detector packages. - Another major differentiator is the ability to extend the default FindBugs - classpath at runtime with required third party libraries (see - AddingDetectors.txt - for more information). -
-This section lists common problems with the plugin and (if known) how to resolve them. -
- If you see OutOfMemory error dialogs after starting FindBugs analysis in Eclipse, - please increase JVM available memory: change eclipse.ini and add the lines below - to the end of the file: -
- -vmargs - -Xmx1000m -
- Important: the configuration arguments starting with the line "-vmargs" must - be last lines in the eclipse.ini file, and only one argument per line is allowed! -
- If you do not see any FindBugs problem markers (in your source - windows or in the Problems View), you may need to change your - Problems View filter settings. See - http://findbugs.sourceforge.net/FAQ.html#q7 for more information. -
Table of Contents
-Filter files may be used to include or exclude bug reports for particular classes -and methods. This chapter explains how to use filter files. - -
![]() | Planned Features |
|---|---|
- Filters are currently only supported by the Command Line interface. - Eventually, filter support will be added to the GUI. - |
-
-Conceptually, a filter matches bug instances against a set of criteria. -By defining a filter, you can select bug instances for special treatment; -for example, to exclude or include them in a report. -
-A filter file is an XML document with a top-level FindBugsFilter element
-which has some number of Match elements as children. Each Match
-element represents a predicate which is applied to generated bug instances.
-Usually, a filter will be used to exclude bug instances. For example:
-
-
-$findbugs -textui -excludemyExcludeFilter.xmlmyApp.jar-
- -However, a filter could also be used to select bug instances to specifically -report: - -
-$findbugs -textui -includemyIncludeFilter.xmlmyApp.jar-
-
-Match elements contain children, which are conjuncts of the predicate.
-In other words, each of the children must be true for the predicate to be true.
-
<Bug>
- This element specifies a particular bug pattern or patterns to match.
- The pattern attribute is a comma-separated list of
- bug pattern types. You can find the bug pattern types for particular
- warnings by looking at the output produced by the -xml
- output option (the type attribute of BugInstance
- elements), or from the bug
- descriptions document.
-
- For more coarse-grained matching, use code attribute. It takes
- a comma-separated list of bug abbreviations. For most-coarse grained matching use
- category attriute, that takes a comma separated list of bug category names:
- CORRECTNESS, MT_CORRECTNESS,
- BAD_PRACTICICE, PERFORMANCE, STYLE.
-
- If more than one of the attributes mentioned above are specified on the same
- <Bug> element, all bug patterns that match either one of specified
- pattern names, or abreviations, or categories will be matched.
-
- As a backwards compatibility measure, <BugPattern> and
- <BugCode> elements may be used instead of
- <Bug> element. Each of these uses a
- name attribute for specifying accepted values list. Support for these
- elements may be removed in a future release.
-
<Priority>
- This element matches warnings with a particular priority.
- The value attribute should be an integer value:
- 1 to match high-priority warnings, 2 to match medium-priority warnings,
- or 3 to match low-priority warnings.
-
<Package>
- This element matches warnings associated with classes within the package specified
- using name attribute. Nested packages are not included (along the
- lines of Java import statement). However matching multiple packages can be achieved
- easily using regex name match.
-
<Class>
- This element matches warnings associated with a particular class. The
- name attribute is used to specify the exact or regex match pattern
- for the class name.
-
- As a backward compatibility measure, instead of element of this type, you can use
- class attribute on a Match element to specify
- exact an class name or classregex attribute to specify a regular
- expression to match the class name against.
-
- If the Match element contains neither a Class element,
- nor a class / classregex attribute, the predicate will apply
- to all classes. Such predicate is likely to match more bug instances than you want, unless it is
- refined further down with apropriate method or field predicates.
-
<Method>This element specifies a method. The name is used to specify
- the exact or regex match pattern for the method name.
- The params attribute is a comma-separated list
- of the types of the method's parameters. The returns attribute is
- the method's return type. In params and returns, class names
- must be fully qualified. (E.g., "java.lang.String" instead of just
- "String".) If one of the latter attributes is specified the other is required for creating a method signature.
- Note that you can provide either name attribute or params
- and returns attributes or all three of them. This way you can provide various kinds of
- name and signature based matches.
-
<Field>This element specifies a field. The name attribute is is used to specify
- the exact or regex match pattern for the field name. You can also filter fields according to their signature -
- use type attribute to specify fully qualified type of the field. You can specify eiter or both
- of these attributes in order to perform name / signature based matches.
-
<Local>This element specifies a local variable. The name attribute is is used to specify
- the exact or regex match pattern for the local variable name. Local variables are variables defined within a method.
-
<Or>
- This element combines Match clauses as disjuncts. I.e., you can put two
- Method elements in an Or clause in order to match either method.
-
<And>
- This element combines Match clauses which both must evaluate to true. I.e., you can put
- Bug and Priority elements in an And clause in order
- to match specific bugs with given priority only.
-
<Not>
- This element inverts the included child Match. I.e., you can put a
- Bug element in a Not clause in order to match any bug
- excluding the given one.
-
-If the name attribute of Class, Method or
-Field starts with the ~ character the rest of attribute content is interpreted as
-a Java regular expression that is matched against the names of the Java element in question.
-
-Note that the pattern is matched against whole element name and therefore .* clauses need to be used -at pattern beginning and/or end to perform substring matching. -
-See java.util.regex.Pattern
-documentation for pattern syntax.
-
-Match clauses can only match information that is actually contained in the
-bug instances. Every bug instance has a class, so in general, excluding
-bugs by class will work.
-
-Some bug instances have two (or more) classes. For example, the DE (dropped exception)
-bugs report both the class containing the method where the dropped exception
-happens, and the class which represents the type of the dropped exception.
-Only the first (primary) class is matched against Match clauses.
-So, for example, if you want to suppress IC (initialization circularity)
-reports for classes "com.foobar.A" and "com.foobar.B", you would use
-two Match clauses:
-
-
- <Match> - <Class name="com.foobar.A" /> - <Bug code="IC" /> - </Match> - - <Match> - <Class name="com.foobar.B" /> - <Bug code="IC" /> - </Match> -
- -By explicitly matching both classes, you ensure that the IC bug instance will be -matched regardless of which class involved in the circularity happens to be -listed first in the bug instance. (Of course, this approach might accidentally -supress circularities involving "com.foobar.A" or "com.foobar.B" and a third -class.) -
-Many kinds of bugs report what method they occur in. For those bug instances,
-you can put Method clauses in the Match element and they should work
-as expected.
-
- 1. Match all bug reports for a class. - -
- - <Match> - <Class name="com.foobar.MyClass" /> - </Match> - -
- -
- 2. Match certain tests from a class by specifying their abbreviations. -
- - <Match> - <Class name="com.foobar.MyClass"/ > - <Bug code="DE,UrF,SIC" /> - </Match> - -
-
- 3. Match certain tests from all classes by specifying their abbreviations. - -
- - <Match> - <Bug code="DE,UrF,SIC" /> - </Match> - -
-
- 4. Match certain tests from all classes by specifying their category. - -
- - <Match> - <Bug category="PERFORMANCE" /> - </Match> - -
-
- 5. Match bug types from specified methods of a class by their abbreviations. - -
- - <Match> - <Class name="com.foobar.MyClass" /> - <Or> - <Method name="frob" params="int,java.lang.String" returns="void" /> - <Method name="blat" params="" returns="boolean" /> - </Or> - <Bug code="DC" /> - </Match> - -
-
- 6. Match a particular bug pattern in a particular method. - -
- - <!-- A method with an open stream false positive. --> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="writeDataToFile" /> - <Bug pattern="OS_OPEN_STREAM" /> - </Match> - -
-
- 7. Match a particular bug pattern with a given priority in a particular method. - -
- - <!-- A method with a dead local store false positive (medium priority). --> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="someMethod" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Priority value="2" /> - </Match> - -
-
- 8. Match minor bugs introduced by AspectJ compiler (you are probably not interested in these unless - you are an AspectJ developer). - -
- - <Match> - <Class name="~.*\$AjcClosure\d+" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Method name="run" /> - </Match> - <Match> - <Bug pattern="UUF_UNUSED_FIELD" /> - <Field name="~ajc\$.*" /> - </Match> - -
-
- 9. Match bugs in specific parts of the code base - -
- - <!-- match unused fields warnings in Messages classes in all packages --> - <Match> - <Class name="~.*\.Messages" /> - <Bug code="UUF" /> - </Match> - <!-- match mutable statics warnings in all internal packages --> - <Match> - <Package name="~.*\.internal" /> - <Bug code="MS" /> - </Match> - <!-- match anonymoous inner classes warnings in ui package hierarchy --> - <Match> - <Package name="~com\.foobar\.fooproject\.ui.*" /> - <Bug pattern="SIC_INNER_SHOULD_BE_STATIC_ANON" /> - </Match> - -
-
- 10. Match bugs on fields or methods with specific signatures -
- - <!-- match System.exit(...) usage warnings in void main(String[]) methods in all classes --> - <Match> - <Method returns="void" name="main" params="java.lang.String[]" /> - <Method pattern="DM_EXIT" /> - </Match> - <!-- match UuF warnings on fields of type com.foobar.DebugInfo on all classes --> - <Match> - <Field type="com.foobar.DebugInfo" /> - <Bug code="UuF" /> - </Match> - -
-
- 11. Match bugs using the Not filter operator -
- -<!-- ignore all bugs in test classes, except for those bugs specifically relating to JUnit tests --> -<!-- i.e. filter bug if ( classIsJUnitTest && ! bugIsRelatedToJUnit ) --> -<Match> - <!-- the Match filter is equivalent to a logical 'And' --> - - <Class name="~.*\.*Test" /> - <!-- test classes are suffixed by 'Test' --> - - <Not> - <Bug code="IJU" /> <!-- 'IJU' is the code for bugs related to JUnit test code --> - </Not> -</Match> - -
-
- -<FindBugsFilter> - <Match> - <Class name="com.foobar.ClassNotToBeAnalyzed" /> - </Match> - - <Match> - <Class name="com.foobar.ClassWithSomeBugsMatched" /> - <Bug code="DE,UrF,SIC" /> - </Match> - - <!-- Match all XYZ violations. --> - <Match> - <Bug code="XYZ" /> - </Match> - - <!-- Match all doublecheck violations in these methods of "AnotherClass". --> - <Match> - <Class name="com.foobar.AnotherClass" /> - <Or> - <Method name="nonOverloadedMethod" /> - <Method name="frob" params="int,java.lang.String" returns="void" /> - <Method name="blat" params="" returns="boolean" /> - </Or> - <Bug code="DC" /> - </Match> - - <!-- A method with a dead local store false positive (medium priority). --> - <Match> - <Class name="com.foobar.MyClass" /> - <Method name="someMethod" /> - <Bug pattern="DLS_DEAD_LOCAL_STORE" /> - <Priority value="2" /> - </Match> - - <!-- All bugs in test classes, except for JUnit-specific bugs --> - <Match> - <Class name="~.*\.*Test" /> - <Not> - <Bug code="IJU" /> - </Not> - </Match> - -</FindBugsFilter> - -
Table of Contents
- This chapter describes how to use the FindBugs graphical user interface (GUI). -
-After you have started FindBugs using the findbugs command, -choose the → -menu item. You will see a dialog which looks like this: -

-
-Use the "Add" button next to "Classpath to analyze" to select a Java archive -file (zip, jar, ear, or war file) or directory containing java classes to analyze for bugs. You may add multiple -archives/directories. -
-You can also add the source directories which contain
-the source code for the Java archives you are analyzing. This will enable
-FindBugs to highlight the source code which contains a possible error.
-The source directories you add should be the roots of the Java
-package hierarchy. For example, if your application is contained in the
-org.foobar.myapp package, you should add the
-parent directory of the org directory
-to the source directory list for the project.
-
-Another optional step is to add additional Jar files or directories as -"Auxiliary classpath locations" entries. You should do this if the archives and directories you are analyzing -have references to other classes which are not included in the analyzed -archives/directories and are not in the standard runtime classpath. Some of the bug -pattern detectors in FindBugs make use of class hierarchy information, -so you will get more accurate results if the entire class hierarchy is -available which FindBugs performs its analysis. -
-Once you have added all of the archives, directories, and source directories, -click the "Analyze" button to analyze the classes contained in the -Jar files. Note that for a very large program on an older computer, -this may take quite a while (tens of minutes). A recent computer with -ample memory will typically be able to analyze a large program in only a -few minutes. -
-When the analysis completes, you will see a screen like the following: -

-
-The upper left-hand pane of the window shows the bug tree; this is a hierarchical -representation of all of the potential bugs detected in the analyzed -Jar files. -
-When you select a particular bug instance in the top pane, you will -see a description of the bug in the "Details" tab of the bottom pane. -In addition, the source code pane on the upper-right will show the -program source code where the potential bug occurs, if source is available. -In the above example, the bug is a stream object that is not closed. The -source code window highlights the line where the stream object is created. -
-You may add a textual annotations to bug instances. To do so, type them -into the text box just below the hierarchical view. You can type any -information which you would like to record. When you load and save bug -results files, the annotations are preserved. -
-You may use the → -menu option to save your work. To save your work, including the jar -file lists you specified and all bug results, choose -"FindBugs analysis results (.xml)" from the drop-down list in the -"Save as..." dialog. There are also options for saving just the jar -file lists ("FindBugs project file (.fbp)") or just the results -("FindBugs analysis file (.fba)"). -A saved file may be loaded with the - → -menu option. -
Copyright © 2003, 2004, 2005, 2006, 2008 University of Maryland
-This manual is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License. -To view a copy of this license, visit -http://creativecommons.org/licenses/by-nc-sa/1.0/ -or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. -
-The name FindBugs and the FindBugs logo are trademarked by the University of Maryland. -
21:17:55 EST, 20 December, 2011
Table of Contents
List of Tables
Table of Contents
-This chapter explains how to install FindBugs. -
-The easiest way to install FindBugs is to download a binary distribution. -Binary distributions are available in -gzipped tar format and -zip format. -Once you have downloaded a binary distribution, extract it into a directory of your choice. -
-Extracting a gzipped tar format distribution: -
-$ gunzip -c findbugs-2.0.0.tar.gz | tar xvf -
--
-Extracting a zip format distribution: -
-C:\Software>unzip findbugs-2.0.0.zip
--
-Usually, extracting a binary distribution will create a directory ending in
-findbugs-2.0.0. For example, if you extracted
-the binary distribution from the C:\Software
-directory, then the FindBugs software will be extracted into the directory
-C:\Software\findbugs-2.0.0.
-This directory is the FindBugs home directory. We'll refer to it as
-$FINDBUGS_HOME (or %FINDBUGS_HOME% for Windows) throughout this manual.
-
Table of Contents
FindBugs™ is a program to find bugs in Java programs. It looks for instances -of "bug patterns" --- code instances that are likely to be errors.
This document describes version 2.0.0 of FindBugs.We -are very interested in getting your feedback on FindBugs. Please visit -the FindBugs web page for -the latest information on FindBugs, contact information, and support resources such -as information about the FindBugs mailing lists.
To use FindBugs, you need a runtime environment compatible with -Java 2 Standard Edition, version 1.5 or later. -FindBugs is platform independent, and is known to run on GNU/Linux, Windows, and -MacOS X platforms.
You should have at least 512 MB of memory to use FindBugs. -To analyze very large projects, more memory may be needed.
-The name FindBugs and the FindBugs logo is trademarked by the University
-of Maryland.
-FindBugs is free software distributed under the terms of the
-Lesser GNU Public License.
-You should have received a copy of the license in the file LICENSE.txt
-in the FindBugs distribution.
-
-You can find the latest version of FindBugs, along with its source code, from the -FindBugs web page. -
-If your project consists of many jarfiles or the jarfiles are scattered -over many directories, you may wish to use the rejarForAnalysis - script to make -FindBugs invocation easier. The script collects many jarfiles and combines them -into a single, large jarfile that can then be easily passed to FindBugs for -analysis. This can be particularly useful in combination with the 'find' command -on unix systems; e.g. find . -name '*.jar' | xargs rejarForAnalysis -. -
-The rejarForAnalysis script -can also be used to split a very large project up into a set of jarfiles with -the project classfiles evenly divided between them. This is useful when running -FindBugs on the entire project is not practical due to time or memory consumption. -Instead of running FindBugs on the entire project, you may use -rejarForAnalysis build one large, all-inclusive jarfile -containing all classes, invoke rejarForAnalysis -again to split the project into multiple jarfiles, then run FindBugs -on each divided jarfiles in turn, specifying the the all-inclusive jarfile in -the -auxclasspath. -
-These are the options accepted by the rejarForAnalysis script: -
days- Maximum age in days (ignore jar files older than this). -
filename- Text file containing names of jar files. -
num- Maximum number of classes per analysis*.jar file. -
class name prefix- Prefix of class names that should be analyzed (e.g., edu.umd.cs.). -
Table of Contents
-FindBugs has two user interfaces: a graphical user interface (GUI) and a -command line user interface. This chapter describes -how to run each of these user interfaces. -
![]() | Warning |
|---|---|
- This chapter is in the process of being re-written. - The rewrite is not complete yet. - |
- If you are running FindBugs on a Windows system,
- double-click on the file to start the FindBugs GUI.
- %FINDBUGS_HOME%\lib\findbugs.jar
- On a Unix, Linux, or Mac OS X system, run the
- script, or run the command $FINDBUGS_HOME/bin/findbugs
-java -jar $FINDBUGS_HOME/lib/findbugs.jar- to run the FindBugs GUI. -
- Refer to Chapter 5, Using the FindBugs GUI for information on how to use the GUI. -
- This section describes how to invoke the FindBugs program. - There are two ways to invoke FindBugs: directly, or using a - wrapper script. -
- The preferred method of running FindBugs is to directly execute
- using the -jar
- command line switch of the JVM (java) executable.
- (Versions of FindBugs prior to 1.3.5 required a wrapper script
- to invoke FindBugs.)
- $FINDBUGS_HOME/lib/findbugs.jar
- The general syntax of invoking FindBugs directly is the following: -
- java [JVM arguments] -jar $FINDBUGS_HOME/lib/findbugs.jar options...
--
- The first command line option chooses the FindBugs user interface to execute. - Possible values are: -
- -gui: runs the graphical user interface (GUI) -
- -textui: runs the command line user interface -
- -version: displays the FindBugs version number -
- -help: displays help information for the - FindBugs command line user interface -
- -gui1: executes the original (obsolete) - FindBugs graphical user interface -
- Several Java Virtual Machine arguments are useful when invoking - FindBugs. -
NNm
- Set the maximum Java heap size to NN
- megabytes. FindBugs generally requires a large amount of
- memory. For a very large project, using 1500 megabytes
- is not unusual.
-
name=value- Set a Java system property. For example, you might use the - argument -Duser.language=ja to display - GUI messages in Japanese. -
- Another way to run FindBugs is to use a wrapper script. -
-On Unix-like systems, use the following command to invoke the wrapper script: -
-$$FINDBUGS_HOME/bin/findbugsoptions...-
-
-On Windows systems, the command to invoke the wrapper script is -
-C:\My Directory>%FINDBUGS_HOME%\bin\findbugs.batoptions...-
-
-On both Unix-like and Windows systems, you can simply add the
-directory to your $FINDBUGS_HOME/binPATH environment variable and then invoke
-FindBugs using the findbugs command.
-
The FindBugs wrapper scripts support the following command-line options. - Note that these command line options are not handled by - the FindBugs program per se; rather, they are handled by the wrapper - script. -
args- Specifies arguments to pass to the JVM. For example, you might want - to set a JVM property: -
-$findbugs -textui -jvmArgs "-Duser.language=ja"myApp.jar-
-
directory- Specifies the directory containing the JRE (Java Runtime Environment) to - use to execute FindBugs. -
size- Specifies the maximum Java heap size in megabytes. The default is 256. - More memory may be required to analyze very large programs or libraries. -
- Prints a trace of detectors run and classes analyzed to standard output. - Useful for troubleshooting unexpected analysis failures. -
name=value
- This option sets a system property. FindBugs uses system properties
- to configure analysis options. See Chapter 9, Analysis Properties.
- You can use this option multiple times in order to set multiple properties.
- Note: In most versions of Windows, the name=value
- string must be in quotes.
-
- This section describes the command line options supported by FindBugs. - These command line options may be used when invoking FindBugs directly, - or when using a wrapper script. -
-These options may be used with both the GUI and command-line interfaces. -
- This option disables analyses that increase precision but also - increase memory consumption. You may want to try this option if - you find that FindBugs runs out of memory, or takes an unusually - long time to complete its analysis. -
- Enable analyses which increase precision and find more bugs, but which - may require more memory and take more time to complete. -
project
- Specify a project to be analyzed. The project file you specify should
- be one that was created using the GUI interface. It will typically end
- in the extension .fb or .fbp.
-
-These options are only accepted by the Graphical User Interface. - -
plastic|gtk|native- Set Swing look and feel. -
-
-These options are only accepted by the Text User Interface. -
- Sort reported bug instances by class name. -
filterFile.xml
- Only report bug instances that match the filter specified by filterFile.xml.
- See Chapter 8, Filter Files.
-
filterFile.xml
- Report all bug instances except those matching the filter specified by filterFile.xml.
- See Chapter 8, Filter Files.
-
com.foobar.MyClass,com.foobar.mypkg.*
- Restrict analysis to find bugs to given comma-separated list of
- classes and packages.
- Unlike filtering, this option avoids running analysis on
- classes and packages that are not explicitly matched:
- for large projects, this may greatly reduce the amount of time
- needed to run the analysis. (However, some detectors may produce
- inaccurate results if they aren't run on the entire application.)
- Classes should be specified using their full classnames (including
- package), and packages should be specified in the same way
- they would in a Java import statement to
- import all classes in the package (i.e., add .*
- to the full name of the package).
- Replace .* with .- to also
- analyze all subpackages.
-
- Report all bugs. -
- Report medium and high priority bugs. This is the default setting. -
- Report only high priority bugs. -
- Relaxed reporting mode. For many detectors, this option - suppresses the heuristics used to avoid reporting false positives. -
- Produce the bug reports as XML. The XML data produced may be - viewed in the GUI at a later time. You may also specify this - option as -xml:withMessages; when this variant - of the option is used, the XML output will contain human-readable - messages describing the warnings contained in the file. - XML files generated this way are easy to transform into reports. -
- Generate HTML output. By default, FindBugs will use the default.xsl
- XSLT
- stylesheet to generate the HTML: you can find this file in findbugs.jar,
- or in the FindBugs source or binary distributions. Variants of this option include
- -html:plain.xsl, -html:fancy.xsl and -html:fancy-hist.xsl.
- The plain.xsl stylesheet does not use Javascript or DOM,
- and may work better with older web browsers, or for printing. The fancy.xsl
- stylesheet uses DOM and Javascript for navigation and CSS for
- visual presentation. The fancy-hist.xsl an evolution of fancy.xsl stylesheet.
- It makes an extensive use of DOM and Javascript for dynamically filtering the lists of bugs.
-
- If you want to specify your own
- XSLT stylesheet to perform the transformation to HTML, specify the option as
- -html:myStylesheet.xsl,
- where myStylesheet.xsl is the filename of the
- stylesheet you want to use.
-
- Produce the bug reports in Emacs format. -
- Produce the bug reports in xdoc XML format for use with Apache Maven. -
filename- Produce the output in the specified file. -
filename- This argument is deprecated. Use -output instead. -
[:true|false]- This option enables or disables scanning of nested jar and zip files found in - the list of files and directories to be analyzed. - By default, scanning of nested jar/zip files is enabled. - To disable it, add -nested:false to the command line - arguments. -
classpath- Set the auxiliary classpath for analysis. This classpath should include all - jar files and directories containing classes that are part of the program - being analyzed but you do not want to have analyzed for bugs. -
---Copyright (c) 2000-2005 INRIA, France Telecom -All rights reserved. - - --Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - -- - -- - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - Neither the name of the copyright holders nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - -
-- --Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved. - - --Redistribution and use of this software and associated documentation -("Software"), with or without modification, are permitted provided that -the following conditions are met: - - -- - -- - Redistributions of source code must retain copyright statements and - notices. Redistributions must also contain a copy of this document. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - - The name "DOM4J" must not be used to endorse or promote products - derived from this Software without prior written permission - of MetaStuff, Ltd. For written permission, please contact - dom4j-info@metastuff.com . -- - Products derived from this Software may not be called "DOM4J" nor may - "DOM4J" appear in their names without prior written permission of - MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. - - - Due credit should be given to the DOM4J Project ( http://dom4j.org/ ). --THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' -AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -
-
|
-
-
-
- FindBugs Performance Improvements and RegressionsI did a performance check against 179 - benchmarks applications I regularly test against. Overall (total the total time to analyze all 179 - benchmarks), FindBugs 2.0 gives a 9% performance improvement over 1.3.9. 154 of the 179 benchmarks saw - performance improvements; 24 saw regressions. All of the benchmarks that saw regressions of more than - 10% were small benchmarks (analyzed in less than 60 seconds), which makes consistent benchmarking - particularly difficult. I'm working to repeat the benchmarks, see if the results are consistent. I took - a look, and couldn't find anything that stood out as being a performance glitch in FindBugs. I haven't - yet done benchmarking with constrained memory. It is possible that you may need to increase the heap - size for FindBugs 2.0. - -Important Request- If you are seeing any significant performance regressions in FindBugs 2.0,
- I very much need your help. Please either email findbugs@cs.umd.edu
- or file a
- bug report. with the following information from the xml file for your project (from both the
- 1.3.9 and 2.0.0 version if possible). Sending me your code or pointing me to a open source repository
- would be great, but I know that isn't feasible for a lot of projects. The information I'm requesting
- doesn't include any information about the code being analyzed other than the total size of the code
- being analyzed and the total number of issues found at the different confidence levels. The
- <FindBugsSummary ... > start tag. For example: - - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-FindBugs Documents and Publications- -This page lists documents, publications, and other sources -of information about FindBugs. - - General Information- -
Publications- -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-Reporting Bugs in FindBugs- --First of all, if you find a bug in FindBugs, and have the -skills to fix it, we encourage you to unleash the power of open source and -send us a patch. We will gladly -credit you on our website and in the manual. - - --Please report bugs using the -Sourceforge -bugs tracker. Note that you need to be logged in to sourceforge to -use the bug tracker. - - --If you cannot use the Sourceforge tracker, you can try sending -email to the findbugs-discuss mailing list. You must be subscribed -to the list to post a message. - - --Finally, as a last resort, you can email findbugs@cs.umd.edu. -However, such emails are much less likely to be handled in a timely manner than -posts to the tracker or mailing list. - - -False and Inaccurate Warnings- -- Like most bug-detection tools based on static analysis, FindBugs - issues some warnings that do not correspond to real bugs. - While in general we would like to make the percentage of such warnings - small, we can never fully eliminate them. - - -Information to include- --When reporting a bug, please include the following information: - -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-FindBugs sourceInfo file- -The FindBugs analysis engine can be invoked with an optional sourceInfo -file. This file gives line number ranges for classes, files and methods. This -information is an alternative to getting line number information -from the classfiles for methods. Since classfiles only contain line number -information -for methods, without a sourceInfo file we can't provide line numbers for fields, -and for classes we just use the line numbers of the methods in the class. - - The first line of the file should be - -sourceInfo version 1.0 -- - Following that are a series of lines, each describing a class, field, or method. For each, a starting and ending line number is provided. For example, the following sourceInfo file: - -sourceInfo version 1.0 -a.C,3,8 -a.C,x,4,4 -a.C,y,4,4 -a.C,-provides the following information about the class a.C: -
-a.C$X,10,15 -- - - |
- -
Send comments to findbugs@cs.umd.edu -
-
-
-
-
-
-
-
-
diff --git a/findbugs/findbugs-2.0.0/doc/sysprops.html b/findbugs/findbugs-2.0.0/doc/sysprops.html
deleted file mode 100644
index ad55622..0000000
--- a/findbugs/findbugs-2.0.0/doc/sysprops.html
+++ /dev/null
@@ -1,202 +0,0 @@
-
-
-
|
-
-
-
-FindBugs Optional System Properties- -These system properties can be added to the command line to alter the way -findbugs works. These options should be considered experimental. The description -gives information if the field is set to true. - - -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
-FindBugs Development Team- -These are the current active members of the FindBugs development team: - -
Previous and/or inactive members of the FindBugs development team include -
- - Send comments to findbugs@cs.umd.edu - |
-
-
-
|
-
-
-
- Update checking in FindBugs- -When FindBugs is run, it now checks for updated versions of FindBugs or plugins. As a side effect - of this, our server sees a request for whether there are any updated version of FindBugs available. - Third party plugins can independently receive this same information. We are recording - information about the operating system, Java version, locale, and Findbugs entry point (ant, command line, - GUI, etc), in order to better understand our users. - - For example, here is an example of the information that would be sent to the server: - -<?xml version="1.0" encoding="UTF-8"?> - -<findbugs-invocation version="2.0.0-rc1" app-name="UpdateChecker" app-version="" entry-point="UpdateChecker" os="Mac OS X" - java-version="1.6" language="en" country="US" uuid="-4bcf8f48ba2842d2"> - <plugin id="edu.umd.cs.findbugs.plugins.core" name="Core FindBugs plugin" version="2.0.0-rc1"/> - <plugin id="edu.umd.cs.findbugs.plugins.appengine" name="FindBugs Cloud Plugin" version=""/> - <plugin id="edu.umd.cs.findbugs.plugins.poweruser" name="Power user commnand line tools" version=""/> -</findbugs-invocation> -- - You can run the main method of edu.umd.cs.findbugs.updates.UpdateChecker to see what would be reported -for you, and whether update checking is disabled and/or redirected (e.g., run - java -classpath ~/findbugs/lib/findbugs.jar edu.umd.cs.findbugs.updates.UpdateChecker- - There is one element of the information sent that needs explanation: the uuid. Since we don't report anything like username, -when we receive a bunch of update checks from a particular ip address, we don't know if that is one person running FindBugs many times -on a single machine, or many users running FindBugs on many different machines So we generate a random 64 bit integer, -store it in the Java user preferences, and report that on each use. - - Disabling or redirecting update checks-Some organizations or individuals may have policies or preferences to not let us know any information about -their running of FindBugs. Note that we do not collect any information about the code being analuzed. -Even so, we understand that is very important for a few of our users, - and provide several ways for you to disable or redirect FindBugs update checks. -
|
-
|
-
-
-
-
-
- - FindBugs Users -- -- There are a - lot of FindBugs users; as of September 2006, we've had - more than 270,000 downloads. - - -- FindBugs is used in many companies and organizations. We don't - have a list of all the users of FindBugs, and we don't have - permission to identify many of the companies where we know - FindBugs is being used (getting this permission often involves red - tape and lawyers). But here are some statics from Google Analytics - showing unique visitors to the FindBugs web pages for the months - of June through August, 2006. - - -
-
- - FindBugs Users --- The following companies, projects and organizations have given us - permission to identify them as FindBugs users and/or have - publically stated that they use FindBugs. Send email to - findbugs@cs.umd.edu if - you'd like to be listed here. - - -
- FindBugs Supporters --- The following companies, organizations and institutions provide - financial support for FindBugs. Tax deductable donations to - support FindBugs can be made to the University of Maryland. - - - -
- - Send comments to findbugs@cs.umd.edu - |
-
| Warning Type | -Number | -
|---|---|
| Total | -
Click on a warning row to see full context information.
- -Project:
-
FindBugs version:
Code analyzed:
-| Metric | -Total | -Density* | -|
|---|---|---|---|
| High Priority Warnings | -
- |
- ||
| Medium Priority Warnings | -
- |
- ||
| Low Priority Warnings | -
- |
- ||
| Total Warnings | -
(* Defects per Thousand lines of non-commenting source statements)
-| Package | -Code Size | -Bugs | -Bugs p1 | -Bugs p2 | -Bugs p3 | -Bugs Exp. | -
|---|---|---|---|---|---|---|
|
- Overall
- ( |
- ||||||
| Package | -Code Size | -Bugs | -High Prio Bugs | -Medium Prio Bugs | -Low Prio Bugs | -Exp. Bugs | -Ratio | -
|---|---|---|---|---|---|---|---|
|
- Overall
- ( |
- - | ||||||
| - - |
Produced using FindBugs
Project:
-
| Warning Type | -Number | -
|---|---|
| Total | -
Click on each warning link to see a full description of the issue, and - details of how to resolve it.
- -
-
-
-
In file
None |
| Metric | -Total | -Density* | -
|---|---|---|
| High Priority Warnings | -
- |
- |
| Medium Priority Warnings | -
- |
- |
| Low Priority Warnings | -
- |
- |
| Total Warnings | -
-
- |
-
(* Defects per Thousand lines of non-commenting source statements)
-
-
(
|
- |
-
|
-
- |
- |
| - | |