Static Code Analysis & Findbug: Shihab KB

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 41

Static Code analysis &

FindBug

Shihab KB
Agenda
 To share some thoughts about static code
analysis.

 Introduce a tool, FindBugs, which is used to


do static code analysis (for java).
Common wisdom of bugs
 Programmers are smart.

 Smart people don’t make dump mistakes.

 We have good practices for finding bugs early. (Unit testing, pair
programming, code review etc)

 So, the bugs remaining in the production code must be difficult to


detect or describe ??
Why do these bug occur

 No body is perfect.

 Common types of bugs


 Misunderstood language features
 Some typing mistakes
 Misunderstood class or method
 Misunderstanding about the requirement and design
Static analysis
 Analyzes code without running it.

 Normally we have code review task in our project


schedule.

 Static analysis typically finds mistakes/bugs

 Used effectively, static analysis is cheaper than other


techniques for catching the same bugs
Static analysis
 Programmers are humans. Humans may make mistakes.

 For example, a Null bug (from eclipse source code)

 if (adapters == null && adapters.length == 0)


 return;

(This code is from Eclipse)

 Clearly a mistake
 but in practice, adapters is probably never null

 Impact
 we would probably notice a null pointer exception
When should we perform
Static analysis
 Static analysis earlier is better

 Find mistakes detected by static analysis before that are


detected using more expensive techniques

 Get them to developers while the code is still fresh in


developers heads, before anyone else is depending on it
or using it
Bug Patterns/
Programming puzzles
All are syntactically valid
 Will show you some common bugs that programmers
create during the development.
Infinite recursive loop
/** Construct a WebSpider */
public Patient() {
Patient p = new Patient();
}
(The above is a student level bug, not a developer level )

public String foundType() {


return this.foundType();
}
(This one is written by Joshua Bloch, who led the design and implementation of
numerous Java platform features, including the Java Collections Framework, the
java.math package)
Actually there is a variable named foundType in the class.
 Smart people make dumb mistakes ;-)
Infinite Recursive
Loops: Sun JDK history
 These bugs are informed by findbug

 Cases when infinite recursive loop is


 when you are using patterns like decorator
 when you forgot to say who you want to delegate.
Hashcode/Equals
 In Java all are represented as objects and all object have a
base class Object.
 Java.lang.Object has methods called hashCode() and
equals().
 In some case these methods are overridden to perform
certain purpose.
 hashCode - This method provides the hashcode of an
object.
 equals - This particular method is used to make equal
comparison between two objects.
Hashcode/Equals
 Equal objects must have equal hash codes
 Programmers sometimes override equals() but not hashCode()
 Or, override hashCode() but not equals()

 Objects violating the contract won’t work in hash tables,


maps, sets

 For Examples (53 bugs in JDK 1.6.0-b29)

 Example
Null Pointer
 Referencing a null value results in NullPointerException
 Examples

// Eclipse 3.0.0M8
Control c = getControl();
if (c == null && c.isDisposed())
return;

// Eclipse 3.0.0M8
String sig = type.getSignature();
if (sig != null || sig.length() == 1) {
return sig;
}
More Null Pointers
// JDK 1.5 build 42
if (name != null || name.length > 0) {

javax.security.auth.kerberos.KerberosTicket, 1.5b42
// flags is a parameter
// this.flags is a field
if (flags != null) {
if (flags.length >= NUM_FLAGS)
this.flags = ...
else
this.flags = ...
} else
this.flags = ...
if (flags[RENEWABLE_TICKET_FLAG]) {
Doomed Equals

if
(“com.sun.java.swing.plaf.WindowsLookAndFeel”
.equals(UIManager.getLookAndFeel())) {

}

 UIManager.getLookAndFeel returns a class and we are


comparing it with string. This will cause an error.
Unintended regular expression

String[] valueSegments = value.split(".");

It should be given as below

String[] valueSegments = value.split(“\\.");


Field Self Assignment
public TagHelpItem(String name, String file,
String startText, int startOffset,
String endText, int endOffset,
String textBefore, String textAfter){
this.name = name;
this.file = file;
this.startText = startText;
this.startTextOffset = startTextOffset;
this.endText = endText;
this.endTextOffset = endTextOffset;
this.textBefore = textBefore;
this.textAfter = textAfter;
this.identical = null;
}
Confusing/bad naming
 Methods with identical names and signatures
– but different capitalization of names
– could mean you don’t override method in
superclass
 Method name same as class name
– gets confused with constructor
Bad naming in jdk1.6.0-b29
/** @return a hash code value
*for the object.
*/
public int hashcode() {
return basic_type.hashCode()^ dimensions;
}
Ignoring of return values
String s5 = n.getValues();
s5.replace("a", "x"); //This function returns a value.
//We don’t have to ignore this.

//This is the right method.


String s6 = s5.replace("a", "x");
FindBugs
 Open source static analysis tool for finding defects in
Java programs

 Analyzes class files

 Generates XML or text output


 can run in Netbeans/Swing/Eclipse/Ant/

 Total downloads from SourceForge: 274,291+


FindBugs
 Static analysis tool to find defects in Java code

 It is not a style checker

 Can find hundreds of defects in each of large apps such


as Sun's JDK, Bea WebLogic, IBM Websphere

 FindBugs was originally written by Bill Pugh


(He is currently a professor of computer science at the University of Maryland)

 Is this tool find all bugs?


 No, No, Never
FindBugs - Installation

 Requirements

 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.
FindBugs - Installation

 Can be downloaded from

 http://findbugs.sourceforge.net/downloads.html

 Unzip the downloaded file. That’s all. You can double click the
findbugs.bat file from \findbugs-1.3.9\bin folder
Using the FindBugs GUI

Choose class’s
location here

Choose source
code’s location here
Using the FindBugs GUI
Using the FindBugs™ Eclipse
plugin
 Requirements
 To use the FindBugs Plugin for Eclipse, you need
Eclipse 3.3 or later, and JRE/JDK 1.5 or later.
 Goto Help->Software Updates (See next
slide)
 You can also manually download the plugin
and extract it in Eclipse's "plugins"
subdirectory.
Using the FindBugs™ Eclipse
plugin
FindBugs command line
 findbugs -textui -xml rt.jar >rt.xml
FindBugs Annotations
 Annotations in Java is all about
adding meta-data facility to the Java
Elements. Like Classes, Interfaces or
Enums, Annotations define a type in
Java and they can be applied to
several Java Elements.

 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.
Annotations - Example
import edu.umd.cs.findbugs.annotations.CheckForNull;
..
..
..
@CheckForNull
public Patient getPatient(int flag) {
Patient p = null;
if (flag == 1) {
p = new Patient();
}
return p;
}
FindBugs Annotations
 edu.umd.cs.findbugs.annotations.CheckForNull
 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.
 edu.umd.cs.findbugs.annotations.CheckReturnValue
 This annotation is used to denote a method whose return value should always be
checked after invoking the method.
 …..
Test, test, test...
 Many times FindBugs will identify bugs.
 So, is testing can be skip after executing FindBugs?
 Never
 Overall, testing is far more valuable than static analysis
 But no one writes code so good you don’t need to check that it does
the right thing

I’ve learned this from personal painful experience 
FindBugs Users
Conclusion
 As a conclusion I would strongly recommend
to do static analysis in the code and use
static analysis tools like FindBugs so that we
can reduce the number bug reported during
testing.
Similar other tools
 Jlint - Jlint will check your Java code and find
bugs, inconsistencies and synchronization
problems by doing data flow analysis
(http://artho.com/jlint/).
 PMD - PMD scans Java source code and
looks for potential problems
(http://pmd.sourceforge.net/).
A comparison
Demo
 Live Demo of running find bugs in eclipse
source code.
References
 http://findbugs.sourceforge.net/
Thank You

You might also like