JSR-305: Annotations for Software Defect Detection

Similar documents
Status Report. JSR-305: Annotations for Software Defect Detection. William Pugh Professor

Code verification. CSE 331 University of Washington. Michael Ernst

Using Type Annotations to Improve Your Code

The Checker Framework: pluggable static analysis for Java

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

The Java Type System (continued)

Rules and syntax for inheritance. The boring stuff

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

FindBugs review of Glassfish v2 b09

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

interface MyAnno interface str( ) val( )

Detecting and preventing null pointer errors with pluggable type-checking

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Operators and Expressions

Defective Java Code: Turning WTF code into a learning experience

CSE 331 Software Design and Implementation. Lecture 16 Checker Framework

Introduction to Programming Using Java (98-388)

Lecture 19 Checker Framework

1 Shyam sir JAVA Notes

Java Database Connectivity

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Defective Java Code: Turning WTF code into a learning experience

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

A Short Summary of Javali

EMBEDDED SYSTEMS PROGRAMMING More About Languages

The New Java Technology Memory Model

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Super-Classes and sub-classes

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CS-202 Introduction to Object Oriented Programming

3 ADT Implementation in Java

CH. 2 OBJECT-ORIENTED PROGRAMMING

CMSC 132: Object-Oriented Programming II

Language Features. 1. The primitive types int, double, and boolean are part of the AP

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Type Checking and Type Equality

EECS168 Exam 3 Review

Definition of DJ (Diminished Java)

Points To Remember for SCJP

Java Programming Training for Experienced Programmers (5 Days)

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Object-Oriented Principles and Practice / C++

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Page 1

Java 8 Programming for OO Experienced Developers

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Another IS-A Relationship

CS 251 Intermediate Programming Methods and Classes

Inheritance (Part 5) Odds and ends

CS 251 Intermediate Programming Methods and More

Lecture Topics. Administrivia

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

QUIZ. What is wrong with this code that uses default arguments?

Preventing Errors Before They Happen The Checker Framework

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Java Fundamentals (II)

Detecting and preventing null pointer errors with pluggable type-checking

Interfaces. An interface forms a contract between the object and the outside world.

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Principles of Software Construction: Objects, Design, and Concurrency (Part 2: Designing (Sub )Systems)

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Introduction to Inheritance

Abstract Classes and Interfaces

CSE 331 Final Exam 3/12/12

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

QUIZ. What are 3 differences between C and C++ const variables?

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

CSE 331 Final Exam 6/5/17. Name UW ID#

c) And last but not least, there are javadoc comments. See Weiss.

CLASS DESIGN. Objectives MODULE 4

Java: introduction to object-oriented features

Lecture 2, September 4

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

INHERITANCE. Spring 2019

Java Overview An introduction to the Java Programming Language

CSE 331 Final Exam 3/16/15 Sample Solution

Software Engineering /48

The Java Programming Language

Java Enum Java, winter semester ,2018 1

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

Array. Prepared By - Rifat Shahriyar

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function

Transcription:

JSR-305: Annotations for Software Defect Detection William Pugh Professor Univ. of Maryland pugh@cs.umd.edu http://www.cs.umd.edu/~pugh/ 1

Why annotations? Static analysis can do a lot can even analyze interprocedural paths Why do we need annotations? they express design decisions that may be implicit, or described in documentation, but not easily available to tools 2

Where is the bug? if (spec!= null) ffragments.add(spec); if (iscomplete(spec)) fpreferences.add(spec); boolean iscomplete(annotationpreference spec) { return spec.getcolorpreferencekey()!= null && spec.getcolorpreferencevalue()!= null && spec.gettextpreferencekey()!= null && spec.getoverviewrulerpreferencekey()!= null; } 3

Finding the bug Many bugs can only be identified, or only localized, if you know something about what the code is supposed to do Annotations are well suited to this... e.g., @Nonnull 4

JSR-305 At least two tools already have defined their own annotations: FindBugs and IntelliJ No one wants to have to apply two sets of annotations to their code come up with a common set of annotations that can be understood by multiple tools 5

JSR-305 target JSR-305 is intended to be compatible with JSE 5.0+ Java 6

JSR-308 Annotations on Java Types Designed to allow annotations to occur in many more places than they can occur now ArrayList<@Nonnull String> a =... Targets JSE 7.0 Will add value to JSR-305, but JSR-305 cannot depend upon JSR-308 7

Nullness Nullness is a great motivating example Most method parameters are expected to always be nonnull some research papers support this Not always documented in JavaDoc 8

Documenting nullness Want to document parameters, return values, fields that should always be nonnull Should warn if null passed where nonnull value required And which should not be presumed nonnull argument to equals(object) Should warn if argument to equals is immediately dereferenced 9

Only two cases? What about Map.get(...)? Return null if key not found even if all values in Map are nonnull So the return value can t be @Nonnull But lots of places where you know that the returned value will be nonnull 10

Null in some situation There are places where a value might be null, under some circumstance return value from Map.get(Object) first argument to Method.invoke(Object obj, Obj.. args) should be null if method is a static method 11

Just dereference it If you use that value that might be null in some circumstance, but you have reason to believe should not be null (perhaps due to the values of other parameters, or program state) you might just dereference it without null check If it is null, something is wrong and throwing a NPE is the right thing to do 12

Data on use of Map.get(...) In JDK 1.6.0, build 105 196 calls to Map.get(...) where the return value is dereferenced without a null check 13

Thus, 3 cases I think there have 3 nullness annotations @Nonnull @NullFeasible @UnknownNullness same as no annotation Would love better name suggestions might use @Nullable for one of last two these, but which one? 14

@Nonnull Should not be null For fields, interpreted as should be nonnull after object is initialized Tools will try to generate a warning if they see a possibly null value being used where a nonnull value is required same as if they see a dereference of a possibly null value 15

@NullFeasible Code should always worry that this value might be null e.g., argument to equals Tools should flag any dereference that isn t preceded by a null check 16

@UnknownNullness Same as no annotation Needed because we are going to introduce default and inherited annotations Need to be able to get back to original state Null under some circumstances might vary in subtypes, or depend on other parameters or state Interprocedural analysis might give us better information 17

@NullFeasible requires work If you mark a return value as @NullFeasible, you will likely have to go make a bunch of changes kind of like const in C++ My experience has been that there are lots of methods that could return null but that in a particular calling context, you may know that it can t 18

Proving no NPEs Some static analysis tools might want to prove that no null pointers can be dereferenced Such tools would likely warn if a value with unknown nullness is dereferenced without a null check other tools would not generate a warning in this case 19

Type Qualifiers Many of the JSR-305 annotations will be type qualifiers: additional type constraints on top of the existing Java type system aka Pluggable type system 20

@Nonnegative and friends Fairly clear motivation for @Nonnegative More? @Positive Where do we stop? @NonZero @PowerOfTwo @Prime 21

Three-way logic again If we have @Nonnegative, do we also need: @Signed similar to @NullFeasible returned by hashcode(), Random.nextInt() @UnknownSign similar to unknown nullness 22

User defined type qualifiers In (too many) places, Java APIs use integer values or Strings where enumerations would have been better except that they weren t around at the time Lots of potential errors, uncaught by compiler 23

Example in java.sql.connection createstatement(int resultsettype, int resultsetconcurrency, int resultsetholdability) Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability. resultsettype: one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE resultsetconcurrency: one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE resultsetholdability: one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT 24

The fix Declare public @TypeQualifier @interface ResultSetType {} public @TypeQualifier @interface ResultSetConcurrency {} public @TypeQualifier @interface ResultSetHoldability {} Annotate static constants and method parameters 25

User defined Type Qualifiers JSR-305 won t define @ResultSetType Rather JSR-305 will define the metaannotations that allow any developer to define their own type qualifier annotations which they can apply and will be interpreted by defect detection tools 26

Defining a type qualifier @TypeQualifier public @interface Nonnull { When when() default When.ALWAYS; } 27

The When element An enum that describes the relationship between the values S allowed at a location and the set T of values described by the type qualifier values: ALWAYS, NEVER, MAYBE, UNKNOWN 28

Meanings NEVER ALWAYS ALWAYS: S T NEVER: S T MAYBE MAYBE: ALWAYS NEVER UNKNOWN: true 29

Applied to Nonnull Say we start by defining @Nonnull @Nonnull(when=When.MAYBE) null feasible @Nonnull(when=When.UNKNOWN) unknown nullness 30

Why so many when s? Don t want to bias type qualifiers as to whether you start with the positive or negative version @Nonnull(when=When.NEVER) represents a value that is always null But what if we had started by defining @Null @Null(when=When.NEVER) nonnull @Null(when=When.MAYBE) null feasible 31

More examples Start by defining @Negative @Negative(when=When.NEVER) nonnegative @Negative(when=When.MAYBE) signed 32

Checking type qualifiers If we detect a feasible path on which a ALWAYS or MAYBE source flows to a NEVER sink generate a warning And the converse NEVER or MAYBE source flowing to an ALWAYS sink 33

Strict type qualifiers If you don t define a when element for a type qualifier, the type qualifier is strict applying it is treated as ALWAYS anything else is treated as UNKNOWN report a warning if an UNKNOWN source reaches an ALWAYS sink Great for stuff like @ResultSetHoldability 34

The value element Type qualifiers can define a value element @TypeQualifier public @interface Foo { } int value(); Defines a family of type qualifiers: @Foo(1), @Foo(2),... Orthagonal/Independent Whether a value is @Foo(1) is independent of whether it is @Foo(2) 35

Exclusive values public @TypeQualifier(exclusive=true) @interface ClassName { Kind value(); enum Kind { SLASHED, DOTTED }; } Defines two exclusive type qualifiers: @ClassName(ClassName.Kind.SLASHED) @ClassName(ClassName.Kind.DOTTED) Anything marked as @ClassName(ClassName.Kind.SLASHED) ALWAYS is also @ClassName(ClassName.Kind.DOTTED) NEVER 36

Exhaustive values? public @TypeQualifier(exhaustive=true) @interface Bar { } Color value(); enum Color { RED, GREEN, BLUE }; If something is Bar(Color.RED) NEVER and Bar(Color.GREEN) NEVER it must be Bar(Color.BLUE) ALWAYS If a value is exhaustive, it is also exclusive. 37

Syntax Two potential ways to denote exclusive/ exhaustive type qualifiers 1)Define boolean exclusive/exhaustive attributes to the TypeQualifier 2)Define marker annotations that are applied to the value() member of a TypeQualifier 38

Possible syntax Syntax (1) public @TypeQualifier(exclusive=true) @interface Bar { } Syntax (2) Color value(); enum Color { RED, GREEN, BLUE }; public @TypeQualifier @interface Bar { } @Exclusive Color value(); enum Color { RED, GREEN, BLUE }; 39

Example usage public @TypeQualifier(exhaustive=true) @interface Sign { } NumericSign value(); When when() default When.ALWAYS; enum NumericSign { NEGATIVE, ZERO, POSITIVE }; Can then define @Nonnegative, @Nonzero, etc. 40

Limiting the scope of a type qualifier When the @TypeQualifier annotation is applied, can define the types it can be applied to: @TypeQualifier( applicableto=charsequence.class) public @interface Foo {} primitive types allowed if wrapper types allowed 41

Type qualifier nicknames No one wants to be typing @Nonnull(when=When.MAYBE) all over the place Define a type qualifier nickname @TypeQualifierNickname @Nonnull(when=When.MAYBE) public @interface NullFeasible {} 42

Default and Inherited Type Qualifiers

Most parameters are nonnull Most reference parameters are intended to be non-null many return values and fields as well Adding a @Nonnull annotation to a majority of parameters won t sell Treating all non-annotated parameters as nonnull also won t sell 44

Default type qualifiers Can mark a method, class or package as having nonnull parameters by default If a parameter doesn t have a nullness annotation climb outwards, looking at method, class, outer class, and then package, to find a default annotation Can mark a package as nonnull parameters by default, and change that on a class or parameter basis as needed 45

Inherited Annotations We want to inherit annotations Object.equals(@CheckForNull Object obj) int compareto(@nonnull E e) @Nonnull Object clone() 46

Inherited qualifiers take precedence over default Default qualifiers shouldn t interfere with or override inherited type qualifiers 47

Do defaults apply to most JSR-305 type qualifiers? Case for default and inherited nullness type qualifiers is very compelling Should it be general mechanism available for many/all type qualifiers? 48

Defining default type qualifiers @TypeQualifierDefault marks an annotation that can be used to specify default type qualifiers @Nonnull @TypeQualifierDefault(ElementType.PARAMETER) public @interface ParametersAreNonnullByDefault {} 49

Meaning If TypeQualifierDefault is used to annotate an annotation Any type qualifiers also applied to the annotation are taken as defaults for the element types provided as arguments to the TypeQualifierDefault 50

Defined default annotations JSR-305 will only define ParametersAreNonnullByDefault, but more can be defined outside of JSR-305 and can be interpreted by static analyzers that interpret JSR-305 annotations 51

Using default annotations Just apply the annotation to a package, class, or method @ParametersAreNonnullByDefault class FooBar {... } 52

Type qualifier validators A type qualifier can define a validator typically, a static inner class to the annotation Checks to see if a particular value is an instance of the type qualifier Static analysis tools can execute the validator at analysis time to check constant values Dynamic instrumentation could check validator at runtime 53

CreditCard example @Documented @TypeQualifier @Retention(RetentionPolicy.RUNTIME) public @interface CreditCardNumber { class Validator implements TypeQualifierValidator<CreditCardNumber> { public boolean forconstantvalue(creditcardnumber annotation, Object v) { if (v instanceof String) { String s = (String) v; if (java.util.regex.pattern.matches("[0-9]{16}", s) && LuhnVerification.checkNumber(s)) return true; } return false; }}} 54

Need a way to cast Need to provide a way to cast to a type qualifier e.g., force the analysis to assume that the result returned by this method is always @CreditCardNumber, even if it can t prove it Use when=when.assume_always? 55

Standard type qualifiers

@Syntax Used to indicate String values with particular syntaxes @Syntax( RegEx ) @Syntax( Java ) @Syntax( SQL ) Allows for error checking and used by IDE s in refactoring 57

@MatchesPattern Provides a regular expression that describes the legal String values @MatchesPattern( \\d+ ) Indicates that the allowed values are nonempty strings of digits 58

@Untainted / @Tainted Needed for security analysis Information derived directly from web form parameters is tainted can be arbitrary content Strings used to form SQL queries or HTML responses must be untainted otherwise get SQL Injection or XSS 59

Question about @Taint Is one kind of taint sufficient, or do we want to allow specification of different kinds of taint? Is HTTP request parameter taint distinct from command line taint or SQL result taint? 60

Annotations other than type qualifier

Thread/Concurrency Annotations Annotations to denote how locks are used to guard against data races Annotations about which threads should invoke which methods See annotations from Java Concurrency In Practice as a starting point 62

JCP Annotations @ThreadSafe @NotThreadSafe @Immutable @GuardedBy( this ) @GuardedBy( lock ) @GuardedBy(...) 63

What is wrong with this code? Properties getprops(file file) throws... { Properties props = new Properties(); props.load(new FileInputStream(file)); return props; } Doesn t close file 64

Resource Closure @WillNotClose this method will not close the resource @WillClose this method will close the resource @WillCloseWhenClosed Usable only in constructors and factories: constructed object decorates the parameter, and will close it when the constructed object is closed 65

Miscellaneous @CheckReturnValue @OverridingMethodsMustInvokeSuper @InjectionAnnotation 66

@CheckReturnValue Indicates a method that should always be invoked as a function, not a procedure. Example: String.toLowerCase() BigInteger.add(BigInteger val) Anywhere you have an immutable object and methods that might be thought of a a mutating method return the new value 67

@OverridingMethodsMust InvokeSuper Applied to a method, it indicates that if this method is overridden in a subclass, the overriding method should invoke the annotated methods via an invocation using super 68

@InjectionAnnotation Static analyzers get confused if there is a field or method that is accessed via reflection/ injection, and they don t understand it Many frameworks have their own annotations for injection Using @InjectionAnnotation on an annotation @X tells static analysis tools that @X denotes an injection annotation 69

JSR-305 status David Hovemeyer and I have largely implemented in FindBugs what is described here for type qualifiers (mostly Dave) still need to work on validators and type qualifiers with exclusive/exhaustive values 70