SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
FindBugs

                               Bernhard Merkle
                        Research & Development
                           Software-Engineering
                          SICK-AG Waldkirch/DE
mailto: Bernhard.Merkle@gmail.com
contact on linkedin.com or xing.com          Page: 1
Possible levels of Static Analysis:
Micro-Level
  – Code
  – e.g: =, ==, { },


Macro-Level
  – Class-Design
  – e.g: by reference, String concat, Exception-Handling


Architecture-Level:
  – Layers, Graphs, Subsystems, Compoments, Interfaces
  – e.g: Coupling, Dependency, etc…

                                                           Page: 6
Static Analysis
Analyzes program without executing it

Doesn’t depend on having good test cases

Doesn’t know what your software is supposed to do
  – Looks for violations of reasonable programming


Tools for static analysis:
  – Commercial:
      • lint, coverity, QA/C/C++, fortify, CodeTest etc
  – Free:
      • PMD, findbugs

                                                          Page: 12
Design + Coding Guidelines




                             Page: 13
if (in == null)
    try {
     in.close();
    …
    }


Eclipse 3.0.0. M8

                    Page: 15
if (listeners == null)
   listeners.remove(listener);

sun.awt.x11.XMSelection
JDK1.6.0, b105

                            Page: 17
public String foundType() {
   return this.foundType();
}

j.l.annotation.AnnotationTypeMismatchException
JDK1.6.0, b13
Bug by Josh Bloch, author of Effective Java

                                                 Page: 19
FindBugs:
features:
  – Bytecode-level static analysis

  – GUI (swing,eclipse,netbeans)
  – Commandline, buildserver
  – Findbugs 2.0: Cloud

  – XML-based format for saved warnings
     • Handling multiple versions of software
     • Tracking warnings over time




                                                Page: 22
Page: 23
Page: 24
Page: 26
Bug Categroies and Bug Patterns


  Bug Categories

  Bug Patterns
                                  Page: 27
Bug Patterns
Some big, broad and common patterns
  – Dereferencing a null pointer
  – An impossible checked cast
  – Methods whose return value should not be ignored


Specific bug patterns, e.g. from
  – Effective Java
  – Programming Puzzler




                                                       Page: 28
Analysis Techniques
Local pattern matching
  – String.toLowerCase(), don’t ignore the return value


Intraprocedural dataflow analysis
  – Null pointer, type cast errors


Interprocedural method summaries
  – E.g. method always dereferences its parameter


Context sensitive interprocedural analysis
  – Interprocedural flow of untrusted data, injection
                                                          Page: 29
Redundant Check For Null
Checking a value to see if it is null When it can't be null

// java.awt.image.LoopupOp, lines 236-247
public final WritableRaster filter(
          Raster src, WritableRaster dst) {
     int dstLength = dst.getNumBands();
     // Create a new destination Raster,
     // if needed
     if (dst == null)




                                                          Page: 32
Bad Method Invocation
Methods whose return value shouldn't be ignored
  – Strings are immutable, so functions like trim()
    and toLowerCase() return new String


Lots of specific rules about particular API methods
  – Hard to memorize, easy to get wrong




                                                      Page: 33
Examples of bad method calls
// com.sun.rowset.CachedRowSetImpl
if (type == Types.DECIMAL || type == Types.NUMERIC)
        ((java.math.BigDecimal)x).setScale(scale);



// com.sun.xml.internal.txw2.output.XMLWriter
try { ... }
catch (IOException e) {
        new SAXException("Server side Exception:" + e);
}




                                                      Page: 34
Page: 35
3 Methods Common to All Objects

 –   Item 8: Obey the general contract when overriding equals
 –   Item 9: Always override hashCode when you override equals
 –   Item 10: Always override toString
 –   Item 11: Override clone judiciously
 –   Item 12: Consider implementing Comparable




                                                                 Page: 36
Item 8: Obey contract overriding equals
easiest way to avoid problems is:
  – not to override equals

right thing to do if any of the following conditions apply:
  – Each instance of the class is inherently unique (no value)
     • Thread

  – don’t care whether class provides a “logical equality” test
     • java.util.Random

  – A superclass has already overridden equals,
    && the superclass behavior is appropriate for this class.
     • Set impls inherit equals from AbstractSet
       (dito List, Map)



                                                                 Page: 37
Item 8: Obey contract overriding equals

right thing to do if any of the following conditions apply:
  – class is private or package-private, and you are certain that
    its equals method will never be invoked
      • Really certain ?
      @Override public boolean equals(Object o) {
        // Method is never called
       throw new AssertionError();
      }




                                                              Page: 38
Item 8: Obey contract overriding equals
When to override Object.equals() ?

  – logical equality that differs from mere object identity
  – Value classes (Integer, Date, etc)

  – must adhere to its general contract for Object [JavaSE6]:
    The equals method implements an equivalence relation.
     •   Reflexive:
     •   Symmetric:
     •   Transitive:
     •   Consistent: multiple invocations of x.equals(y) return same value
     •   For any non-null reference value x, x.equals(null) must return false.


                                                                            Page: 39
Item 8: Obey contract overriding equals
a recipe for a high-quality equals() method:
  – Use == operator to check if argument is a reference to this
    object
     • If so, return true. Performance optimization
  – Use the instanceof operator to check if the argument has the
    correct type
     • If not, return false.
  – Cast the argument to the correct type
  – For each “significant” field in the class, check matches
     • For primitive fields, use == operator
     • For object reference fields, use equals()
     • For float/double use Float/Double.compare()
     • Arrays.equals
  – Watch out for null
  (field == null ? o.field == null :
    field.equals(o.field))
                                                             Page: 40
Item 8: Obey contract overriding equals
Caveat when overriding equals() method
  – Always override hashCode when override equals (Item 9).
  – Don’t try to be too clever
     • If you are overly aggressive in searching for equivalence,
       it’s easy to get into trouble. E.g. aliasing))
  – Don’t substitute another type for Object in the equals
    declaration (override vs. overload)
     //MyClass.class
     public boolean equals(MyClass o) {
     ...
     }
        Consistent use of the @Override annotation

                                                                    Page: 41
Test Item 8 with real code
Equal objects must have equal hash codes
  – Fail: override equals() but not hashCode()
    (or other way around)
  – Object violating the contract won’t work in
    hash table, maps, set, etc

  – Examples: (53 bugs in JDK 1.6.0)
  – java.awt.geom.Area
  – javax.management.Attribute




                                                  Page: 42
Other Categories
Bad practice

Dodgy code

Multithreaded correctness

Performance

Vulnerability to malicious code


                                  Page: 44
Bad Practice
•A class that defines an equals method but inherits
hashCode from Object

•equals method doesn't handle null argument

•Serializable class without a serialVersionUID

•Exception caught and ignored




                                                      Page: 45
Dodgy code
•Dead local store - a value is stored into a local variable,
but that value is never used

•Use of non-short circuit boolean logic

•Switch statement fallthrough

•Branch where code on both branches is identical




                                                         Page: 46
Multithreaded correctness
•Inconsistent synchronization - a lock is held most of the
time a field is accessed, but not always

•Problems with wait/notify - e.g., call to wait() not in
loop

•thread unsafe lazy initialization of static field




                                                           Page: 47
Performance
•Unused field

•Invocation of Boolean or Integer constructors

•final constant field that could be made static

•Loop with quadratic string concatenation

•Inner class that could be made static


                                                  Page: 48
Vunerability to Malicious code
•public static non-final fields

•public static final fields that reference mutable objects

•Methods that don’t defensively copy mutable
arguments before storing them into fields

•Methods that don’t defensively copy mutable values
stored in fields before returning them


                                                        Page: 49
Bad naming in Eclipse
 package org.eclipse.jface.dialogs;

 public abstract class Dialog extends Window {
    protected Button getOKButton () {
    ….
    }

 public class InputDialog extends Dialog {
    protected Button getOkButton() {
    ….
    }




                                                 Page: 52
Page: 55
Basic Approach Algorithm:


Start with a bug (important!)

Write the simplest possible detector

While (not happy && False positive rate )
      Refine: improve analysis FP suppression heuristics

Done


                                                     Page: 57
Example Bug
Don’t use String literals for the synchronized blocks!

static private final String LOCK = "LOCK";
void someMethod() {
     synchronized(LOCK) {
        ...
     }
}


Real world example from Jetty
If other code synchronizes on same String: deadlock
                                                         Page: 58
Writing a detector
Bytecode:
      LDC "LOCK"
      DUP
      ASTORE 1
      MONITORENTER

Let’s use opcode stack.
Could also look for bytecode sequence.



                                         Page: 59
SynchronizationOnSharedBuiltinConstant
public void sawOpcode(int seen) {
if (seen == MONITORENTER) {
   OpcodeStack.Item top = stack.getStackItem(0);

    if (top.getSignature().equals("Ljava/lang/String;")
        && top.getConstant() instanceof String)

          bugReporter.reportBug(new BugInstance(this,
          "DL_SYNCHRONIZATION_ON_SHARED_CONSTANT",
          NORMAL_PRIORITY)
          .addClassAndMethod(this)
          .addString((String)constant)
          .addSourceLine(this));
    }

}
                                                          Page: 60
Results
Found issue fixed in Jetty-352.

Jetty-352 didn’t fix all occurrences in Jetty (Jetty-362).

Also found occurrences in Eclipse, glassfish, Sun’s JDK,
netbeans, nutch, oc4j, weblogic, websphere




                                                             Page: 61
More simple rules:
do not require code analysis: e.g.

  – classes that override equals() but not hashCode()

  – method naming problems
    (e.g., hashcode() instead of hashCode())




                                                        Page: 62
More simple rules




                    Page: 63
Caveat




         Page: 64
Caveat

Bytecode != Bytecode
Eclipse ejc and JDK javac




                            Page: 65
New Findbugs Features in 2.x
Dashboard like
  – Keep track when bugs were introduced/resolved
  – Historical recorder


Roadmap ?
  –   Client API,
  –   multicore analysis,
  –   cleanup BCEL, etc
  –   Refactor findbugs itself (Architecture Eriosion)




                                                         Page: 66
Findbugs in the Cloud




                        Page: 67
Findbugs, eclipse




                    Page: 68
Findbugs, eclipse




                    Page: 69

Mais conteúdo relacionado

Mais procurados

Elements of Java Language - Continued
Elements of Java Language - Continued Elements of Java Language - Continued
Elements of Java Language - Continued Hitesh-Java
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureJayaram Sankaranarayanan
 
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...Lionel Briand
 
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,..."Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...Vladimir Ivanov
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++Prof Ansari
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programmingRaza Najam
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJAXLondon_Conference
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockschlebu
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 

Mais procurados (20)

Elements of Java Language - Continued
Elements of Java Language - Continued Elements of Java Language - Continued
Elements of Java Language - Continued
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
 
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...
Known XML Vulnerabilities Are Still a Threat to Popular Parsers ! & Open Sour...
 
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,..."Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Java chapter 2
Java chapter 2Java chapter 2
Java chapter 2
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programming
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 

Semelhante a findbugs Bernhard Merkle

Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011Juan Gomez
 
How to really obfuscate your pdf malware
How to really obfuscate   your pdf malwareHow to really obfuscate   your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019Paulo Clavijo
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad WoodOrtus Solutions, Corp
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataCodemotion Tel Aviv
 
Advanced
AdvancedAdvanced
Advancedmxmxm
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad WoodOrtus Solutions, Corp
 

Semelhante a findbugs Bernhard Merkle (20)

Modern C++
Modern C++Modern C++
Modern C++
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011
 
Responsible JavaScript
Responsible JavaScriptResponsible JavaScript
Responsible JavaScript
 
How to really obfuscate your pdf malware
How to really obfuscate   your pdf malwareHow to really obfuscate   your pdf malware
How to really obfuscate your pdf malware
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malware
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
 
Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015Sperasoft‬ talks j point 2015
Sperasoft‬ talks j point 2015
 
Java performance
Java performanceJava performance
Java performance
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad Wood
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Advanced
AdvancedAdvanced
Advanced
 
Gallio Crafting A Toolchain
Gallio Crafting A ToolchainGallio Crafting A Toolchain
Gallio Crafting A Toolchain
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Scalax
ScalaxScalax
Scalax
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

findbugs Bernhard Merkle

  • 1. FindBugs Bernhard Merkle Research & Development Software-Engineering SICK-AG Waldkirch/DE mailto: Bernhard.Merkle@gmail.com contact on linkedin.com or xing.com Page: 1
  • 2. Possible levels of Static Analysis: Micro-Level – Code – e.g: =, ==, { }, Macro-Level – Class-Design – e.g: by reference, String concat, Exception-Handling Architecture-Level: – Layers, Graphs, Subsystems, Compoments, Interfaces – e.g: Coupling, Dependency, etc… Page: 6
  • 3. Static Analysis Analyzes program without executing it Doesn’t depend on having good test cases Doesn’t know what your software is supposed to do – Looks for violations of reasonable programming Tools for static analysis: – Commercial: • lint, coverity, QA/C/C++, fortify, CodeTest etc – Free: • PMD, findbugs Page: 12
  • 4. Design + Coding Guidelines Page: 13
  • 5. if (in == null) try { in.close(); … } Eclipse 3.0.0. M8 Page: 15
  • 6. if (listeners == null) listeners.remove(listener); sun.awt.x11.XMSelection JDK1.6.0, b105 Page: 17
  • 7. public String foundType() { return this.foundType(); } j.l.annotation.AnnotationTypeMismatchException JDK1.6.0, b13 Bug by Josh Bloch, author of Effective Java Page: 19
  • 8. FindBugs: features: – Bytecode-level static analysis – GUI (swing,eclipse,netbeans) – Commandline, buildserver – Findbugs 2.0: Cloud – XML-based format for saved warnings • Handling multiple versions of software • Tracking warnings over time Page: 22
  • 12. Bug Categroies and Bug Patterns Bug Categories Bug Patterns Page: 27
  • 13. Bug Patterns Some big, broad and common patterns – Dereferencing a null pointer – An impossible checked cast – Methods whose return value should not be ignored Specific bug patterns, e.g. from – Effective Java – Programming Puzzler Page: 28
  • 14. Analysis Techniques Local pattern matching – String.toLowerCase(), don’t ignore the return value Intraprocedural dataflow analysis – Null pointer, type cast errors Interprocedural method summaries – E.g. method always dereferences its parameter Context sensitive interprocedural analysis – Interprocedural flow of untrusted data, injection Page: 29
  • 15. Redundant Check For Null Checking a value to see if it is null When it can't be null // java.awt.image.LoopupOp, lines 236-247 public final WritableRaster filter( Raster src, WritableRaster dst) { int dstLength = dst.getNumBands(); // Create a new destination Raster, // if needed if (dst == null) Page: 32
  • 16. Bad Method Invocation Methods whose return value shouldn't be ignored – Strings are immutable, so functions like trim() and toLowerCase() return new String Lots of specific rules about particular API methods – Hard to memorize, easy to get wrong Page: 33
  • 17. Examples of bad method calls // com.sun.rowset.CachedRowSetImpl if (type == Types.DECIMAL || type == Types.NUMERIC) ((java.math.BigDecimal)x).setScale(scale); // com.sun.xml.internal.txw2.output.XMLWriter try { ... } catch (IOException e) { new SAXException("Server side Exception:" + e); } Page: 34
  • 19. 3 Methods Common to All Objects – Item 8: Obey the general contract when overriding equals – Item 9: Always override hashCode when you override equals – Item 10: Always override toString – Item 11: Override clone judiciously – Item 12: Consider implementing Comparable Page: 36
  • 20. Item 8: Obey contract overriding equals easiest way to avoid problems is: – not to override equals right thing to do if any of the following conditions apply: – Each instance of the class is inherently unique (no value) • Thread – don’t care whether class provides a “logical equality” test • java.util.Random – A superclass has already overridden equals, && the superclass behavior is appropriate for this class. • Set impls inherit equals from AbstractSet (dito List, Map) Page: 37
  • 21. Item 8: Obey contract overriding equals right thing to do if any of the following conditions apply: – class is private or package-private, and you are certain that its equals method will never be invoked • Really certain ? @Override public boolean equals(Object o) { // Method is never called throw new AssertionError(); } Page: 38
  • 22. Item 8: Obey contract overriding equals When to override Object.equals() ? – logical equality that differs from mere object identity – Value classes (Integer, Date, etc) – must adhere to its general contract for Object [JavaSE6]: The equals method implements an equivalence relation. • Reflexive: • Symmetric: • Transitive: • Consistent: multiple invocations of x.equals(y) return same value • For any non-null reference value x, x.equals(null) must return false. Page: 39
  • 23. Item 8: Obey contract overriding equals a recipe for a high-quality equals() method: – Use == operator to check if argument is a reference to this object • If so, return true. Performance optimization – Use the instanceof operator to check if the argument has the correct type • If not, return false. – Cast the argument to the correct type – For each “significant” field in the class, check matches • For primitive fields, use == operator • For object reference fields, use equals() • For float/double use Float/Double.compare() • Arrays.equals – Watch out for null (field == null ? o.field == null : field.equals(o.field)) Page: 40
  • 24. Item 8: Obey contract overriding equals Caveat when overriding equals() method – Always override hashCode when override equals (Item 9). – Don’t try to be too clever • If you are overly aggressive in searching for equivalence, it’s easy to get into trouble. E.g. aliasing)) – Don’t substitute another type for Object in the equals declaration (override vs. overload) //MyClass.class public boolean equals(MyClass o) { ... } Consistent use of the @Override annotation Page: 41
  • 25. Test Item 8 with real code Equal objects must have equal hash codes – Fail: override equals() but not hashCode() (or other way around) – Object violating the contract won’t work in hash table, maps, set, etc – Examples: (53 bugs in JDK 1.6.0) – java.awt.geom.Area – javax.management.Attribute Page: 42
  • 26. Other Categories Bad practice Dodgy code Multithreaded correctness Performance Vulnerability to malicious code Page: 44
  • 27. Bad Practice •A class that defines an equals method but inherits hashCode from Object •equals method doesn't handle null argument •Serializable class without a serialVersionUID •Exception caught and ignored Page: 45
  • 28. Dodgy code •Dead local store - a value is stored into a local variable, but that value is never used •Use of non-short circuit boolean logic •Switch statement fallthrough •Branch where code on both branches is identical Page: 46
  • 29. Multithreaded correctness •Inconsistent synchronization - a lock is held most of the time a field is accessed, but not always •Problems with wait/notify - e.g., call to wait() not in loop •thread unsafe lazy initialization of static field Page: 47
  • 30. Performance •Unused field •Invocation of Boolean or Integer constructors •final constant field that could be made static •Loop with quadratic string concatenation •Inner class that could be made static Page: 48
  • 31. Vunerability to Malicious code •public static non-final fields •public static final fields that reference mutable objects •Methods that don’t defensively copy mutable arguments before storing them into fields •Methods that don’t defensively copy mutable values stored in fields before returning them Page: 49
  • 32. Bad naming in Eclipse package org.eclipse.jface.dialogs; public abstract class Dialog extends Window { protected Button getOKButton () { …. } public class InputDialog extends Dialog { protected Button getOkButton() { …. } Page: 52
  • 34. Basic Approach Algorithm: Start with a bug (important!) Write the simplest possible detector While (not happy && False positive rate ) Refine: improve analysis FP suppression heuristics Done Page: 57
  • 35. Example Bug Don’t use String literals for the synchronized blocks! static private final String LOCK = "LOCK"; void someMethod() { synchronized(LOCK) { ... } } Real world example from Jetty If other code synchronizes on same String: deadlock Page: 58
  • 36. Writing a detector Bytecode: LDC "LOCK" DUP ASTORE 1 MONITORENTER Let’s use opcode stack. Could also look for bytecode sequence. Page: 59
  • 37. SynchronizationOnSharedBuiltinConstant public void sawOpcode(int seen) { if (seen == MONITORENTER) { OpcodeStack.Item top = stack.getStackItem(0); if (top.getSignature().equals("Ljava/lang/String;") && top.getConstant() instanceof String) bugReporter.reportBug(new BugInstance(this, "DL_SYNCHRONIZATION_ON_SHARED_CONSTANT", NORMAL_PRIORITY) .addClassAndMethod(this) .addString((String)constant) .addSourceLine(this)); } } Page: 60
  • 38. Results Found issue fixed in Jetty-352. Jetty-352 didn’t fix all occurrences in Jetty (Jetty-362). Also found occurrences in Eclipse, glassfish, Sun’s JDK, netbeans, nutch, oc4j, weblogic, websphere Page: 61
  • 39. More simple rules: do not require code analysis: e.g. – classes that override equals() but not hashCode() – method naming problems (e.g., hashcode() instead of hashCode()) Page: 62
  • 40. More simple rules Page: 63
  • 41. Caveat Page: 64
  • 42. Caveat Bytecode != Bytecode Eclipse ejc and JDK javac Page: 65
  • 43. New Findbugs Features in 2.x Dashboard like – Keep track when bugs were introduced/resolved – Historical recorder Roadmap ? – Client API, – multicore analysis, – cleanup BCEL, etc – Refactor findbugs itself (Architecture Eriosion) Page: 66
  • 44. Findbugs in the Cloud Page: 67
  • 45. Findbugs, eclipse Page: 68
  • 46. Findbugs, eclipse Page: 69