k

1,343 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,343
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

k

  1. 1. Detected Java Issues
  2. 2. Contents Articles Detected Java Issues 1 Conventions used in reported Java issue messages 8 Checkers:ANDROID.NPE 9 Checkers:ANDROID.RLK.MEDIAPLAYER 10 Checkers:ANDROID.RLK.MEDIARECORDER 11 Checkers:ANDROID.RLK.SQLCON 13 Checkers:ANDROID.RLK.SQLOBJ 15 Checkers:ANDROID.UF.BITMAP 17 Checkers:ANDROID.UF.CAMERA 18 Checkers:ANDROID.UF.MEDIAPLAYER 20 Checkers:ANDROID.UF.MEDIARECORDER 21 Checkers:CMP.CLASS 22 Checkers:CMP.OBJ 23 Checkers:CMP.STR 24 Checkers:CMPF.FLOAT 25 Checkers:COV.CMP 26 Checkers:ECC.EMPTY 27 Checkers:EHC.EQ 28 Checkers:EHC.HASH 29 Checkers:ESCMP.EMPTYSTR 30 Checkers:EXC.BROADTHROWS 31 Checkers:FIN.EMPTY 32 Checkers:FIN.NOSUPER 33 Checkers:FSC.PRT 34 Checkers:FSC.PUB 35 Checkers:FSC.PRV 36 Checkers:JD.BITCMP 37 Checkers:JD.BITMASK 38 Checkers:JD.BITR 39 Checkers:JD.CALL.WRONGSTATIC 40 Checkers:JD.CAST.COL 41 Checkers:JD.CAST.KEY 42 Checkers:JD.CAST.SUSP 43 Checkers:JD.CAST.UPCAST 44
  3. 3. Checkers:JD.CATCH 45 Checkers:JD.CONCUR 46 Checkers:JD.EQ.ARR 47 Checkers:JD.EQ.UTA 48 Checkers:JD.EQ.UTC 49 Checkers:JD.FINRET 50 Checkers:JD.IFBAD 51 Checkers:JD.IFEMPTY 52 Checkers:JD.INF.AREC 53 Checkers:JD.INST.TRUE 54 Checkers:JD.LIST.ADD 55 Checkers:JD.LOCK 56 Checkers:JD.LOCK.NOTIFY 58 Checkers:JD.LOCK.SLEEP 59 Checkers:JD.LOCK.WAIT 60 Checkers:JD.NEXT 61 Checkers:JD.OVER 63 Checkers:JD.RC.EXPR.CHECK 64 Checkers:JD.RC.EXPR.DEAD 65 Checkers:JD.ST.POS 67 Checkers:JD.SYNC.DCL 68 Checkers:JD.SYNC.IN 70 Checkers:JD.THREAD.RUN 71 Checkers:JD.UMC.FINALIZE 72 Checkers:JD.UMC.RUNFIN 73 Checkers:JD.UMC.WAIT 74 Checkers:JD.UN.MET 75 Checkers:JD.UN.PMET 76 Checkers:JD.UNCAUGHT 77 Checkers:JD.UNMOD 78 Checkers:JD.VNU 80 Checkers:JD.VNU.NULL 82 Checkers:MNA.CAP 83 Checkers:MNA.CNS 84 Checkers:MNA.SUS 85 Checkers:NPE.COND 86 Checkers:NPE.CONST 87 Checkers:NPE.RET 88
  4. 4. Checkers:NPE.RET.UTIL 90 Checkers:NPE.STAT 91 Checkers:REDUN.DEF 92 Checkers:REDUN.EQ 93 Checkers:REDUN.EQNULL 94 Checkers:REDUN.FINAL 95 Checkers:REDUN.NULL 96 Checkers:REDUN.OP 97 Checkers:RI.IGNOREDCALL 98 Checkers:RI.IGNOREDNEW 99 Checkers:RLK.AWT 100 Checkers:RLK.FIELD 102 Checkers:RLK.HIBERNATE 104 Checkers:RLK.IMAGEIO 106 Checkers:RLK.IN 107 Checkers:RLK.JNDI 109 Checkers:RLK.MAIL 111 Checkers:RLK.MICRO 112 Checkers:RLK.NIO 114 Checkers:RLK.OUT 116 Checkers:RLK.SOCK 118 Checkers:RLK.SQLCON 120 Checkers:RLK.SQLOBJ 122 Checkers:RLK.SWT 123 Checkers:RLK.ZIP 124 Checkers:RNU.THIS 125 Checkers:RR.IGNORED 126 Checkers:RTC.CALL 127 Checkers:STRCON.LOOP 129 Checkers:SV.CLEXT.CLLOADER 130 Checkers:SV.CLEXT.POLICY 131 Checkers:SV.CLLOADER 132 Checkers:SV.CLONE.SUP 133 Checkers:SV.DATA.BOUND 135 Checkers:SV.DATA.DB 136 Checkers:SV.DOS.ARRINDEX 138 Checkers:SV.DOS.ARRSIZE 140 Checkers:SV.DOS.TMPFILEDEL 142
  5. 5. Checkers:SV.DOS.TMPFILEEXIT 143 Checkers:SV.EMAIL 144 Checkers:SV.EXEC 146 Checkers:SV.EXEC.DIR 147 Checkers:SV.EXEC.ENV 148 Checkers:SV.EXPOSE.FIELD 149 Checkers:SV.EXPOSE.FIN 150 Checkers:SV.EXPOSE.IFIELD 152 Checkers:SV.EXPOSE.MUTABLEFIELD 153 Checkers:SV.EXPOSE.RET 154 Checkers:SV.EXPOSE.STORE 155 Checkers:SV.HTTP SPLIT 156 Checkers:SV.IL.DEV 158 Checkers:SV.INT OVF 160 Checkers:SV.IL.FILE 162 Checkers:SV.LDAP 163 Checkers:SV.LOG FORGING 164 Checkers:SV.PASSWD.HC.EMPTY 165 Checkers:SV.PASSWD.PLAIN 166 Checkers:SV.PATH.INJ 167 Checkers:SV.PASSWD.HC 168 Checkers:SV.PATH 169 Checkers:SV.RANDOM 171 Checkers:SV.SERIAL.INON 172 Checkers:SV.SERIAL.NON 173 Checkers:SV.SERIAL.NOREAD 174 Checkers:SV.SERIAL.NOWRITE 175 Checkers:SV.SHARED.VAR 176 Checkers:SV.SERIAL.SIG 177 Checkers:SV.SOCKETS 178 Checkers:SV.STRBUF.CLEAN 180 Checkers:SV.SQL.DBSOURCE 182 Checkers:SV.SQL 183 Checkers:SV.STRUTS.NOTRESET 185 Checkers:SV.STRUTS.NOTVALID 187 Checkers:SV.STRUTS.PRIVATE 189 Checkers:SV.STRUTS.RESETMET 190 Checkers:SV.STRUTS.STATIC 191
  6. 6. Checkers:SV.STRUTS.VALIDMET 193 Checkers:SV.TAINT 195 Checkers:SV.TAINT NATIVE 196 Checkers:SV.TMPFILE 197 Checkers:SV.UMC.EXIT 198 Checkers:SV.UMC.JDBC 200 Checkers:SV.UMC.THREADS 202 Checkers:SV.UMD.MAIN 204 Checkers:SV.USE.POLICY 206 Checkers:SV.XPATH 207 Checkers:SV.XSS.DB 208 Checkers:SV.XSS.REF 210 Checkers:SYNCH.NESTED 212 Checkers:SYNCH.NESTEDS 213 Checkers:UC.BOOLB 214 Checkers:UC.BOOLS 215 Checkers:UC.STRS 216 Checkers:UC.STRV 217 Checkers:UF.IMAGEIO 218 Checkers:UF.IN 221 Checkers:UF.JNDI 224 Checkers:UF.MAIL 227 Checkers:UF.MICRO 229 Checkers:UF.NIO 231 Checkers:UF.OUT 233 Checkers:UF.SOCK 234 Checkers:UF.SQLCON 235 Checkers:UF.SQLOBJ 237 Checkers:UF.ZIP 239 Checkers:UMC.EXIT 241 Checkers:UMC.GC 242 Checkers:UMC.SYSERR 243 Checkers:UMC.SYSOUT 244 Checkers:UMC.TOSTRING 245 Article Licenses License 246
  7. 7. Detected Java Issues 1 Detected Java Issues Note: To download all of these pages from the Wiki as a PDF, go to the book page [1]. See also: • → Conventions used in reported Java issue messages • CWE IDs mapped to Klocwork Java issue types Issue code Description CWE Mapping → ANDROID.NPE Dereference of a null value in an Android application → ANDROID.RLK.MEDIAPLAYER Media player not released on exit → Media recorder not released on exit ANDROID.RLK.MEDIARECORDER → ANDROID.RLK.SQLCON Sql connection not closed on exit → ANDROID.RLK.SQLOBJ Sql object not closed on exit → ANDROID.UF.BITMAP Usage of recycled bitmap → ANDROID.UF.CAMERA Usage of released camera → ANDROID.UF.MEDIAPLAYER Usage of released media player → ANDROID.UF.MEDIARECORDER Usage of released media recorder → CMP.CLASS Comparing by classname [2] 486 → CMP.OBJ Comparing objects with == [3] 595 → CMP.STR Comparing strings with ==" → CMPF.FLOAT Equality checks on floating point types → COV.CMP Method compareTo() should have signature 'public int compareTo(Object)' → ECC.EMPTY Empty catch clause [4] 391 → EHC.EQ Class defines hashCode() but does not define equals() [5] 581 → EHC.HASH Class defines equals() but does not define hashCode() [5] 581 → ESCMP.EMPTYSTR Inefficient empty string comparison → EXC.BROADTHROWS Method has an overly broad throws declaration [6] 396 → FIN.EMPTY Empty finalize() method [7] 568 → FIN.NOSUPER Implementation of finalize() without call to super.finalize() [7] 568 → FSC.PRT Class and its superclass have protected fields with same name → FSC.PRV Class and its superclass have private fields with same name → FSC.PUB Class and its superclass have public fields with same name → JD.BITCMP Using non short-circuit logic in expression → JD.BITMASK Possible error in bit operations → JD.BITR Redundant expression → JD.CALL.WRONGSTATIC Call to static method via instance reference → JD.CAST.COL Possible ClassCastException for collection
  8. 8. Detected Java Issues 2 → JD.CAST.KEY Suspicious key type used to retrieve element from collection → JD.CAST.SUSP Possible ClassCastException for different types → JD.CAST.UPCAST Possible ClassCastException for subtypes → JD.CATCH Catching runtime exception → JD.CONCUR Possible ConcurrentModificationException → JD.EQ.ARR Calling 'equals' on array → JD.EQ.UTA Calling 'equals' on incompatible types (array and non-array) → JD.EQ.UTC Calling equals on incompatible types → JD.FINRET Return inside finally → JD.IFBAD Redundant 'if' statement → JD.IFEMPTY Redundant 'if' statement. Unfinished code → JD.INF.AREC Apparent infinite recursion → JD.INST.TRUE Redundant 'instanceof' conditio → JD.LIST.ADD Container added to itself → JD.LOCK Lock without unlock → JD.LOCK.NOTIFY Method 'notify' called with locks held → JD.LOCK.SLEEP Method 'sleep' called with locks held → JD.LOCK.WAIT Method 'wait' called with locks held → JD.NEXT Possible 'NoSuchElementException' → JD.OVER Mismatched override → JD.RC.EXPR.CHECK Test expression is always true → JD.RC.EXPR.DEAD Redundant check causing dead code → JD.ST.POS Incorrect check for method 'indexOf' → JD.SYNC.DCL Double-checked locking → JD.SYNC.IN Inconsistent synchronization → JD.THREAD.RUN Explicit call to a 'Thread.run' method → JD.UMC.FINALIZE Explicit call to method 'Object.finalize' → JD.UMC.RUNFIN runFinalizersOnExit() is called → JD.UMC.WAIT Wait called on incorrect object → JD.UN.MET Unused non-private method → JD.UN.PMET Unused private method → JD.UNCAUGHT Uncaught exception → JD.UNMOD Modification of unmodifiable collection → JD.VNU Variable was never read after being assigned → JD.VNU.NULL Variable was never read after null being assigned → MNA.CAP Method name should start with non-capital letter → MNA.CNS Method name is same as constructor name but is not a constructor → MNA.SUS Suspicious method name → NPE.COND Null pointer dereference where null comes from condition
  9. 9. Detected Java Issues 3 → NPE.CONST Null pointer dereference where null comes from constant → NPE.RET Dereference of a null value which is returned from a method → NPE.RET.UTIL Dereference of a null value which is returned from a map or a collection → NPE.STAT Null pointer dereference of a return value (statistical) → REDUN.DEF Assignment of expression to itself → REDUN.EQ Suspicious equals() called with same expression on both sides [8] 571 → REDUN.EQNULL Suspicious equals() called with expression and null (never true) [9] 570 → REDUN.FINAL Redundant 'final' modifier → REDUN.NULL Usage of variable instead of null constant → REDUN.OP Suspicious operation with same expression on both sides → RI.IGNOREDCALL The value returned by a method called on immutable object is ignored [4] 391 → RI.IGNOREDNEW Newly created object is ignored [4] 391 → RLK.AWT AWT object not disposed on exit → RLK.FIELD Possible leak of system resource stored in a field [10] 404 → RLK.HIBERNATE Hibernate object is not closed on exit → RLK.IMAGEIO ImageIO stream is not closed on exit → RLK.IN Input stream is not closed on exit [10] 404 → RLK.JNDI JNDI context is not closed on exi → RLK.MAIL Java mail object is not closed on exit → RLK.MICRO Java Microedition connection is not closed on exit → RLK.NIO NIO object is not closed on exit → RLK.OUT Output stream is not closed on exit [10] 404 → RLK.SOCK Socket is not closed on exit → RLK.SQLCON Sql connection is not closed on exit [10] 404 → RLK.SQLOBJ Sql object is not closed on exit → RLK.SWT SWT object is not disposed on exit [10] 404 → RLK.ZIP Zip file is not closed on exit → RNU.THIS Comparison of this and null but this cannot be null [11] 476 → RR.IGNORED The returned value is ignored [4] 391 → RTC.CALL Type cast is redundant → STRCON.LOOP Using append for string in a loop → SV.CLEXT.CLLOADER Class extends 'java.lang.ClassLoader' → SV.CLEXT.POLICY Class extends 'java.security.Policy' → SV.CLLOADER Direct use of Classloader → SV.CLONE.SUP Class implements 'clone' method but does not implement Cloneable [12] 580 → SV.DATA.BOUND Untrusted Data leaks into trusted storag [13] 501
  10. 10. Detected Java Issues 4 → SV.DATA.DB Data injection [14] 79 , 89 [15] → SV.DOS.ARRINDEX Tainted index used for array access [16] 129 → SV.DOS.ARRSIZE Tainted size used for array allocation [17] 130 → SV.DOS.TMPFILEDEL Leaving temporary file for lifetime of JVM [18] 459 → SV.DOS.TMPFILEEXIT Leaving temporary file [18] 459 → SV.EMAIL Unchecked e-mail [19] 472 → SV.EXEC Process Injection [20] 77 → SV.EXEC.DIR Process Injection. Working Directory [20] 77 → SV.EXEC.ENV Process Injection. Environment Variables [21] 454 → SV.EXPOSE.FIELD Static field may be changed by malicious code [22] 493 → SV.EXPOSE.FIN Method finalize() should have protected access modifier, not public [23] 583 → SV.EXPOSE.IFIELD Instance field should be made final → SV.EXPOSE.MUTABLEFIELD Static mutable field can be accessed by malicious code → SV.EXPOSE.RET Internal representation may be exposed [24] 374 → SV.EXPOSE.STORE Method stores reference to mutable object [24] 374 → SV.HTTP_SPLIT HTTP Response Splitting [25] 113 → SV.IL.DEV Design information leakage [26] 497 → SV.IL.FILE File Name Leaking [27] 548 → SV.INT_OVF Tainted data may lead to Integer Overflow [28] 190 → SV.LDAP Unvalidated user input is used as LDAP filter → SV.LOG_FORGING Log Forging [29] 117 → SV.PASSWD.HC Hardcoded Password [30] 259 → SV.PASSWD.HC.EMPTY Empty Password [31] 25 → SV.PASSWD.PLAIN Plain-text Password [32] 555 → SV.PATH Path and file name injection [33] 73 → SV.PATH.INJ File injection [33] 73 → SV.RANDOM Use of insecure Random number generator [34] 330 → SV.SERIAL.INON Interface extends 'Serializable' → SV.SERIAL.NON Class implements 'Serializable' → SV.SERIAL.NOREAD Method readObject() should be defined for a serializable class → SV.SERIAL.NOWRITE Method writeObject() should be defined for a serializable class → SV.SERIAL.SIG Methods readObject() and writeObject() in serializable classes should have correct signature
  11. 11. Detected Java Issues 5 → SV.SHARED.VAR Unsynchronized access to static variable from servlet [35] 567 → SV.SOCKETS Bad practices: use of socket [36] 246 → SV.SQL Sql Injection [15] 89 → SV.SQL.DBSOURCE Unchecked information from the database is used in SQL statements [15] 89 → SV.STRBUF.CLEAN String buffer not cleaned → SV.STRUTS.NOTRESET Struts Forms: inconsistent reset [37] 226 → SV.STRUTS.NOTVALID Struts Forms: inconsistent validate [38] 105 → SV.STRUTS.PRIVATE Struts Forms: non-private fields → SV.STRUTS.RESETMET Struts Forms: reset method [37] 226 → SV.STRUTS.STATIC Struts Forms: static fields [39] 500 → SV.STRUTS.VALIDMET Struts Forms: validate method [40] 103 → SV.TAINT Tainted data [41] 20 → SV.TAINT_NATIVE Tainted data goes to native code [41] 20 → SV.TMPFILE Temporary file path tampering [33] 73 → SV.UMC.EXIT The System.exit() and Runtime.exit() method calls should not be used in servlets code [42] 382 → SV.UMC.JDBC Application should avoid calling DriverManager.getConnection() directly [43] 245 → SV.UMC.THREADS Bad practices: use of thread management [44] 383 → SV.UMD.MAIN Leftover debug code - main method [45] 489 → SV.USE.POLICY Direct use methods of Policy → SV.XPATH Unvalidated user input is used as an XPath expression → SV.XSS.DB Cross Site Scripting (Stored XSS) [14] 79 , 80 [46] → SV.XSS.REF Cross Site Scripting (Reflected XSS) [14] 79 , 80 [46] → SYNCH.NESTED Synchronized method calls another synchronized method with the same lock held → SYNCH.NESTEDS Synchronized static method calls another synchronized static method with the same lock held → UC.BOOLB Unnecessary creation of new Boolean object from a boolean expression → UC.BOOLS Unnecessary creation of new Boolean object from a string expression → UC.STRS Unnecessary creation of new String object from a string expression → UC.STRV Unnecessary creation of empty String object → UF.IMAGEIO Usage of closed ImageIO stream → UF.IN Usage of closed input stream → UF.JNDI Usage of closed JNDI context → UF.MAIL Usage of closed Java mail object → UF.MICRO Usage of closed Java Microedition connection
  12. 12. Detected Java Issues 6 → UF.NIO Usage of closed NIO object → UF.OUT Usage of closed output stream → UF.SOCK Usage of closed socket → UF.SQLCON Usage of closed SQL connection → UF.SQLOBJ Usage of closed SQL object → UF.ZIP Usage of closed zip file → UMC.EXIT The System.exit() and Runtime.exit() method calls should not be used in servlets code [42] 382 → UMC.GC The System.gc() method call is unwanted → UMC.SYSERR Debug print using System.err method calls is unwanted [47] 576 → UMC.SYSOUT Debug print using System.out method calls is unwanted [47] 576 → UMC.TOSTRING Unnecessary toString() method called for a String argument References [1] http:/ / www. klocwork. com/ products/ documentation/ Insight-9. 1/ Insight-9. 1:Books/ Detected_Java_Issues [2] http:/ / cwe. mitre. org/ data/ definitions/ 486. html [3] http:/ / cwe. mitre. org/ data/ definitions/ 595. html [4] http:/ / cwe. mitre. org/ data/ definitions/ 391. html [5] http:/ / cwe. mitre. org/ data/ definitions/ 581. html [6] http:/ / cwe. mitre. org/ data/ definitions/ 396. html [7] http:/ / cwe. mitre. org/ data/ definitions/ 568. html [8] http:/ / cwe. mitre. org/ data/ definitions/ 571. html [9] http:/ / cwe. mitre. org/ data/ definitions/ 570. html [10] http:/ / cwe. mitre. org/ data/ definitions/ 404. html [11] http:/ / cwe. mitre. org/ data/ definitions/ 476. html [12] http:/ / cwe. mitre. org/ data/ definitions/ 580. html [13] http:/ / cwe. mitre. org/ data/ definitions/ 501. html [14] http:/ / cwe. mitre. org/ data/ definitions/ 79. html [15] http:/ / cwe. mitre. org/ data/ definitions/ 89. html [16] http:/ / cwe. mitre. org/ data/ definitions/ 129. html [17] http:/ / cwe. mitre. org/ data/ definitions/ 130. html [18] http:/ / cwe. mitre. org/ data/ definitions/ 459. html [19] http:/ / cwe. mitre. org/ data/ definitions/ 472. html [20] http:/ / cwe. mitre. org/ data/ definitions/ 77. html [21] http:/ / cwe. mitre. org/ data/ definitions/ 454. html [22] http:/ / cwe. mitre. org/ data/ definitions/ 493. html [23] http:/ / cwe. mitre. org/ data/ definitions/ 583. html [24] http:/ / cwe. mitre. org/ data/ definitions/ 374. html [25] http:/ / cwe. mitre. org/ data/ definitions/ 113. html [26] http:/ / cwe. mitre. org/ data/ definitions/ 497. html [27] http:/ / cwe. mitre. org/ data/ definitions/ 548. html [28] http:/ / cwe. mitre. org/ data/ definitions/ 190. html [29] http:/ / cwe. mitre. org/ data/ definitions/ 117. html [30] http:/ / cwe. mitre. org/ data/ definitions/ 259. html [31] http:/ / cwe. mitre. org/ data/ definitions/ 258. html [32] http:/ / cwe. mitre. org/ data/ definitions/ 555. html [33] http:/ / cwe. mitre. org/ data/ definitions/ 73. html [34] http:/ / cwe. mitre. org/ data/ definitions/ 330. html [35] http:/ / cwe. mitre. org/ data/ definitions/ 567. html [36] http:/ / cwe. mitre. org/ data/ definitions/ 246. html [37] http:/ / cwe. mitre. org/ data/ definitions/ 226. html [38] http:/ / cwe. mitre. org/ data/ definitions/ 105. html
  13. 13. Detected Java Issues 7 [39] http:/ / cwe. mitre. org/ data/ definitions/ 500. html [40] http:/ / cwe. mitre. org/ data/ definitions/ 103. html [41] http:/ / cwe. mitre. org/ data/ definitions/ 20. html [42] http:/ / cwe. mitre. org/ data/ definitions/ 382. html [43] http:/ / cwe. mitre. org/ data/ definitions/ 245. html [44] http:/ / cwe. mitre. org/ data/ definitions/ 383. html [45] http:/ / cwe. mitre. org/ data/ definitions/ 489. html [46] http:/ / cwe. mitre. org/ data/ definitions/ 80. html [47] http:/ / cwe. mitre. org/ data/ definitions/ 576. html
  14. 14. Conventions used in reported Java issue messages 8 Conventions used in reported Java issue messages In the message or "output" of a detected Java issue: • the string "someMethodName().$RET" means the value that was returned by someMethodName(). • the string "someMethodName().$N", where N can be 1, 2, 3 (and so on), means the first, second, third (and so on) parameter of the someMethodName() call. See also: • → Detected Java Issues • Fixing issues before they enter the code stream • Investigating issues in your integration build
  15. 15. Checkers:ANDROID.NPE 9 Checkers:ANDROID.NPE A NullPointerException is thrown in case of an attempt to dereference a null value. The dereference may be a function call, a read or write of a field, or an array access. An ANDROID.NPE error is reported for Android [1] -specific null pointer dereference situations. Example 1 17 protected void onCreate(Bundle bundle) { 18 super.onCreate(bundle); 19 setContentView(R.layout.note_layout); 20 final ImageView image = (ImageView) findViewById(R.id.image); 21 22 final String title = bundle.getString(TITLE); 23 setTitle(title); 24 } ANDROID.NPE is reported for line 22 since 'bundle' might be null in the 'onCreate()' method due to the contract. See also • → NPE.CONST • → NPE.RET • → NPE.RET.UTIL • → NPE.STAT Language: English References [1] http:/ / code. google. com/ android
  16. 16. Checkers:ANDROID.RLK.MEDIAPLAYER 10 Checkers:ANDROID.RLK.MEDIAPLAYER RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.MEDIAPLAYER warning indicates that a MediaPlayer that was opened is not explicitly closed. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 19 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 20 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 21 final MediaPlayer player = MediaPlayer.create(this, ringtoneUri); 22 player.start(); 23 24 } 25 return super.onKeyDown(keyCode, event); 26 } ANDROID.RLK.CAMERA is reported for the snippet on line 25: 'player' is not released on exit. Language: English
  17. 17. Checkers:ANDROID.RLK.MEDIARECORDER 11 Checkers:ANDROID.RLK. MEDIARECORDER RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.MEDIARECORDER warning indicates that a MediaRecorder that was opened is not explicitly released. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 20 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 21 if (keyCode == KeyEvent.KEYCODE_ENTER) { 22 MediaRecorder recorder = new MediaRecorder(); 23 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 24 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 25 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 26 recorder.setOutputFile(PATH_NAME); 27 recorder.prepare(); 28 recorder.start(); // Recording is now started 29 recorder.stop(); 30 recorder.reset(); // You can reuse the object by going back to setAudioSource() step 31 recorder.release(); 32 return true; 33 } 34 return super.onKeyDown(keyCode, event); 35 } ANDROID.RLK.MEDIARECORDER is reported for the snippet on line 22: 'recorder' will not be released on exit if 'setAudioSource(...)' throws java.lang.IllegalStateException (line 23).
  18. 18. Checkers:ANDROID.RLK.MEDIARECORDER 12 Example 2 20 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 21 if (keyCode == KeyEvent.KEYCODE_ENTER) { 22 MediaRecorder recorder = new MediaRecorder(); 23 try { 24 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 25 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 26 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 27 recorder.setOutputFile(PATH_NAME); 28 recorder.prepare(); 29 recorder.start(); // Recording is now started 30 recorder.stop(); 31 recorder.reset(); // You can reuse the object by going back to setAudioSource() step 32 } finally { 33 recorder.release(); 34 } 35 return true; 36 } 37 return super.onKeyDown(keyCode, event); 38 } The snippet from the previous section is fixed; ANDROID.RLK.MEDIARECORDER is not reported here. Language: English
  19. 19. Checkers:ANDROID.RLK.SQLCON 13 Checkers:ANDROID.RLK.SQLCON RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. ANDROID.RLK.SQLCON indicates that an Sql connection is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 30 protected void onCreate(Bundle bundle) { 31 super.onCreate(bundle); 32 final SQLiteDatabase database = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); 33 final Cursor query = database.query(DATABASE_TABLE, 34 new String[]{KEY_FILE, KEY_DATE, KEY_COMMENT}, 35 null, 36 null, 37 null, 38 null, 39 KEY_DATE + " asc"); 40 startManagingCursor(query); 41 42 ListAdapter adapter = new SimpleCursorAdapter(this, 43 android.R.layout.simple_list_item_1, 44 query, 45 new String[]{Contacts.People.NAME}, 46 new int[]{android.R.id.text1}); 47 setListAdapter(adapter); 48 } ANDROID.RLK.SQLCON is reported for the snippet on line 32: connection 'database' is not closed on exit.
  20. 20. Checkers:ANDROID.RLK.SQLCON 14 See also • → ANDROID.RLK.SQLOBJ Language: English
  21. 21. Checkers:ANDROID.RLK.SQLOBJ 15 Checkers:ANDROID.RLK.SQLOBJ RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. An ANDROID.RLK.SQLOBJ warning indicates that an SQLite API object (other than an SQL connection) is not closed on exit. Vulnerability and risk Resources such as streams, connections and graphic objects must be explicitly closed. The close operation can unblock transactions or flush file changes in the file system. While a resource will eventually be closed by the garbage collector, resource exhaustion can occur before garbage collection starts. Depending on the nature of the resource, various exceptions will be thrown on a failed attempt to allocate another resource, for example: java.io.FileNotFoundException: Too many open files or too many database connections. Mitigation and prevention Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors. Example 1 41 protected void onCreate(Bundle bundle) { 42 super.onCreate(bundle); 43 database = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null); 44 45 if (bundle != null) { 46 final String[] queryClauseArray = bundle.getStringArray(KEY_QUERY); 47 if (queryClauseArray != null) { 48 for (final String queryClause : queryClauseArray) { 49 final Cursor query = database.query(DATABASE_TABLE, 50 new String[]{KEY_FILE, KEY_DATE, KEY_COMMENT}, 51 null, 52 null, 53 null, 54 null, 55 queryClause); 56 files.add(query.getString(0)); 57 dates.add(query.getString(1)); 58 comments.add(query.getString(2)); 59 60 } 61 } 62 }
  22. 22. Checkers:ANDROID.RLK.SQLOBJ 16 63 } ANDROID.RLK.SQLOBJ is reported for the snippet on line 49: database cursor 'query' is not closed on exit. See also • → ANDROID.RLK.SQLCON Language: English
  23. 23. Checkers:ANDROID.UF.BITMAP 17 Checkers:ANDROID.UF.BITMAP UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.BITMAP warning indicates an attempt to get pixel(s) from a Bitmap or set pixel(s) into a Bitmap after it was recycled. Example 1 19 public void addWatermark(final byte[] data) { 20 final Bitmap bmp = loadBitmap(data); 21 if (bmp != null) { 22 final int width = bmp.getWidth(); 23 for (int i = 0; i < width; i++) { 24 bmp.setPixel(i, i, Color.argb(255, 0, 0, 0)); 25 } 26 } 27 } 28 29 private Bitmap loadBitmap(byte[] data) { 30 final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length); 31 if (bmp == null) { 32 Log.d(TAG, "Was not able to decode an image"); 33 } 34 35 final int width = bmp.getWidth(); 36 final int height = bmp.getHeight(); 37 if (width <= 3 || height <= 3 ) { 38 bmp.recycle(); 39 } 40 return bmp; 41 } ANDROID.UF.BITMAP is reported for the snippet on line 24 since method 'loadBitmap()' recycles the bitmap if one of its dimensions is less than '3' (line 38). Language: English
  24. 24. Checkers:ANDROID.UF.CAMERA 18 Checkers:ANDROID.UF.CAMERA UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.CAMERA warning indicates an attempt to use Camera after it was released. Example 1 21 private Camera camera; 22 23 private void initCamera() { 24 camera = Camera.open(); 25 } 26 27 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 28 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 29 if (camera != null) { 30 final CameraPictureCallbackImpl callback = new CameraPictureCallbackImpl(); 31 camera.takePicture(null, null, callback); 32 } 33 return true; 34 } 35 return super.onKeyDown(keyCode, event); 36 } 37 38 private class CameraPictureCallbackImpl implements Camera.PictureCallback { 39 private Bitmap bitmap; 40 41 public void onPictureTaken(final byte[] bytes, final Camera camera) { 42 camera.stopPreview(); 43 camera.release(); 44 bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 45 if (bitmap == null) { 46 camera.startPreview(); 47 } 48 } 49 50 public Bitmap getBitmap() { 51 return bitmap; 52 } 53 } ANDROID.UF.CAMERA is reported for the snippet on line 46 since callback method 'onPictureTaken(...)' starts the camera preview even if the camera was released on line 43.
  25. 25. Checkers:ANDROID.UF.CAMERA 19 Language: English
  26. 26. Checkers:ANDROID.UF.MEDIAPLAYER 20 Checkers:ANDROID.UF.MEDIAPLAYER UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.MEDIAPLAYER warning indicates an attempt to use MediaPlayer after it was released. Example 1 26 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 27 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 28 MediaPlayer mp = new MediaPlayer(); 29 try { 30 mp.setDataSource(PATH_TO_FILE); 31 mp.prepare(); 32 } catch (IOException e) { 33 mp.release(); 34 } 35 mp.start(); 36 mp.release(); 37 return true; 38 } 39 return super.onKeyDown(keyCode, event); 40 } ANDROID.UF.MEDIAPLAYER is reported for the snippet on line 35 since there is an attempt to use the 'mp' that is released in case of IOException on line 33. Language: English
  27. 27. Checkers:ANDROID.UF.MEDIARECORDER 21 Checkers:ANDROID.UF.MEDIARECORDER UF (Use Freed) issues are reported when there is an attempt to use resources after they were released. The ANDROID.UF.MEDIARECORDER warning indicates an attempt to use MediaRecorder after it was released. Example 1 15 public boolean onKeyDown(final int keyCode, final KeyEvent event) { 16 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 17 MediaRecorder mRecorder = new MediaRecorder(); 18 19 mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 20 mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 21 mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 22 23 final File file = new File("test.raw"); 24 if (file.exists()) { 25 mRecorder.release(); 26 } else { 27 mRecorder.setOutputFile(file.getPath()); 28 } 29 30 mRecorder.start(); 31 mRecorder.release(); 32 return true; 33 } 34 return super.onKeyDown(keyCode, event); 35 } ANDROID.UF.MEDIARECORDER is reported for the snippet on line 30 since there is an attempt to use the 'mRecorder' that is released if the output file exists (line 25). Language: English
  28. 28. Checkers:CMP.CLASS 22 Checkers:CMP.CLASS This error appears when the program attempts to compare two objects' classnames to see whether they are the same. It can also appear if an object has a certain class using other means than a currently loaded class or via the classloader itself. Vulnerability and risk When comparing classes by name, you allow for mix-and-match attacks, where an attacker constructs new code that links some of your code together with malicious classes or links two classes together that were not meant to be together. Mitigation and prevention Do not use an object's equals method to find classnames. Instead, retrieve the first object's class with getClass method, then retrieve the second object's class by means of the current classloader. Example 1 10 public void privateMethod(Object object1, Object object2) { 11 if (object1.getClass().getName().equals("anotherClass")) {// wrong 12 // do work based on the assumption we're dealing with 13 // the right object 14 } 15 if (object1.getClass() == object2.getClass()) { // correct 16 // do work based on the fact that the objects are the 17 // of the same class 18 } 19 } CMP.CLASS is reported for line 11: Comparing by classname. Security Guidelines • CWE-486: Comparison of Classes by Name [2] Language: English
  29. 29. Checkers:CMP.OBJ 23 Checkers:CMP.OBJ This warning appears if object references are compared rather than the objects themselves. An error is reported only if the compared objects have different types, and none of them has the explicit Object type. Vulnerability and risk This problem can cause unexpected application behavior. Comparing objects using == usually produces deceptive results, since the == operator compares object references rather than their values. To use == on a string, the programmer has to make sure that these objects are unique in the program, that is, that they don't have the equals method defined, or they have a static factory that produces unique objects. Mitigation and prevention Use the equals() method to compare objects instead of the == operator. If using ==, it is important for performance reasons that your objects are created by a static factory, not by a constructor. Example 1 9 /** 10 * Check that person is John 25 miner 11 */ 12 Proffesional john = new Proffesional("John", 25, "miner"); 13 public boolean checkJohn(Person p) { 14 return p == john; 15 } CMP.OBJ is reported for line 14: Comparing objects 'p' and 'john' with == Security Guidelines • CWE-595: Comparison of Object References Instead of Object Contents [3] Language: English
  30. 30. Checkers:CMP.STR 24 Checkers:CMP.STR This warning appears if string references are compared rather than strings themselves for String type. Vulnerability and risk This problem can cause unexpected application behavior. Comparing objects using == usually produces deceptive results, since the == operator compares object references rather than values. To use == on a string, the programmer has to make sure that these are constant strings, statically created in the same class or "interned" prior to comparison using the intern() method. Mitigation and prevention Use the equals() method to compare objects instead of the == operator. Example 1 10 /** 11 * Return symbolic name of operation 12 */ 13 public String nameOperation(String key) { 14 if (key == "++") return "PLUS"; 15 if (key == "--") return "MINUS"; 16 return "UNKNOWN"; 17 } CMP.STR is reported for line 14: Comparing strings 'key' and '++' with ==CMP.STR is reported for line 15: Comparing strings 'key' and '--' with == Language: English
  31. 31. Checkers:CMPF.FLOAT 25 Checkers:CMPF.FLOAT Error printed when two float or double value compared using equals operator (==). Vulnerability and risk Avoid equality checks on floating point types because of possible inaccuracy of floating point calculations. The example below can lead to an infinite loop because x1 + 700 times ((x2 - x1) / 700) does not equal to x2, due to inaccuracy. Mitigation and prevention Use check great or equals, less or equals or abs different less than something, for example (Math.abs(x1-x2) < MIN_DIFF). Example 1 9 /** 10 * Calculates define integral 11 */ 12 public static double integral(MyFunction f, double x1, 13 double x2) { 14 double x = x1; 15 double result = 0; 16 double step = (x2 - x1) / 700; 17 while (x != x2) { // should use (x <= x2) 18 result = result + f.valueFor(x) * step; 19 x = x + step; 20 } 21 return result; 22 } CMPF.FLOAT is reported for line 17: Equality checks on floating point types should be avoided Language: English
  32. 32. Checkers:COV.CMP 26 Checkers:COV.CMP Error exists when method compareTo declared with signature different than int compareTo(Object). Vulnerability and risk Intent was probably to implement interface method of Comparable interface, but since this method has different signature it is not same method and will not be called when comparator is used. Mitigation and prevention Declare that class implements Comparable, declare int compareTo(Object) method. Example 1 14 String name; 15 int compareTo(MyClass a) { 16 return name.compareTo(a.name); 17 } COV.CMP is reported for line 15: Method compareTo(..) should have signature 'public int compareTo(Object)' Language: English
  33. 33. Checkers:ECC.EMPTY 27 Checkers:ECC.EMPTY An Empty Catch Clause (ECC.EMPTY) warning appears if nothing is written in a catch block. If you catch an exception, it would be better to process it rather than to ignore it. Example 1 12 public void openFile(String name) { 13 try { 14 FileInputStream is = new FileInputStream(name); 15 // read file ... 16 } catch (FileNotFoundException e) { 17 // TODO Auto-generated catch block 18 } 19 } ECC.EMPTY is reported for line 16: Empty catch clause Security Guidelines • CWE-391: Unchecked Error Condition [4] Language: English
  34. 34. Checkers:EHC.EQ 28 Checkers:EHC.EQ The EHC Class should implement both equals(Object) and hashCode() methods. EHC warnings appear if an equals() method was specified without a hashCode() method, or vice versa. This warning appears if a hashCode() is specified without an equals(). This may cause a problem with some collections that expect equal objects to have equal hashcodes. Example 1 8 public class EHC_EQ_Sample_1 { 9 private int seed; 10 public EHC_EQ_Sample_1(int seed) { 11 this.seed = seed; 12 } 13 public int hashCode() { 14 return seed; 15 } 16 // no equals(Object o) method defined 17 } EHC.EQ is reported for class declaration on line 8: Class defines hashCode() but does not define equals(). Security Guidelines • CWE-581: Object Model Violation: Just One of Equals and Hashcode Defined [5] See also • → EHC.HASH Language: English
  35. 35. Checkers:EHC.HASH 29 Checkers:EHC.HASH The EHC Class should implement both equals(Object) and hashCode() methods. EHC warnings appear if an equals() method was specified without a hashCode() method, or vice versa. This may cause a problem with some collections that expect equal objects to have equal hashcodes. Example 1 8 public class EHC_HASH_Sample_1 { 9 private int seed; 10 public EHC_HASH_Sample_1(int seed) { 11 this.seed = seed; 12 } 13 public boolean equals(Object o) { 14 return (o instanceof EHC_HASH_Sample_1) 15 && ((EHC_HASH_Sample_1) o).seed == seed; 16 } 17 // no hashCode method defined 18 } EHC.HASH is reported for class declaration on line 8: Class defines equals() but does not define hashCode(). Security Guidelines • CWE-581: Object Model Violation: Just One of Equals and Hashcode Defined [5] See also • → EHC.EQ Language: English
  36. 36. Checkers:ESCMP.EMPTYSTR 30 Checkers:ESCMP.EMPTYSTR ESCMP Compare string with an empty string using equals(). It is not necessary to call equals() to compare a string with an empty string. s.length() works twice as fast. The following expressions: s.equals("") or "".equals(s) can be easily replaced with (s.length() == 0) and (s != null && s.length() == 0) Performance measurements (done using Java 2 Runtime Environment, Standard Edition, build 1.4.1_02-b06) showed that code with "equals" executed in 147 units of time while the same code with "length" executed in 71 units of time. Example 1 9 public boolean emptyCheck1(String s) { 10 if (s.equals("")) return true; 11 return false; 12 } 13 public boolean emptyCheck2(String s) { 14 if ("".equals(s)) return true; 15 return false; 16 } 17 // fixed code 18 public boolean emptyCheck3(String s) { 19 if (s.length() == 0) return true; 20 return false; 21 } ESCMP.EMPTYSTR is reported for line 10: Comparing strings 's' and "" using equals(), instead of length() == 0ESCMP.EMPTYSTR is reported for line 14: Comparing strings "" and 's' using equals(), instead of length() == 0 Language: English
  37. 37. Checkers:EXC.BROADTHROWS 31 Checkers:EXC.BROADTHROWS A method should throw exceptions appropriate to the abstraction level. When a method throws exceptions that are too general, like Exception and Throwable, it is difficult for callers to handle errors correctly and do appropriate error recovery. Vulnerability and risk When method throws exceptions that are too general, callers have to investigate what kind of problem happened so that they can handle it appropriately. Also, when a method code is changed and a new kind of exception is introduced, it's harder to force all callers to handle it properly. Mitigation and prevention A method should throw exceptions appropriate to the abstraction level. When necessary, low-level exceptions can be wrapped with higher-level exceptions. Example 1 15 public void processFile(String fileName) throws Exception { 16 InputStream is = new FileInputStream(fileName); 17 // do something 18 } 19 public int calculateSum(Collection data) throws Throwable { 20 int sum = 0; 21 for (Iterator it = data.iterator(); it.hasNext();) { 22 String element = (String) it.next(); 23 int i = Integer.parseInt(element); 24 sum += i; 25 } 26 return sum; 27 } EXC.BROADTHROWS is reported for method 'processFile' declaration on line 15: The 'processFile' method throws a generic exception 'java.lang.Exception'. EXC.BROADTHROWS is reported for method 'calculateSum' declaration on line 19: The 'calculateSum' method throws a generic exception 'java.lang.Throwable'. Security Guidelines • CWE-396: Declaration of Catch for Generic Exception [6] Language: English
  38. 38. Checkers:FIN.EMPTY 32 Checkers:FIN.EMPTY Empty finalize() method. FIN.* code problems have a questionable implementation of the finalize method(). In this case, there is an empty finalize() method. Example 1 11 public void test3() { 12 new FIN_EMPTY_Sample_1() { 13 protected void finalize() throws Throwable { 14 15 } 16 }; 17 } 18 // fixed code 19 public void test1() { 20 new FIN_EMPTY_Sample_1() { 21 }; 22 } FIN.EMPTY is reported for line 13: Empty finalize() method should be removed. Security Guidelines • CWE-568: finalize() Method Without super.finalize() [7] Language: English
  39. 39. Checkers:FIN.NOSUPER 33 Checkers:FIN.NOSUPER Implementation of the finalize() method should call super.finalize(). FIN.* code problems report on questionable implementations of the finalize method(). In this case there is a finalize() method implementation that does not call super.finalize(). Vulnerability and risk If a superclass implementor overrides a superclass finalizer but forgets to invoke the superclass finalizer manually, the superclass finalizer will never be invoked. This means resource cleanup for the superclass will never be performed, leading to resource leaks. Example 1 8 public class FIN_NOSUPER_Sample_1 { 9 /* 10 * no super.finalize() was called 11 */ 12 public void finalize() { 13 System.err.println("finalized"); 14 } 15 } FIN.NOSUPER is reported for 'finalize' method declaration on line 12: Implementation of the finalize() method should call super.finalize(). Security Guidelines • CWE-568: finalize() Method Without super.finalize() [7] Language: English
  40. 40. Checkers:FSC.PRT 34 Checkers:FSC.PRT This warning is reported for protected fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 protected int index; 15 // ... 16 } FSC.PRT is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRT_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRT_Sample_1$SuperClass' by declaring a protected or package-private field with the same name 4 Language: English
  41. 41. Checkers:FSC.PUB 35 Checkers:FSC.PUB This warning is reported for public fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 public int index; 15 // ... 16 } FSC.PUB is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PUB_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PUB_Sample_1$SuperClass' by declaring a public field with the same name Language: English
  42. 42. Checkers:FSC.PRV 36 Checkers:FSC.PRV This warning is reported for private fields. It appears if some field in a subclass shadows (has the same name, type and modifier) as some field in the superclass. This can cause confusion. Example 1 9 public class SuperClass { 10 protected int index; 11 // ... 12 } 13 public class SubClass extends SuperClass { 14 private int index; 15 // ... 16 } FSC.PRV is reported for field declaration on line 14: Class 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRV_Sample_1$SubClass' hides field 'index' of superclass 'com.klocwork.jdefects.checkers.ast.samples.FSC_PRV_Sample_1$SuperClass' by declaring a private field with the same name Language: English
  43. 43. Checkers:JD.BITCMP 37 Checkers:JD.BITCMP JD.BITCMP happens when an if check contains binary such as & or | instead of short-circuit, such as && or ||. It is better to use short-circuit operation for performance. Also, if you use binary, both sides of the expression are evaluated, and this can cause other unexpected problems, such as a null pointer exception being thrown. as in the example below. Vulnerability and risk A JD.BITCMP defect can cause a performance impact or unexpected behavior, such as a RuntimeException being thrown. Mitigation and prevention Replace bit operation with short-circuit operation. Example 1 10 static void check(int arr[]) { 11 if (arr!=null & arr.length!=0) { 12 foo(); 13 } 14 return; 15 } JD.BITCMP is reported for line 11: Questionable use of bit operation '&' in expression. Did you mean '&&'? See also • → JD.BITMASK • → JD.BITR Language: English
  44. 44. Checkers:JD.BITMASK 38 Checkers:JD.BITMASK JD.BITMASK happens when int or a long variable is used with bit operation & or | and is then compared to a constant, while the result of the evaluation is known in advance. For example ((a & 0x0f) == 0xf0) is always false because bitmasks are incompatible. Vulnerability and risk It is unlikely that the code was intentional, so the error can cause unexpected behavior. Mitigation and prevention Fix the bit operator (if it was the cause), or fix the bitmask. Example 1 10 final static int FLAG = 0x01; 11 static boolean checkMask(int a) { 12 // mistyped, should be & 13 if ((a | FLAG) == 0) return true; 14 return false; 15 } JD.BITMASK is reported for line 13: Incompatible bitmasks 'a | FLAG' and '0' cause the expression to always be 'false'. See also • → JD.BITCMP • → JD.BITR Language: English
  45. 45. Checkers:JD.BITR 39 Checkers:JD.BITR JD.BITR happens when an if check contains only constants on both sides. It can be the result of a programming error followed by compiler optimization which replaces expressions with constants. As a sub-case, this checker will trigger accidental assignments in conditions such as those in the example below. Note: Whether or not this error occurs depends on how the Java compiler optimizes the code. For some compilers, JD.BITR never occurs and either JD.RC.EXPR.DEAD or JD.RC.EXPR.CHECK occurs instead. Vulnerability and risk A statically evaluatable expression in an 'if' statement is most likely an error in logic. Mitigation and prevention Fix the 'if' statement. Example 1 10 static void check(boolean hasFields) { 11 if (hasFields = true) { 12 foo(); 13 } 14 return; 15 } JD.BITR is reported for lline 11: Expression 'hasFields = true' is always 'true'. Is there a typo? See also • → JD.BITCMP • → JD.BITMASK • → JD.RC.EXPR.CHECK • → JD.RC.EXPR.DEAD Language: English
  46. 46. Checkers:JD.CALL.WRONGSTATIC 40 Checkers:JD.CALL.WRONGSTATIC JD.CALL.WRONGSTATIC appears when a static method is called by means of instance reference. Vulnerability and risk Calling of a static method by means of an instance reference is a bad coding practice, and it can cause incorrect behavior. For example, if static method interrupted() is called by means of an instance reference, then the returned state would be the state of the current Thread, not the state of the given instance. If you wants to get the state of the instance, use a non-static call isInterrupted(). Mitigation and prevention Do not call static methods by means of instance references. Example 1 9 void run(final Thread thread) throws Throwable{ 10 thread.interrupted(); 11 } JD.CALL.WRONGSTATIC is reported for line 10: Call to static method 'java.lang.Thread.interrupted' via instance reference. Language: English
  47. 47. Checkers:JD.CAST.COL 41 Checkers:JD.CAST.COL JD.CAST.COL is found when an object is retrieved from a collection (map or list) and is cast immediately as type A, although it was put into the collection as type B, where types A and B are unrelated. That is, Klocwork cannot find that A is a subtype of B or B is a subtype of A. The JD.CAST.COL checker checks only class fields. Vulnerability and risk This usually causes a ClassCastException, because objects in the collection have different types. Mitigation and prevention Choose which type you actually want to use--A or B--and, either put objects of type A, or get objects of type B. The other option is to allow both of these types to use an instanceof check before casting the object. Example 1 10 public class JD_CAST_COL_Sample_1 { 11 HashMap test; 12 void foo(){ 13 test.put("a","b"); 14 JD_CAST_COL_Sample_1 res =(JD_CAST_COL_Sample_1)test.get("a"); 15 } 16 } JD.CAST.COL is reported for line 14: Suspicious cast to 'com.klocwork.jdefects.checkers.ast.samples.JD_CAST_COL_Sample_1' of collection element. Object was put into the collection as 'java.lang.String'.-> 13: test.put(a, b)-> 14: (JD_CAST_COL_Sample_1)test.get(a) See also • → JD.CAST.UPCAST • → JD.CATCH Language: English
  48. 48. Checkers:JD.CAST.KEY 42 Checkers:JD.CAST.KEY JD.CAST.KEY is reported when the type of key used to retrieve a collection element differs from the type of key used to put the object into the collection. Vulnerability and risk The expected element will not be found in the collection, since no elements were put into the collection with a key of this type. Mitigation and prevention Check if the collection is expected to contain keys of different types. Check if the key used to retrieve an element from the collection is of the correct type. Example 1 11 public class JD_CAST_KEY_Sample_1 { 12 13 HashMap len=new HashMap(); 14 15 void fill(File dir){ 16 File[] list = dir.listFiles(); 17 for (int i = 0; i < list.length; i++) { 18 File file = list[i]; 19 len.put(file, new Long(file.length())); 20 } 21 } 22 23 int getLength(String file){ 24 Long l = (Long) len.get(file); 25 if (l!=null) return l.intValue(); 26 return 0; 27 } 28 } JD.CAST.KEY is reported for call to 'len.get(file)' on line 24: Suspicious key of type 'java.lang.String' used to retrieve a collection element. Object was put into the collection with key of type 'java.io.File'. See also • → JD.CAST.COL Language: English
  49. 49. Checkers:JD.CAST.SUSP 43 Checkers:JD.CAST.SUSP JD.CAST.SUSP is triggered when an object is checked with an instance of operator for type A and than cast to type B, where types A and B are unrelated. (That is Klocwork cannot find that A is a subtype of B or B is a subtype of A.) Vulnerability and risk This is usually an error, because cast is not safe; the object can actually be another type than B. In some cases, this error can produce false positives when the path from instanceof to cast is incompatible. Mitigation and prevention Choose which type you actually want to use--A or B--and either change the typecast to A, or check the instanceof to B. Example 1 10 void setValue(Object a, Object value) { 11 if (a instanceof String) { 12 StringBuffer b = (StringBuffer) a; 13 b.append("="); 14 b.append(value); 15 } 16 } JD.CAST.SUSP is reported for cast on line 12: Suspicious cast of 'a' from 'String' to 'StringBuffer', where types are unrelated.-> 11: a instanceof String-> 12: (StringBuffer)a See also • → JD.CAST.UPCAST Language: English
  50. 50. Checkers:JD.CAST.UPCAST 44 Checkers:JD.CAST.UPCAST JD.CAST.UPCAST is triggered when an object is checked with an instance of operator for type A and than cast to type B, where B is a subtype of type A. Vulnerability and risk This is usually an error, because the cast is not safe, the object can actually be another subtype of A. In some cases, this error can produce false positives when the path from the instanceof to the cast is incompatible. Example 1 14 void setValue(Object a, Object value) { 15 if (a instanceof Map) { 16 HashMap b = (HashMap) a; 17 b.put(value, ""); 18 } else if (a instanceof List) { 19 List b = (List) a; 20 b.add(value); 21 } 22 } JD.CAST.UPCAST: Suspicious cast of 'a' to 'HashMap', where 'HashMap' is a subtype of 'Map'. This object can hold other subtypes of 'Map' which can cause a ClassCastException.-> 15: a instanceof Map-> 16: (HashMap)a See also • → JD.CAST.SUSP Language: English
  51. 51. Checkers:JD.CATCH 45 Checkers:JD.CATCH Klocwork reports a JD.CATCH issue when it finds a catch block with an unwanted exception such as java.lang.NullPointerException. A list of possible exceptions is in the Parameters section. Vulnerability and risk Exceptions, as their names implies, should be used only for exceptional conditions; they should never be used for ordinary control flow. Using exceptions for control flow dramatically reduces performance, maintainability, and readability of the code. Mitigation and prevention Change the code to code that does a preventive check (full null, array index, and so on). Example 1 9 String test1(String my) { 10 try { 11 return my.substring(1,4); 12 } catch (NullPointerException e) { 13 return ""; 14 } 15 } JD.CATCH is reported on line 12: Catching 'java.lang.NullPointerException' explicitly is usually a bad practice. Use preventive checks on data instead. Language: English
  52. 52. Checkers:JD.CONCUR 46 Checkers:JD.CONCUR JD.CONCUR is found when an iterator is created for collection A, then something is removed from the collection, but the loop is not stopped. For more information see ConcurrentModificationException [1] Vulnerability and risk On the following invocation of the "next" method, the code will throw a ConcurrentModificationException. Mitigation and prevention An object under iteration cannot be modified. Elements for removal have to be stored in another collection and removed later, or the collection can be cloned and the iterator used on the cloned version. Example 1 12 void fixList(Collection col) { 13 for (Iterator iter = col.iterator(); iter.hasNext();) { 14 String el = (String) iter.next(); 15 if (el.startsWith("/")) { 16 col.remove(el); 17 } 18 } 19 } JD.CONCUR is reported for line 14: Possible 'ConcurrentModificationException' can be thrown by method 'iter.next()' while iterating over 'col'. You cannot remove a collection element while iterating over the same collection. Language: English References [1] http:/ / java. sun. com/ j2se/ 1. 5. 0/ docs/ api/ java/ util/ ConcurrentModificationException. html
  53. 53. Checkers:JD.EQ.ARR 47 Checkers:JD.EQ.ARR JD.EQ.ARR is reported when two arrays are compared through an equals() method. Vulnerability and risk Method equals() called on array operates the same as a '==' operator, comparing references, not the array itself. It is most likely an error; a deep array comparison is required. Mitigation and prevention Either change this method invocation to an invocation of a deep array comparison Arrays.equals(arr1,arr2) or use a direct reference comparison arr1==arr2 (but only if the objects are exactly the same.) Example 1 9 static class MyClass { 10 String names[]; 11 public boolean equals(Object o) { 12 if (!(o instanceof MyClass)) 13 return false; 14 MyClass m = (MyClass)o; 15 return this.names.equals(m.names); 16 } 17 } JD.EQ.ARR is reported for 'equals' call on line 15: Comparison of arrays using the 'equals' method. For arrays, 'equals' compares the identities of the two arrays - not the values of the array contents. See also • → JD.EQ.UTA • → JD.EQ.UTC Language: English
  54. 54. Checkers:JD.EQ.UTA 48 Checkers:JD.EQ.UTA JD.EQ.UTA is found when there is a comparison of array and non-array types through the equals method. Vulnerability and risk This call always returns false, meaning that the program contains an error which can cause incorrect behavior. Mitigation and prevention Fix arguments of equals methods. Most likely, the comparison should be with an array element. Example 1 9 public boolean checkNames(String[] ids) { 10 if (ids.equals("")) return false; 11 // ... 12 return true; 13 } JD.EQ.UTA is reported for line 10: Comparing an array with a non-array type always returns false. See also • → JD.EQ.UTC • → JD.EQ.ARR Language: English
  55. 55. Checkers:JD.EQ.UTC 49 Checkers:JD.EQ.UTC JD.EQ.UTC is found when objects of incompatible types are compared through the equals method. Object types are considered to be incompatible if they don't have any class or interface in common. Vulnerability and risk Most likely an error. For example, a comparison of String and File objects, was probably meant to be file.getPath().equals(""). Mitigation and prevention Fix the equals argument to make it type compatible. It probably needs additional function calls to retrieve an object of the correct type for comparison. Example 1 11 public boolean checkFile(File file) { 12 if (file==null || file.equals("")) return false; 13 // ... 14 return true; 15 } JD.EQ.UTC is reported for 'equals' call on line 12: Calling equals on incompatible types 'java.io.File' and 'java.lang.String'. See also • → JD.EQ.UTA • → JD.EQ.ARR Language: English
  56. 56. Checkers:JD.FINRET 50 Checkers:JD.FINRET JD.FINRET is found when a return statement occurs in a finally block. Vulnerability and risk A return statement inside a finally block will cause any exception that might be thrown in the try block to be discarded and any value that was originally intended to be returned by the method to be replaced with the value returned in the finally block. Mitigation and prevention A finally block should contain only finalization code. Any logic about return values and re-throwing expectations should not be in a finally block. Example 1 9 int foo2(String name) { 10 try { 11 return Integer.parseInt(name); 12 } catch (NumberFormatException e) { 13 throw e; 14 } finally { 15 return -1; 16 } 17 } JD.FINRET is reported on line 15: A 'return' in a finally block can cause exceptions to be ignored. Language: English
  57. 57. Checkers:JD.IFBAD 51 Checkers:JD.IFBAD JD.IFBAD happens when an 'if' statement has only an empty 'then' branch. Possible misplaced ";". Vulnerability and risk Usually JD.IFBAD represents a logical error in the code. When there is a misplaced semicolon, the following statement is assumed to be executed only on condition but, in fact, is always executed. In less severe cases, it is just left-over code and should be removed for efficiency. Mitigation and prevention Change the code so that the 'if' contains a non-empty branch or remove the 'if' altogether. Example 1 9 private void foo(boolean debug) { 10 // ... 11 if (debug); { // print something 12 System.err.println("Enter foo"); 13 } 14 } JD.IFBAD is reported for line 11: Redundant 'if' statement. The cause is probably a misplaced semicolon. See also • → JD.IFEMPTY Language: English
  58. 58. Checkers:JD.IFEMPTY 52 Checkers:JD.IFEMPTY JD.IFEMPTY happens when an if statement has only an empty then branch. Possible unfinished code. Vulnerability and risk A programmer might have left this check, intending to return and add something to the code but forgetting. An if that does nothing impacts performance, especially if method calls are involved. Mitigation and prevention Change the code so that the if contains a non-empty branch or remove the if altogether. Example 1 9 private void foo(Object a) { 10 // ... 11 if (a==null) { 12 // do something 13 } 14 } JD.IFEMPTY is reported for line 11: Redundant 'if' statement. This may be unfinished code. See also • → JD.IFBAD Language: English
  59. 59. Checkers:JD.INF.AREC 53 Checkers:JD.INF.AREC JD.INF.AREC occurs when the method calls itself without any prior checks. Vulnerability and risk If this method is called, it will call itself again and again, and then the program stack will overflow and the JVM will throw a StackOverflowError. Obviously this is not what the programmer intended. Mitigation and prevention JD.INF.AREC has three possible causes. • There is a misspelled instance object. For example, instead of "super.equals(o)", the programmer typed "this.equals(o)" Fix the spelling of the instance object. • The argument of the method is not cast for a specific type. For example, it should be this.equals((MyType)o). Cast the argument to a specific type. • A condition for terminating the recursion is missing. Add a condition that will stop recursion. Example 1 10 /** 11 * Implementation required by the interface. 12 * @param o - object to compare 13 * @return true, if equal. 14 */ 15 public boolean equals(Object o) { 16 return this.equals(o); 17 } JD.INF.AREC is reported for call on line 16: Apparent infinite recursion by calling 'equals(java.lang.Object)' from itself Language: English
  60. 60. Checkers:JD.INST.TRUE 54 Checkers:JD.INST.TRUE JD.INST.TRUE is reported when the result of an instance of for type check is known in advance. Vulnerability and risk There is no error in this construction, but the check does not make sense, and can be replaced by a check for non-null. Maybe there was a typo in a type name or in the name of an instanceof argument. Mitigation and prevention Remove this check or replace it with a check for non-null or change the code to use an appropriate type of object. Example 1 9 private void test3(String b) { 10 if (b instanceof String) { 11 foo(); 12 } 13 } JD.INST.TRUE is reported for 'instanceof' expression on line 10: Condition 'b instanceof String' is redundant and can be replaced with '!=null'. Language: English
  61. 61. Checkers:JD.LIST.ADD 55 Checkers:JD.LIST.ADD JD.LIST.ADD occurs when an operation is performed on a container, for example, addAll, removeAll, retainAll or containsAll, but the argument is a container itself. This is definitely a typo. Vulnerability and risk This is not an error in itself, but since it makes no sense, there is an error in the logic. For example, instead of writing con1.addAll(con2), the programmer wrote con1.addAll(con1). The severity of this error depends on where and how the code is used. Mitigation and prevention Fix the name of the method argument or, perhaps, replace removeAll with list.clean(). Example 1 11 private Collection foo(Collection list12_3, 12 Collection list12_4) { 13 if (list12_3.size() < list12_4.size()) { 14 list12_3.addAll(list12_4); 15 return list12_3; 16 } else { 17 list12_4.addAll(list12_4); 18 return list12_4; 19 } 20 21 } JD.LIST.ADD is reported for 'addAll' call on line 17 : Container 'list12_4' calls 'addAll' with itself as an argument. This code does nothing, or there is simpler way to do it. Probably a typo. Language: English
  62. 62. Checkers:JD.LOCK 56 Checkers:JD.LOCK JD.LOCK occurs when a lock was acquired with a java.util.concurrent.locks.Lock.lock() method call, but it was never actually released; that is, the java.util.concurrent.locks.Lock.unlock() method was not called on some path. Vulnerability and risk This situation can cause deadlock. Mitigation and prevention Here is a pattern for implementing locking by means of a Lock object: l.lock(); try { ... } finally { l.unlock(); } Example 1 12 void action() { 13 Lock l = new ReentrantLock(); 14 l.lock(); 15 try { 16 dosomething(); 17 } catch (Exception e) { 18 l.unlock(); 19 } 20 } 21 22 private void dosomething() throws Exception { 23 // ... 24 } JD.LOCK is reported for the line 13: Lock 'l' acquired but not released. Example 2 11 void action() { 12 Lock l = new ReentrantLock(); 13 l.lock(); 14 try { 15 dosomething(); 16 } catch (Exception e) { 17 // ...
  63. 63. Checkers:JD.LOCK 57 18 } finally { 19 l.unlock(); 20 } 21 } 22 23 private void dosomething() throws Exception { 24 // ... 25 } The problem from the previous snippet is fixed: the lock would be released whether an exception was thrown or not. JD.LOCK is not reported here. Language: English

×