SlideShare uma empresa Scribd logo
1 de 346
Baixar para ler offline
Detected Java Defects
                Software release 7.6


               Document version 2.0
Copyright © 1998-2006 Klocwork Inc.
All rights reserved

This document, as well as the software described in it, is furnished under license and may only be
used or copied in accordance with the terms of such license. The information contained herein is the
property of Klocwork Inc. and is confidential between Klocwork Inc. and the client and remains the
exclusive property of Klocwork Inc. No part of this documentation may be copied, translated, stored
in a retrieval system, or transmitted in any form or by any means, electronic, mechanical,
photocopying, recording or otherwise without the prior written permission of Klocwork Inc.

If you find any problems in the documentation, please report them to us in writing. Klocwork Inc.
does not warrant that this document is error-free.

Klocwork Inc. and Klocwork are registered trademarks and Klocwork inSight, Klocwork inSight Architect, Klocwork Architectural Analysis,
Klocwork inSight Developer, Klocwork Source Cross-Reference, Klocwork Management Console, Klocwork inForce, Klocwork Enterprise
Developer, Klocwork Developer for Java in Eclipse, Klocwork for C/C++, Klocwork for Java, Klocwork inSpect, Klocwork Project Central,
Klocwork inTellect, Klocwork Metrics and Trending, Klocwork Software Analysis, Klocwork Extensibility Interface, and Klocwork Stack
Overflow Analyzer are trademarks of Klocwork Inc.

Copyright notices for third-party software are contained in the file “3rdparty_copyright_notices.txt”, located in the Klocwork installation
directory.

Adobe®, Adobe Acrobat, Acrobat Exchange, Acrobat Reader, and PostScript are either registered trademarks or trademarks of Adobe Systems
Incorporated in the United States and/or other countries. Rational ClearCase is a registered trademark of IBM Corporation. Linux is a registered
trademark of Linus Torvalds. FLEXlm is a registered trademark of Macrovision Corporation. Microsoft®, Microsoft Word, Microsoft Excel,
Microsoft Office, Internet Explorer, Windows®, Windows NT®, Windows® 2000, Windows® 2000 Server, Windows® Server 2003, Windows®
XP, MS-DOS™, Microsoft Visual Studio®, Microsoft .NET, and Microsoft Visual C++ are trademarks of Microsoft Corporation. Pentium® is a
registered trademark of Intel Corporation. Red Hat is a trademark of Red Hat, Inc., in the United States and other countries. Sun, Sun
Microsystems, the Sun Logo, Solaris, Forte, Java, JRE and all Java-related trademarks and logos are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States and other countries. All SPARC trademarks are used under license and are trademarks or registered
trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an
architecture developed by Sun Microsystems, Inc. Tom Sawyer Layout (c) 2005 Tom Sawyer Software, Oakland, California. All Rights Reserved.
MySQL is a registered trademark of MySQL AB in the USA and other countries. InstallShield is a service mark and is either a registered
trademark or trademark of InstallShield Software Corporation in the United States and/or other countries. Java Service Wrapper is a trademark of
Tanuki Software. WinCVS, Krusader and SourceForge are trademarks of OSTG Open Source Technology Group, All Rights Reserved. Apache
TomCat is a trademark of the Apache Software Foundation. Green Hills is a registered trademark of Green Hills Software, Inc. Metrowerks is a
registered trademark of Freescale Semiconductor, Inc. Wind River is a registered trademark of Wind River Systems, Inc.

                                                                                                                         Klocwork Inc.
                                                                                                 Toll-free telephone (North America):
                                                                                                                      1-866-556-2967
                                                                                                                               E-mail:
                                                                                                                 sales@klocwork.com
                                                                                                               support@klocwork.com
                                                                                                  Website: http://www.klocwork.com
                                                                                                                           In the U.S.:
                                                                                                         35 Corporate Drive, 4th Floor
                                                                                                     Burlington, Massachusetts 01803
                                                                                                                                 USA
                                                                                                                            In Canada:
                                                                                                       30 Edgewater Street, Suite 114
                                                                                                                      Ottawa, Ontario
                                                                                                                     Canada K2L 1V8
i




Contents

Chapter 1 About this document                                                                                                                                7


Chapter 2 Code problems detected by Klocwork                                                                                                                 9
     Code problems: Java.....................................................................................................................................9
           ARRAY .............................................................................................................................................9
           CMP.OBJ ........................................................................................................................................11
           CMP.STR ........................................................................................................................................13
           CMPF.FLOAT.................................................................................................................................14
           COV.CMP .......................................................................................................................................16
           ECC.EMPTY...................................................................................................................................18
           EHC.EQ...........................................................................................................................................19
           EHC.HASH .....................................................................................................................................20
           ESCMP.EMPTYSTR ......................................................................................................................21
           EXC.BROADTHROWS .................................................................................................................23
           FIN.EMPTY ....................................................................................................................................24
           FIN.NOSUPER ...............................................................................................................................26
           FSC.PRT..........................................................................................................................................27
           FSC.PRV .........................................................................................................................................28
           FSC.PUB .........................................................................................................................................30
           JD.BITCMP.....................................................................................................................................31
           JD.BITMASK..................................................................................................................................32
           JD.BTO.SBS ...................................................................................................................................34
           JD.BITR ..........................................................................................................................................35
           JD.CAST.COL ................................................................................................................................37
           JD.CAST.SUSP...............................................................................................................................39
           JD.CAST.UPCAST .........................................................................................................................40
           JD.CATCH ......................................................................................................................................41
           JD.CONCUR...................................................................................................................................43
           JD.EQ.ARR .....................................................................................................................................46
           JD.EQ.UTA .....................................................................................................................................47
           JD.EQ.UTC .....................................................................................................................................49
           JD.FINRET......................................................................................................................................50
           JD.IFBAD........................................................................................................................................51
           JD.IFEMPTY ..................................................................................................................................53
           JD.INF.AREC .................................................................................................................................54
           JD.INST.TRUE ...............................................................................................................................56
           JD.LIST.ADD..................................................................................................................................57
           JD.LOCK.........................................................................................................................................58
           JD.LOCK.EXC................................................................................................................................60
           JD.LOCK.NOTIFY .........................................................................................................................62
           JD.LOCK.SLEEP ............................................................................................................................64
           JD.LOCK.WAIT .............................................................................................................................65
           JD.NEXT.........................................................................................................................................67
           JD.OVER.........................................................................................................................................68
           JD.RC.EXPR.CHECK.....................................................................................................................70
ii   Contents


         JD.RC.EXPR.DEAD .......................................................................................................................71
         JD.RC.EXPR.FIELD.......................................................................................................................73
         JD.ST.POS.......................................................................................................................................75
         JD.SYNC.DCL ................................................................................................................................77
         JD.SYNC.IN....................................................................................................................................79
         JD.THREAD.RUN ..........................................................................................................................80
         JD.UMC.FINALIZE........................................................................................................................82
         JD.UMC.WAIT ...............................................................................................................................83
         JD.UN.FIELD..................................................................................................................................85
         JD.UN.MET ....................................................................................................................................86
         JD.UN.PMET ..................................................................................................................................87
         JD.UNCAUGHT .............................................................................................................................89
         JD.VNU.EXIT.................................................................................................................................90
         JD.VNU.PAR ..................................................................................................................................92
         JD.VNU.RE.....................................................................................................................................95
         JD.VNU.SI ......................................................................................................................................96
         JI.REC .............................................................................................................................................98
         MNA.CAP.....................................................................................................................................100
         MNA.CNS.....................................................................................................................................101
         MNA.SUS .....................................................................................................................................103
         NPD.COND...................................................................................................................................104
         NPD.CONST .................................................................................................................................106
         NPD.PAR ......................................................................................................................................108
         NPDS.EXPR..................................................................................................................................109
         NPDS.VAR ...................................................................................................................................114
         NPE.FIELD ...................................................................................................................................117
         NPE.LOCAL .................................................................................................................................119
         NPE.MUST ...................................................................................................................................122
         NPE.PASS.....................................................................................................................................124
         NPE.RET.......................................................................................................................................126
         REDUN.DEF.................................................................................................................................129
         REDUN.EQ...................................................................................................................................130
         REDUN.EQNULL ........................................................................................................................131
         REDUN.NULL..............................................................................................................................132
         REDUN.OP ...................................................................................................................................134
         RI.IGNOREDCALL......................................................................................................................135
         RI.IGNOREDNEW .......................................................................................................................137
         RLK.FIELD...................................................................................................................................138
         RLK.IN..........................................................................................................................................141
         RLK.OUT......................................................................................................................................143
         RLK.SQLCON ..............................................................................................................................147
         RLK.SWT......................................................................................................................................149
         RNU.CHECK ................................................................................................................................151
         RNU.DEREF .................................................................................................................................153
         RNU.NCHECK .............................................................................................................................156
         RNU.NEW ....................................................................................................................................158
         RNU.NULL...................................................................................................................................159
         RNU.THIS.....................................................................................................................................161
         RR.IGNORED...............................................................................................................................162
         RTC.CALL....................................................................................................................................164
         STRCON.LOOP............................................................................................................................166
         SYNCH.NESTED .........................................................................................................................167
         SYNCH.NESTEDS .......................................................................................................................168
         UC.BOOLB...................................................................................................................................170
         UC.BOOLS ...................................................................................................................................171
Contents               iii


               UC.STRS.......................................................................................................................................173
               UC.STRV ......................................................................................................................................175
               UIR.CONSTR ...............................................................................................................................176
               UMC.EXIT....................................................................................................................................178
               UMC.GC .......................................................................................................................................179
               UMC.SYSERR..............................................................................................................................181
               UMC.SYSOUT .............................................................................................................................182
               UMC.TOSTRING .........................................................................................................................184


Chapter 3 Security vulnerabilities detected by Klocwork                                                                                                   187
     Security vulnerabilities: Java ....................................................................................................................187
            CMP.CLASS .................................................................................................................................187
            SV.CLASS.FINAL........................................................................................................................188
            SV.CLEXT.CLLOADER..............................................................................................................190
            SV.CLEXT.POLICY.....................................................................................................................191
            SV.CLLOADER............................................................................................................................192
            SV.CLONE.NOFIN ......................................................................................................................194
            SV.CLONE.SUP ...........................................................................................................................195
            SV.CLONE.UNDEF .....................................................................................................................197
            SV.CLONE.UNSAFE ...................................................................................................................198
            SV.DATA.BOUND.......................................................................................................................200
            SV.DATA.DB ...............................................................................................................................202
            SV.DOS.ARRINDEX ...................................................................................................................205
            SV.DOS.ARRSIZE .......................................................................................................................208
            SV.DOS.RESOURCE ...................................................................................................................210
            SV.DOS.TMPFILEDEL................................................................................................................212
            SV.DOS.TMPFILEEXIT ..............................................................................................................213
            SV.EMAIL ....................................................................................................................................215
            SV.EXEC ......................................................................................................................................218
            SV.EXEC.DIR...............................................................................................................................220
            SV.EXEC.ENV .............................................................................................................................222
            SV.EXPOSE.FIELD......................................................................................................................224
            SV.EXPOSE.FIN ..........................................................................................................................226
            SV.EXPOSE.IFIELD ....................................................................................................................228
            SV.EXPOSE.MUTABLEFIELD ..................................................................................................230
            SV.EXPOSE.RET .........................................................................................................................231
            SV.EXPOSE.STORE ....................................................................................................................233
            SV.FIELD.ACC ............................................................................................................................234
            SV.FIELD.FIN ..............................................................................................................................236
            SV.HTTP_SPLIT ..........................................................................................................................238
            SV.IL.DEV....................................................................................................................................240
            SV.IL.FILE....................................................................................................................................243
            SV.INNERCLASS ........................................................................................................................244
            SV.INT_OVF ................................................................................................................................246
            SV.LOG_FORGING .....................................................................................................................247
            SV.METHOD.ACC.......................................................................................................................249
            SV.METHOD.FINAL ...................................................................................................................251
            SV.METHOD.NONFINAL.GS ....................................................................................................252
            SV.METHOD.NONPRIVATE .....................................................................................................254
            SV.OBJ.INIT.CHECK ..................................................................................................................256
            SV.OBJ.INIT.DEF ........................................................................................................................258
            SV.OBJ.INIT.SET.........................................................................................................................259
            SV.PASSWD.HC ..........................................................................................................................261
            SV.PASSWD.HC.EMPTY............................................................................................................263
iv     Contents


           SV.PASSWD.PLAIN ....................................................................................................................265
           SV.PATH ......................................................................................................................................267
           SV.PATH.INJ................................................................................................................................269
           SV.RACE.FILE.............................................................................................................................271
           SV.RANDOM ...............................................................................................................................272
           SV.SERIAL.INON ........................................................................................................................274
           SV.SERIAL.NON .........................................................................................................................275
           SV.SERIAL.NONDE ....................................................................................................................276
           SV.SERIAL.SAFE ........................................................................................................................278
           SV.SHARED.VAR........................................................................................................................280
           SV.SOCKETS ...............................................................................................................................282
           SV.SQL .........................................................................................................................................285
           SV.SQL.DBSOURCE ...................................................................................................................287
           SV.STRBUF.CLEAN....................................................................................................................290
           SV.STRUTS.NOTRESET.............................................................................................................292
           SV.STRUTS.NOTVALID.............................................................................................................293
           SV.STRUTS.PRIVATE ................................................................................................................296
           SV.STRUTS.RESETMET.............................................................................................................297
           SV.STRUTS.STATIC ...................................................................................................................299
           SV.STRUTS.VALIDMET ............................................................................................................302
           SV.TAINT.....................................................................................................................................303
           SV.TAINT.OERR .........................................................................................................................305
           SV.TAINT_NATIVE ....................................................................................................................307
           SV.TMPFILE ................................................................................................................................308
           SV.UMC.EXIT..............................................................................................................................310
           SV.UMC.JDBC .............................................................................................................................312
           SV.UMC.THREADS ....................................................................................................................314
           SV.UMD.MAIN ............................................................................................................................317
           SV.USE.POLICY ..........................................................................................................................319
           SV.XSS..........................................................................................................................................320
           SV.XSS.DB ...................................................................................................................................322
           SV.XSS.REF .................................................................................................................................324
     Descriptions of sample secure coding rules..............................................................................................326


Chapter 4 Parameters                                                                                                                                    331
     What are defect parameters?.....................................................................................................................331
           Knowledge base parameters ..........................................................................................................331
           Other parameters ...........................................................................................................................332
     About parameter types ..............................................................................................................................332
           Table of parameter types ...............................................................................................................332
           Source parameters .........................................................................................................................333
           Sink parameters .............................................................................................................................334
           Prop parameters .............................................................................................................................334
           Method parameters ........................................................................................................................336
     Shared parameter groups ..........................................................................................................................337
           $MUTABLE.OBJECTS ................................................................................................................337
           $SV.FILEPROP.............................................................................................................................337
           $SV.MAPPROP ............................................................................................................................337
           $SV.MAPSTOP.............................................................................................................................338
           $SV.NUMERICPROP...................................................................................................................338
           $SV.NUMERICSTOP...................................................................................................................338
           $SV.PASSWDSINKS ...................................................................................................................338
           $SV.PROP.....................................................................................................................................338
           $SV.SQL .......................................................................................................................................338
Contents                 v


        $SV.SYSINFO ..............................................................................................................................338
        $SV.TAINT.AWT.........................................................................................................................338
        $SV.TAINT.DB ............................................................................................................................339
        $SV.TAINT.DBSOURCE.............................................................................................................339
        $SV.TAINT.FILES .......................................................................................................................339
        $SV.TAINT.HTTP.ATTRS ..........................................................................................................339
        $SV.TAINT.HTTP.PARAM.........................................................................................................339
        $SV.TAINT.HTTP.REQ ...............................................................................................................339
        $SV.TAINT.SCK ..........................................................................................................................339
        $SV.TAINT.SOAP........................................................................................................................339
        $SV.TAINT.SOURCES ................................................................................................................340
        $SV.TAINT.STRUTS ...................................................................................................................340
        $SV.TAINT.SWING.....................................................................................................................340
        $SV.VALIDATE...........................................................................................................................340
        $SV.XSS........................................................................................................................................340
        $UNCHECKER.FIELD ................................................................................................................340


Index                                                                                                                                              341
7


CHAPTER 1

About this document
            This document describes the specific Java defects that can be detected by
            Klocwork. It also describes defect parameters.
9


CHAPTER 2

Code problems detected by Klocwork

             In This Chapter
             Code problems: Java ..........................................................9




Code problems: Java

             ARRAY
             This error is reported when the index of array access can be less than zero or
             greater than the size of the array.

             Defect Attributes

             Name                               Value
             Defect Code                        ARRAY
             Category                           Code Quality/ Reliability/ Exceptions
             Title                              Array index is out of range
             Message                            Array {0} index {1} is out of range {2}
             Enabled (default)                  true
             Severity (default)                 Critical (1)
             Applicable language                Java
             Customizable                       false
10   Detected Java Defects



                             Vulnerability and risk

                             If this situation occurs in Java, it will throw an IndexArrayOutOfBounds
                             runtime exception. Rather than try to catch this exception, use index
                             checking. Index checking can work up to 100 times faster than catching the
                             exception. Also, an uncaught exception can cause a thread to finish, which
                             can lead to deadlock in multi-thread environments or the death of an
                             application. If a general exception is caught, an application may be restored,
                             but it may be missing functionality or diagnostics, or it may have a logic
                             flaw.

                             Mitigation and prevention

                             Check for array boundaries. Make sure the check is correct, that is, that
                             upperIndex string is less than array.length. Novice programmers usually
                             make mistakes using array.length as index.

                             Example_001:
                             Java Code Sample:
                             ...
                             15:       /**
                             16:         * This method prints file number j from directory dir or
                             17:         * error message if index is out of bounds
                             18:         */
                             19:       public static void getNthFile(File dir, int j) {
                             20:          System.err.println("Info: getting file number " + j
                             21:              + " from directory " + dir);
                             22:          File results[] = dir.listFiles();
                             23:          if (results != null && results.length >= j && j >= 0) {
                             24:            System.out.println(j + " file is " + results[j]);
                             25:          } else {
                             26:            System.err.println("Error: not enough files");
                             27:          }
                             28:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_001.java:24:Critical(1):
                               ARRAY: Array results index j is out of range upper bound:
                               j(j<results.length) from j(j<=results.length)

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_001.java
Chapter 2 Code problems detected by Klocwork    11




Example_002:
Java Code Sample:
...
15:       /**
16:         * This method validates input string. String has field
17:         * separated by :, original string, result string and
18:         * extra info First field sould be equal second field to
19:         * match
20:         */
21:       static boolean validate(String text) {
22:          StringTokenizer tok = new StringTokenizer(text, ":");
23:          String[] result = new String[tok.countTokens()];
24:          int count = 0;
25:          while (tok.hasMoreTokens()) {
26:            result[count] = tok.nextToken();
27:            count++;
28:          }
29:          if ((result == null) || (result.length < 2)
30:              || (result[2] == null)) { return false; }
31:          String toCompare = result[1];
32:          if (toCompare.equalsIgnoreCase(result[0])) return true;
33:          return false;
34:       }
...

Output:
com/klocwork/examples/Example_002.java:29:Critical(1):
  ARRAY: Array result index 2 is out of range upper bound:
  result.length(2<result.length) from
result.length(2<=result.length)

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_002.java


CMP.OBJ
This warning appears if object references are compared rather than objects
themselves. Error produced only if compared object has different types and
none of them has explicit Object type.
12   Detected Java Defects



                             Defect Attributes

                             Name                     Value
                             Defect Code              CMP.OBJ
                             Category                 Code Quality/ Reliability/ Suspicious
                                                      practices
                             Title                    Comparing objects with ==
                             Message                  Comparing objects {0} and {1} with ==
                             Enabled (default)        false
                             Severity (default)       Review (9)
                             Applicable language      Java
                             Customizable             false



                             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 objects are unique in the program, that is, that
                             they don't have the equals method defined or 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_010:
                             Java Code Sample:
                             ...
                             14:   /**
                             15:     * Check that person is John 25 miner
                             16:     */
                             17:   Proffesional john = new Proffesional("John", 25,
                             "miner");
                             18:   public boolean checkJohn(Person p) {
                             19:      return p == john;
                             20:   }
                             ...
Chapter 2 Code problems detected by Klocwork     13




Output:
com/klocwork/examples/Example_010.java:19:Review(9):
  CMP.OBJ: Comparing objects this.john and p with ==

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_010.java


CMP.STR
This warning appears if string references are compared rather than strings
themselves for String type.

Defect Attributes

Name                        Value
Defect Code                 CMP.STR
Category                    Code Quality/ Reliability/ Suspicious
                            practices
Title                       Comparing strings with ==
Message                     Comparing strings {0} and {1} with ==
Enabled (default)           true
Severity (default)          Investigate (5)
Applicable language         Java
Customizable                false



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.
14   Detected Java Defects



                             Example_009:
                             Java Code Sample:
                             ...
                             14:       /**
                             15:         * Return symbolic name of operation
                             16:         */
                             17:       public String nameOperation(String key) {
                             18:          if (key == "++") return "PLUS";
                             19:          if (key == "--") return "MINUS";
                             20:          return "UNKNOWN";
                             21:       }
                             22:
                             23:       // test start
                             24:       public static void main(String[] args) {
                             25:         Example_009 ex = new Example_009();
                             26:         ex.test("++");
                             27:         ex.test("+++");
                             28:         String one = "+";
                             29:         ex.test("+" + one);
                             30:         ex.test(new String("++"));
                             31:       }
                             32:       private void test(String str) {
                             33:         System.err.println("Name of " + str + "="
                             34:             + nameOperation(str));
                             35:       }
                             36:       //test end
                             ...

                             Output:
                             com/klocwork/examples/Example_009.java:18:Investigate(5):
                               CMP.STR: "Comparing strings "++" and key with =="
                             com/klocwork/examples/Example_009.java:19:Investigate(5):
                               CMP.STR: "Comparing strings "--" and key with =="

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_009.java


                             CMPF.FLOAT
                             Error printed when two float or double value compared using equals operator
                             (==).
Chapter 2 Code problems detected by Klocwork       15




Defect Attributes

Name                      Value
Defect Code               CMPF.FLOAT
Category                  Code Quality/ Reliability/ Suspicious practices
Title                     Equality checks on floating point types should
                          be avoided
Message                   Equality checks on floating point types should
                          be avoided
Enabled (default)         true
Severity (default)        Warning (6)
Applicable language       Java
Customizable              false



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).
16   Detected Java Defects



                             Example_023:
                             Java Code Sample:
                             ...
                             14:       /**
                             15:         * Calculates define integral
                             16:         */
                             17:       public static double integral(MyFunction f, double x1,
                             18:            double x2) {
                             19:          double x = x1;
                             20:          double result = 0;
                             21:          double step = (x2 - x1) / 700;
                             22:          while (x != x2) { // should use (x <= x2)
                             23:            result = result + f.valueFor(x) * step;
                             24:            x = x + step;
                             25:          }
                             26:          return result;
                             27:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_023.java:22:Warning(6):
                               CMPF.FLOAT: Equality checks on floating point types should be
                             avoided

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_023.java


                             COV.CMP
                             Error exists when method compareTo declared with signature different than
                             int compareTo(Object).
Chapter 2 Code problems detected by Klocwork       17




Defect Attributes

Name                      Value
Defect Code               COV.CMP
Category                  Code Quality/ Reliability/ Suspicious practices
Title                     Method compareTo() should have signature int
                          compareTo(Object)
Message                   Method compareTo() should have signature int
                          compareTo(Object)
Enabled (default)         true
Severity (default)        Warning (6)
Applicable language       Java
Customizable              false



Vulnerability and risk

Intent was probably to implement interface method of Comarible 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 Cloneable, declare int compareTo(Object)
method.

Example_024:
Java Code Sample:
...
18:        String name;
19:        int compareTo(MyClass a) {
20:          return name.compareTo(a.name);
21:        }
...

Output:
com/klocwork/examples/Example_024.java:20:Warning(6):
  COV.CMP: Method compareTo() should have signature int
  compareTo(Object)

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_024.java
18   Detected Java Defects




                             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.

                             Defect Attributes

                             Name                        Value
                             Defect Code                 ECC.EMPTY
                             Category                    Code Quality/ Reliability/ Error Handling
                             Title                       Empty catch clause
                             Message                     Empty catch clause
                             Enabled (default)           true
                             Severity (default)          Investigate (5)
                             Applicable language         Java
                             Customizable                false



                             Example_305:
                             Java Code Sample:
                             ...
                             20:       public void openFile(String name) {
                             21:         try {
                             22:           FileInputStream is = new FileInputStream(name);
                             23:           // read file ...
                             24:         } catch (FileNotFoundException e) {
                             25:           // TODO Auto-generated catch block
                             26:         }
                             27:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_305.java:24:Investigate(5):
                               ECC.EMPTY: Empty catch clause

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_305.java
Chapter 2 Code problems detected by Klocwork       19




EHC.EQ
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 a equals(). This may cause a problem with some collections
that expect that equal objects to have equal hashcodes.

Defect Attributes

Name                   Value
Defect Code            EHC.EQ
Category               Code Quality/ Reliability/ Suspicious practices
Title                  Class defines hashCode() but does not define
                       equals()
Message                Class defines hashCode() but does not define
                       equals()
Enabled (default)      true
Severity (default)     Warning (6)
Applicable language    Java
Customizable           false



Example_307:
Java Code Sample:
...
17:     public class MyClass {
18:       private int seed;
19:       public MyClass(int seed) {
20:         this.seed = seed;
21:       }
22:       public int hashCode() {
23:         return seed;
24:       }
25:       // no equals(Object o) method defined
26:     }
...
20   Detected Java Defects


                             Output:
                             com/klocwork/examples/Example_307.java:23:Warning(6):
                               EHC.EQ: Class defines hashCode() but does not define equals()

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_307.java


                             EHC.HASH
                             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.

                             Defect Attributes

                             Name                    Value
                             Defect Code             EHC.HASH
                             Category                Code Quality/ Reliability/ Suspicious practices
                             Title                   Class defines equals() but does not define
                                                     hashCode()
                             Message                 Class defines equals() but does not define
                                                     hashCode()
                             Enabled (default)       true
                             Severity (default)      Warning (6)
                             Applicable language     Java
                             Customizable            false
Chapter 2 Code problems detected by Klocwork        21




Example_306:
Java Code Sample:
...
17:       public class MyClass {
18:         private int seed;
19:         public MyClass(int seed) {
20:           this.seed = seed;
21:         }
22:         public boolean equals(Object o) {
23:           return (o instanceof MyClass)
24:               && ((MyClass) o).seed == seed;
25:         }
26:         // no hashCode method defined
27:       }
...

Output:
com/klocwork/examples/Example_306.java:23:Warning(6):
  EHC.HASH: Class defines equals() but does not define
hashCode()

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_306.java


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.
22   Detected Java Defects



                             Defect Attributes

                             Name                  Value
                             Defect Code           ESCMP.EMPTYSTR
                             Category              Code Quality/ Efficiency
                             Title                 Inefficient empty string comparison
                             Message               Comparing strings {0} and {1} using equals(),
                                                   instead of length() == 0
                             Enabled (default)     false
                             Severity (default)    Suggestion (7)
                             Applicable language   Java
                             Customizable          false



                             Example_003:
                             Java Code Sample:
                             ...
                             16:       public boolean emptyCheck1() {
                             17:         if (s.equals("")) return true;
                             18:         return false;
                             19:       }
                             20:       public boolean emptyCheck2() {
                             21:         if ("".equals(s)) return true;
                             22:         return false;
                             23:       }
                             24:       // fixed code
                             25:       public boolean emptyCheck3() {
                             26:         if (s.length() == 0) return true;
                             27:         return false;
                             28:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_003.java:17:Suggestion(7):
                               ESCMP.EMPTYSTR: "Comparing strings "" and this.s using
                             equals(),
                               instead of length() == 0"
                             com/klocwork/examples/Example_003.java:21:Suggestion(7):
                               ESCMP.EMPTYSTR: "Comparing strings this.s and "" using
                             equals(),
                               instead of length() == 0"
Chapter 2 Code problems detected by Klocwork     23




See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_003.java


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 good
error recovery.

Defect Attributes

Name                      Value
Defect Code               EXC.BROADTHROWS
Category                  Code Quality/ Reliability/ Error Handling
Title                     Method has an overly broad throws declaration
Message                   The {0} method throws a generic exception {1}
Enabled (default)         false
Severity (default)        Style (8)
Applicable language       Java
Customizable              true



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. It raises the risk of improperly handled problems. 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.
24   Detected Java Defects



                             Example_300:
                             Java Code Sample:
                             ...
                             23:       public void processFile(String fileName) throws Exception
                             {
                             24:           InputStream is = new FileInputStream(fileName);
                             25:           // do something
                             26:       }
                             27:       public int calculateSum(Collection data) throws Throwable
                             {
                             28:           int sum = 0;
                             29:           for (Iterator it = data.iterator(); it.hasNext();) {
                             30:             String element = (String) it.next();
                             31:             int i = Integer.parseInt(element);
                             32:             sum += i;
                             33:           }
                             34:           return sum;
                             35:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_300.java:24:Style(8):
                               EXC.BROADTHROWS: The processFile method throws a generic
                             exception
                               java.lang.Exception
                             com/klocwork/examples/Example_300.java:28:Style(8):
                               EXC.BROADTHROWS: The calculateSum method throws a generic
                             exception
                               java.lang.Throwable

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_300.java


                             FIN.EMPTY
                             Empty finalize() method.

                             FIN code problems have a questionable implementation of finalize method().
                             In this case, there is an empty finalize() method.
Chapter 2 Code problems detected by Klocwork      25




Defect Attributes

Name                        Value
Defect Code                 FIN.EMPTY
Category                    Code Quality/ Efficiency
Title                       Empty finalize() method should be removed
Message                     Empty finalize() method should be removed
Enabled (default)           true
Severity (default)          Suggestion (7)
Applicable language         Java
Customizable                false



Example_004:
Java Code Sample:
...
15:
16:       public void test3() {
17:         new Example_004() {
18:           protected void finalize() throws Throwable {
19:
20:           }
21:         };
22:       }
23:       // fixed code
24:       public void test1() {
25:         new Example_004() {
26:         };
27:       }
...

Output:
com/klocwork/examples/Example_004.java:20:Suggestion(7):
  FIN.EMPTY: Empty finalize() method should be removed

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_004.java
26   Detected Java Defects




                             FIN.NOSUPER
                             Implementation of the finalize() method should call super.finalize().

                             FIN code problems have a questionable implementation of finalize method().
                             In this case there is a finalize() method implementation that does not call
                             super.finalize().

                             Defect Attributes

                             Name                     Value
                             Defect Code              FIN.NOSUPER
                             Category                 Code Quality/ Reliability/ Suspicious practices
                             Title                    Implementation of the finalize() method should
                                                      call super.finalize()
                             Message                  Implementation of the finalize() method should
                                                      call super.finalize()
                             Enabled (default)        true
                             Severity (default)       Unexpected (4)
                             Applicable language      Java
                             Customizable             false



                             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_308:
                             Java Code Sample:
                             ...
                             16: public class Example_308 {
                             17:   /*
                             18:     * no super.finalize() was called
                             19:     */
                             20:   public void finalize() {
                             21:      System.err.println("finalized");
                             22:   }
                             23: }
                             ...
Chapter 2 Code problems detected by Klocwork       27




Output:
com/klocwork/examples/Example_308.java:21:Unexpected(4):
  FIN.NOSUPER: Implementation of the finalize() method should
call
  super.finalize()

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_308.java


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.

Defect Attributes

Name                    Value
Defect Code             FSC.PRT
Category                Code Quality/ Maintainability
Title                   Class and its superclass have protected fields
                        with the same name
Message                 Class {0} hides field {2} of superclass {1} by
                        declaring a protected or package-private field
                        with the same name
Enabled (default)       false
Severity (default)      Review (9)
Applicable language     Java
Customizable            false
28   Detected Java Defects


                             Example_309:
                             Java Code Sample:
                             ...
                             17:    public class SuperClass {
                             18:       protected int index;
                             19:       // ...
                             20:    }
                             21:    public class SubClass extends SuperClass {
                             22:       protected int index;
                             23:       // ...
                             24:    }
                             ...

                             Output:
                             com/klocwork/examples/Example_309.java:21:Review(9):
                               FSC.PRT: Class com.klocwork.examples.Example_309$SubClass and
                             its
                               superclass com.klocwork.examples.Example_309$SuperClass have
                             protected
                               fields with the same name: index

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_309.java


                             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.
Chapter 2 Code problems detected by Klocwork          29




Defect Attributes

Name                    Value
Defect Code             FSC.PRV
Category                Code Quality/ Maintainability
Title                   Class and its superclass have private fields with
                        the same name
Message                 Class {0} hides field {2} of superclass {1} by
                        declaring a private field with the same name
Enabled (default)       false
Severity (default)      Review (9)
Applicable language     Java
Customizable            false



Example_310:
Java Code Sample:
...
17:       public class SuperClass {
18:         private int index;
19:         // ...
20:       }
21:       public class SubClass extends SuperClass {
22:         private int index;
23:         // ...
24:       }
...

Output:
com/klocwork/examples/Example_310.java:21:Review(9):
  FSC.PRV: Class com.klocwork.examples.Example_310$SubClass and
its
  superclass com.klocwork.examples.Example_310$SuperClass have
private
  fields with the same name: index

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_310.java
30   Detected Java Defects




                             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.

                             Defect Attributes

                             Name                     Value
                             Defect Code              FSC.PUB
                             Category                 Code Quality/ Maintainability
                             Title                    Class and its superclass have public fields with
                                                      the same name
                             Message                  Class {0} hides field {2} of superclass {1} by
                                                      declaring a public field with the same name
                             Enabled (default)        false
                             Severity (default)       Warning (6)
                             Applicable language      Java
                             Customizable             false



                             Example_311:
                             Java Code Sample:
                             ...
                             17:       public class   SuperClass {
                             18:         public int   index;
                             19:         // ...
                             20:       }
                             21:       public class   SubClass extends SuperClass {
                             22:         public int   index;
                             23:         // ...
                             24:       }
                             ...

                             Output:
                             com/klocwork/examples/Example_311.java:21:Warning(6):
                               FSC.PUB: Class com.klocwork.examples.Example_311$SubClass and
                             its
                               superclass com.klocwork.examples.Example_311$SuperClass have
                             public
                               fields with the same name: index
Chapter 2 Code problems detected by Klocwork        31




See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_311.java


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.

Defect attributes

Name                     Value
Defect Code              JD.BITCMP
Category                 Code Quality/ Reliability/ Suspicious practices
Title                    Using non short-circuit logic in expression
Message                  Questionable use of bit operation '{0}' in
                         expression. Did you mean '{1}'?
Enabled (default)        true
Severity (default)       Severe (2)
Applicable language      Java



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.
32   Detected Java Defects



                             Example_043:
                             Java Code Sample:
                             ...
                             14:    static void check(int arr[]) {
                             15:       if (arr!=null & arr.length!=0) {
                             16:         foo();
                             17:       }
                             18:       return;
                             19:     }
                             ...

                             Output:
                             com/klocwork/examples/Example_043.java:15:Severe(2):
                              JD.BITCMP: Questionable use of bit operation '&' in
                             expression. Did
                               you mean '&&'?

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_04
                             3.java

                             See also:
                                   JD.BITMASK (on page 32)
                                   JD.BITR (on page 35)


                             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.
Chapter 2 Code problems detected by Klocwork      33




Defect attributes

Name                     Value
Defect Code              JD.BITMASK
Category                 Code Quality/ Reliability/ Suspicious practices
Title                    Possible error in bit operations
Message                  Incompatible bitmasks '{0}' and '{1}' cause the
                         expression to always be constant.
Enabled (default)        true
Severity (default)       Severe (2)
Applicable language      Java



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_041:
Java Code Sample:
...
16:       final static int FLAG = 0x01;
17:       static boolean checkMask(int a) {
18:         // mistyped, should be &
19:          if ((a |FLAG) == 0) return true;
20:          return false;
21:       }
...

Output:

com/klocwork/examples/Example_041.java:19:Severe(2):
JD.BITMASK: Incompatible bitmasks '0x1' and '0x0' cause the
expression to always be constant.
34   Detected Java Defects


                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_04
                             1.java

                             See also:
                                 JD.BITCMP (on page 31)
                                 JD.BITR (on page 35)


                             JD.BTO.SBS
                             The JD.BTO.SBS checker triggers an error if a byte type is used with shift
                             operations or with an OR bit operator. Usually, it is an error, because usually,
                             the byte is perceived as unsigned and, if it contains a number greater than
                             128, it will be negative and the OR operator will produce unexpected results.

                             Defect attributes

                             Name                     Value
                             Defect Code              JD.BTO.SBS
                             Category                 Code Quality/ Reliability/ Suspicious practices
                             Title                    Bit operation used with signed value
                             Message                  Bit operation '{1}' used with signed byte value
                                                      of '{0}'
                             Enabled (default)        true
                             Severity (default)       Warning (6)
                             Applicable language      Java



                             Vulnerability and risk

                             JD.BTO.SBS defects result in incorrect program behavior.

                             Mitigation and prevention

                             Manually convert the unsigned value to signed and cast to the int, that is, if
                             you want to store '160', make sure the int contains '160', not -96, as would be
                             the case with an implicit cast.
Chapter 2 Code problems detected by Klocwork    35




Example_040:
Java Code Sample:
...
16:   static int ipToInt(byte[] inet) {
17:      int l = 0;
18:      for (int i = 0; i < inet.length; i++) {
19:        final byte b = inet[i];
20:        l=l<<8 | b;
21:      }
22:      return l;
23:    }
24:    // fixed
25:    static int ipToInt2(byte[] inet) {
26:      int l = 0;
27:      for (int i = 0; i < inet.length; i++) {
28:        final byte b = inet[i];
29:        int x = b<0?256+b:b;
30:        l=l<<8 | x;
31:      }
32:      return l;
33:    }
...

Output:
com/klocwork/examples/Example_040.java:20:Warning(6):
 JD.BTO.SBS: Bit operation '|' used with signed byte value of
'b'

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_04
0.java


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.
36   Detected Java Defects



                             Defect attributes

                             Name                      Value
                             Defect Code               JD.BITR
                             Category                  Code Quality/ Reliability/ Suspicious practices
                             Title                     Redundant expression
                             Message                   Expression '{0}' is always '{1}'. Is there a typo?
                             Enabled (default)         true
                             Severity (default)        Severe (2)
                             Applicable language       Java

                             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_042:
                             Java Code Sample:
                             ...
                             14:     static void check(boolean hasFields) {
                             15:        if (hasFields = true) {
                             16:          foo();
                             17:        }
                             18:        return;
                             19:      }
                             ...

                             Output:
                             com/klocwork/examples/Example_042.java:15:Severe(2):
                              JD.BITR: Expression '(...)' is always '1'. Is it a typo?

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_04
                             2.java
Chapter 2 Code problems detected by Klocwork          37




See also:
    JD.BITCMP (on page 31)
    JD.BITMASK (on page 32)
    JD.RC.EXPR.CHECK (on page 70)
    JD.RC.EXPR.DEAD (on page 71)


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.

Defect attributes

Name                     Value
Defect Code              JD.CAST.COL
Category                 Code Quality/ Reliability/ Exceptions
Title                    Possible ClassCastException for collection
Message                  Suspicious cast to '{0}' of collection element. Put
                         the object into the collection as '{1}'.
Enabled (default)        true
Severity (default)       Error (3)
Applicable language Java



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.
38   Detected Java Defects



                             Example_071:
                             Java Code Sample:
                             ...
                             19:    class Filter {
                             20:       HashMap len=new HashMap();
                             21:       void fill(File dir){
                             22:         File[] list = dir.listFiles();
                             23:         for (int i = 0; i < list.length; i++) {
                             24:           File file = list[i];
                             25:           len.put(file,new Long(file.length()));
                             26:         }
                             27:       }
                             28:       int getLength(String file){
                             29:         Long l = (Long) len.get(file);
                             30:         if (l!=null) return l.intValue();
                             31:         return 0;
                             32:       }
                             33:     }
                             ...

                             Output:
                             com/klocwork/examples/Example_071.java:29:Error(3):
                              JD.CAST.COL: Suspicious cast to 'java.lang.String' of
                             collection
                               element. Put the object into the collection as
                             'java.io.File'.
                              ->                   get at
                             com/klocwork/examples/Example_071.java:29
                              ->                   put at
                             com/klocwork/examples/Example_071.java:25

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_07
                             1.java

                             See also:
                                   JD.CAST.UPCAST (on page 40)
                                   JD.CATCH (on page 41)
Chapter 2 Code problems detected by Klocwork         39




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.)

Defect attributes

Name                     Value
Defect Code              JD.CAST.SUSP
Category                 Code Quality/ Reliability/ Exceptions
Title                    Possible ClassCastException for different types
Message                  Suspicious cast of '{0}' from '{1}' to '{2}', {3}.
Enabled (default)        true
Severity (default)       Unexpected (4)
Applicable language      Java



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_069:
Java Code Sample:
...
15:     void setValue(Object a, Object value) {
16:        if (a instanceof String) {
17:          StringBuffer b = (StringBuffer) a;
18:          b.append("=");
19:          b.append(value);
20:        }
21:      }
...
40   Detected Java Defects


                             Output:
                             com/klocwork/examples/Example_069.java:17:Unexpected(4):
                              JD.CAST.SUSP: Suspicious cast of 'a' from 'java.lang.String'
                             to
                                'java.lang.StringBuffer', where types are unrelated.
                              on trace 16 17

                             See complete code sample:

                             <Klocwork installation
                             directory>/samples/inforcejava/com/klocwork/examples/Example_06
                             9.java

                             See also:

                             JD.CAST.UPCAST (on page 40)


                             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.

                             Defect attributes

                             Name                     Value
                             Defect Code              JD.CAST.UPCAST
                             Category                 Code Quality/ Reliability/ Exceptions
                             Title                    Possible ClassCastException for subtypes
                             Message                  Suspicious cast of '{0}' to '{2}', where '{2}' is a
                                                      subtype of '{1}'. This object can hold other
                                                      subtypes of '{1}' which can cause a
                                                      ClassCastException.
                             Enabled (default)        true
                             Severity (default)       Warning (6)
                             Applicable language Java



                             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.
Chapter 2 Code problems detected by Klocwork   41




Example_070:
Java Code Sample:
...
19:   void setValue(Object a, Object value) {
20:      if (a instanceof Map) {
21:        HashMap b = (HashMap) a;
22:        b.put(value, "");
23:      } else if (a instanceof List) {
24:        List b = (List) a;
25:        b.add(value);
26:      }
27:    }
...

Output:

com/klocwork/examples/Example_070.java:21:Warning(6):

 JD.CAST.UPCAST: Suspicious cast of 'a' to 'java.util.HashMap',
where

  'java.util.HashMap' is subtype of 'java.util.Map'. This
object can

  hold other subtypes of 'java.util.Map' which can cause

  ClassCastException.

 on trace 20 21

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_07
0.java

See also:

JD.CAST.SUSP (on page 39)


JD.CATCH
Klocwork reports a JD.CATCH defect 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.
42   Detected Java Defects



                             Defect attributes

                             Name                     Value
                             Defect Code              JD.CATCH
                             Category                 Code Quality/ Reliability/ Error Handling
                             Title                    Catching runtime exception
                             Message                  Catching '{0}' explicitly is usually a bad
                                                      practice. Use preventive checks on data instead.
                             Enabled (default)        true
                             Severity (default)       Investigate (5)
                             Applicable language      Java



                             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_058:
                             Java Code Sample:
                             ...
                             16:     // horrible abuse of exceptions. Don't ever do this!
                             17:      void foo(int arr[]) {
                             18:        try {
                             19:           int i = 0;
                             20:           while (true) {
                             21:              arr[i++]--;
                             22:           }
                             23:         } catch (ArrayIndexOutOfBoundsException e) {
                             24:             return;
                             25:         }
                             26:
                             27:      }
                             ...
Chapter 2 Code problems detected by Klocwork    43




Output:
com/klocwork/examples/Example_058.java:23:Investigate(5):
 JD.CATCH: Catching 'java.lang.ArrayIndexOutOfBoundsException'
  explicitly is usually a bad practice. Use preventive checks
on data
  instead.

See complete code sample:

<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_05
8.java

References

Effective Java, Item 39.


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.

Defect attributes

Name                Value
Defect Code         JD.CONCUR
Category            Code Quality/ Reliability/ Exceptions
Title               Possible ConcurrentModificationException
Message             Possible 'ConcurrentModificationException' can be
                    thrown by method '{0}' while iterating over '{1}'.
                    You cannot remove a collection element while
                    iterating over the same collection.
Enabled (default)   true
Severity (default) Critical (1)
Applicable          Java
language



Vulnerability and risk

On the following invocation of the "next" method, the code will throw a
ConcurrentModificationException.
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis
Detected Java Defects in Klocwork Software Analysis

Mais conteúdo relacionado

Destaque

Other Selected Projects
Other Selected ProjectsOther Selected Projects
Other Selected ProjectsAYUB PATEL
 
Landscapes and sketches
Landscapes and sketchesLandscapes and sketches
Landscapes and sketchesPaul Davenport
 
Landscape Drawing
Landscape DrawingLandscape Drawing
Landscape DrawingWC Yan
 
Critical Analysis: Dept. of Architecture, CET
Critical Analysis: Dept. of Architecture, CETCritical Analysis: Dept. of Architecture, CET
Critical Analysis: Dept. of Architecture, CETbaburajiv2007
 
Urban design analysis, Circulation, Architecture, London, Redevelopment studies
Urban design analysis, Circulation, Architecture, London, Redevelopment  studiesUrban design analysis, Circulation, Architecture, London, Redevelopment  studies
Urban design analysis, Circulation, Architecture, London, Redevelopment studiesSujeet Thakare
 
Architecture drawing presentation
Architecture drawing presentationArchitecture drawing presentation
Architecture drawing presentationCarlson Ko
 

Destaque (8)

Other Selected Projects
Other Selected ProjectsOther Selected Projects
Other Selected Projects
 
Landscapes and sketches
Landscapes and sketchesLandscapes and sketches
Landscapes and sketches
 
Landscape Drawing
Landscape DrawingLandscape Drawing
Landscape Drawing
 
Critical Analysis: Dept. of Architecture, CET
Critical Analysis: Dept. of Architecture, CETCritical Analysis: Dept. of Architecture, CET
Critical Analysis: Dept. of Architecture, CET
 
Concept sheet - Thesis
Concept sheet - ThesisConcept sheet - Thesis
Concept sheet - Thesis
 
Urban design analysis, Circulation, Architecture, London, Redevelopment studies
Urban design analysis, Circulation, Architecture, London, Redevelopment  studiesUrban design analysis, Circulation, Architecture, London, Redevelopment  studies
Urban design analysis, Circulation, Architecture, London, Redevelopment studies
 
Architecture drawing presentation
Architecture drawing presentationArchitecture drawing presentation
Architecture drawing presentation
 
5 Type Of Architecture Design Process
5 Type Of Architecture Design Process 5 Type Of Architecture Design Process
5 Type Of Architecture Design Process
 

Semelhante a Detected Java Defects in Klocwork Software Analysis

Easy recovery62 user guide en
Easy recovery62 user guide enEasy recovery62 user guide en
Easy recovery62 user guide enMichael Fernandes
 
Upgrading blackboard academic_suite_to_blackboard_learn_release_9
Upgrading blackboard academic_suite_to_blackboard_learn_release_9Upgrading blackboard academic_suite_to_blackboard_learn_release_9
Upgrading blackboard academic_suite_to_blackboard_learn_release_9Selva G Kumar
 
2020 KringleCon HolidayHack Report - Brazzell
2020 KringleCon HolidayHack Report - Brazzell2020 KringleCon HolidayHack Report - Brazzell
2020 KringleCon HolidayHack Report - BrazzellCurtis Brazzell
 
Cycle_Count_Approval_Process.pdf
Cycle_Count_Approval_Process.pdfCycle_Count_Approval_Process.pdf
Cycle_Count_Approval_Process.pdfthanyac2
 
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...Case Study: EchoStar Transforms Complex Software Releases to Customer Network...
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...CA Technologies
 
Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Curtis Brenneman
 
Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Curtis Brenneman
 
deploying-oracle-12c-on-rhel6_1.2_1.pdf
deploying-oracle-12c-on-rhel6_1.2_1.pdfdeploying-oracle-12c-on-rhel6_1.2_1.pdf
deploying-oracle-12c-on-rhel6_1.2_1.pdfcpcproc
 
V Mware Qualcomm Case1
V Mware Qualcomm Case1V Mware Qualcomm Case1
V Mware Qualcomm Case1davidbe
 
R12_IMPLEMENTATION GUIDE.pdf
R12_IMPLEMENTATION GUIDE.pdfR12_IMPLEMENTATION GUIDE.pdf
R12_IMPLEMENTATION GUIDE.pdfTejeshwar Kumar
 
CCNA Routing and Switching Complete Study Guide.pdf
CCNA Routing and Switching Complete Study Guide.pdfCCNA Routing and Switching Complete Study Guide.pdf
CCNA Routing and Switching Complete Study Guide.pdfNho Vĩnh
 
blue-infinity White Paper on JavaFX by Jan Stenvall
blue-infinity White Paper on JavaFX by Jan Stenvallblue-infinity White Paper on JavaFX by Jan Stenvall
blue-infinity White Paper on JavaFX by Jan Stenvallblue-infinity
 
Extract The Traffic From The Db
Extract The Traffic From The DbExtract The Traffic From The Db
Extract The Traffic From The DbMoshe Kaplan
 

Semelhante a Detected Java Defects in Klocwork Software Analysis (20)

Easy recovery62 user guide en
Easy recovery62 user guide enEasy recovery62 user guide en
Easy recovery62 user guide en
 
Upgrading blackboard academic_suite_to_blackboard_learn_release_9
Upgrading blackboard academic_suite_to_blackboard_learn_release_9Upgrading blackboard academic_suite_to_blackboard_learn_release_9
Upgrading blackboard academic_suite_to_blackboard_learn_release_9
 
2020 KringleCon HolidayHack Report - Brazzell
2020 KringleCon HolidayHack Report - Brazzell2020 KringleCon HolidayHack Report - Brazzell
2020 KringleCon HolidayHack Report - Brazzell
 
Cycle_Count_Approval_Process.pdf
Cycle_Count_Approval_Process.pdfCycle_Count_Approval_Process.pdf
Cycle_Count_Approval_Process.pdf
 
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...Case Study: EchoStar Transforms Complex Software Releases to Customer Network...
Case Study: EchoStar Transforms Complex Software Releases to Customer Network...
 
Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5
 
Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5Whats New In Change Auditor - 5.5
Whats New In Change Auditor - 5.5
 
deploying-oracle-12c-on-rhel6_1.2_1.pdf
deploying-oracle-12c-on-rhel6_1.2_1.pdfdeploying-oracle-12c-on-rhel6_1.2_1.pdf
deploying-oracle-12c-on-rhel6_1.2_1.pdf
 
V Mware Qualcomm Case1
V Mware Qualcomm Case1V Mware Qualcomm Case1
V Mware Qualcomm Case1
 
Rst4userguide
Rst4userguideRst4userguide
Rst4userguide
 
R12_IMPLEMENTATION GUIDE.pdf
R12_IMPLEMENTATION GUIDE.pdfR12_IMPLEMENTATION GUIDE.pdf
R12_IMPLEMENTATION GUIDE.pdf
 
C sharp notes
C sharp notesC sharp notes
C sharp notes
 
CCNA Routing and Switching Complete Study Guide.pdf
CCNA Routing and Switching Complete Study Guide.pdfCCNA Routing and Switching Complete Study Guide.pdf
CCNA Routing and Switching Complete Study Guide.pdf
 
blue-infinity White Paper on JavaFX by Jan Stenvall
blue-infinity White Paper on JavaFX by Jan Stenvallblue-infinity White Paper on JavaFX by Jan Stenvall
blue-infinity White Paper on JavaFX by Jan Stenvall
 
Thamim
ThamimThamim
Thamim
 
Project Management Plan
Project Management PlanProject Management Plan
Project Management Plan
 
brother 2170
brother 2170brother 2170
brother 2170
 
9500 mxc user manual 004
9500 mxc user manual 0049500 mxc user manual 004
9500 mxc user manual 004
 
Dng de-01012014
Dng de-01012014Dng de-01012014
Dng de-01012014
 
Extract The Traffic From The Db
Extract The Traffic From The DbExtract The Traffic From The Db
Extract The Traffic From The Db
 

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
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...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

Detected Java Defects in Klocwork Software Analysis

  • 1. Detected Java Defects Software release 7.6 Document version 2.0
  • 2. Copyright © 1998-2006 Klocwork Inc. All rights reserved This document, as well as the software described in it, is furnished under license and may only be used or copied in accordance with the terms of such license. The information contained herein is the property of Klocwork Inc. and is confidential between Klocwork Inc. and the client and remains the exclusive property of Klocwork Inc. No part of this documentation may be copied, translated, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior written permission of Klocwork Inc. If you find any problems in the documentation, please report them to us in writing. Klocwork Inc. does not warrant that this document is error-free. Klocwork Inc. and Klocwork are registered trademarks and Klocwork inSight, Klocwork inSight Architect, Klocwork Architectural Analysis, Klocwork inSight Developer, Klocwork Source Cross-Reference, Klocwork Management Console, Klocwork inForce, Klocwork Enterprise Developer, Klocwork Developer for Java in Eclipse, Klocwork for C/C++, Klocwork for Java, Klocwork inSpect, Klocwork Project Central, Klocwork inTellect, Klocwork Metrics and Trending, Klocwork Software Analysis, Klocwork Extensibility Interface, and Klocwork Stack Overflow Analyzer are trademarks of Klocwork Inc. Copyright notices for third-party software are contained in the file “3rdparty_copyright_notices.txt”, located in the Klocwork installation directory. Adobe®, Adobe Acrobat, Acrobat Exchange, Acrobat Reader, and PostScript are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Rational ClearCase is a registered trademark of IBM Corporation. Linux is a registered trademark of Linus Torvalds. FLEXlm is a registered trademark of Macrovision Corporation. Microsoft®, Microsoft Word, Microsoft Excel, Microsoft Office, Internet Explorer, Windows®, Windows NT®, Windows® 2000, Windows® 2000 Server, Windows® Server 2003, Windows® XP, MS-DOS™, Microsoft Visual Studio®, Microsoft .NET, and Microsoft Visual C++ are trademarks of Microsoft Corporation. Pentium® is a registered trademark of Intel Corporation. Red Hat is a trademark of Red Hat, Inc., in the United States and other countries. Sun, Sun Microsystems, the Sun Logo, Solaris, Forte, Java, JRE and all Java-related trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. Tom Sawyer Layout (c) 2005 Tom Sawyer Software, Oakland, California. All Rights Reserved. MySQL is a registered trademark of MySQL AB in the USA and other countries. InstallShield is a service mark and is either a registered trademark or trademark of InstallShield Software Corporation in the United States and/or other countries. Java Service Wrapper is a trademark of Tanuki Software. WinCVS, Krusader and SourceForge are trademarks of OSTG Open Source Technology Group, All Rights Reserved. Apache TomCat is a trademark of the Apache Software Foundation. Green Hills is a registered trademark of Green Hills Software, Inc. Metrowerks is a registered trademark of Freescale Semiconductor, Inc. Wind River is a registered trademark of Wind River Systems, Inc. Klocwork Inc. Toll-free telephone (North America): 1-866-556-2967 E-mail: sales@klocwork.com support@klocwork.com Website: http://www.klocwork.com In the U.S.: 35 Corporate Drive, 4th Floor Burlington, Massachusetts 01803 USA In Canada: 30 Edgewater Street, Suite 114 Ottawa, Ontario Canada K2L 1V8
  • 3. i Contents Chapter 1 About this document 7 Chapter 2 Code problems detected by Klocwork 9 Code problems: Java.....................................................................................................................................9 ARRAY .............................................................................................................................................9 CMP.OBJ ........................................................................................................................................11 CMP.STR ........................................................................................................................................13 CMPF.FLOAT.................................................................................................................................14 COV.CMP .......................................................................................................................................16 ECC.EMPTY...................................................................................................................................18 EHC.EQ...........................................................................................................................................19 EHC.HASH .....................................................................................................................................20 ESCMP.EMPTYSTR ......................................................................................................................21 EXC.BROADTHROWS .................................................................................................................23 FIN.EMPTY ....................................................................................................................................24 FIN.NOSUPER ...............................................................................................................................26 FSC.PRT..........................................................................................................................................27 FSC.PRV .........................................................................................................................................28 FSC.PUB .........................................................................................................................................30 JD.BITCMP.....................................................................................................................................31 JD.BITMASK..................................................................................................................................32 JD.BTO.SBS ...................................................................................................................................34 JD.BITR ..........................................................................................................................................35 JD.CAST.COL ................................................................................................................................37 JD.CAST.SUSP...............................................................................................................................39 JD.CAST.UPCAST .........................................................................................................................40 JD.CATCH ......................................................................................................................................41 JD.CONCUR...................................................................................................................................43 JD.EQ.ARR .....................................................................................................................................46 JD.EQ.UTA .....................................................................................................................................47 JD.EQ.UTC .....................................................................................................................................49 JD.FINRET......................................................................................................................................50 JD.IFBAD........................................................................................................................................51 JD.IFEMPTY ..................................................................................................................................53 JD.INF.AREC .................................................................................................................................54 JD.INST.TRUE ...............................................................................................................................56 JD.LIST.ADD..................................................................................................................................57 JD.LOCK.........................................................................................................................................58 JD.LOCK.EXC................................................................................................................................60 JD.LOCK.NOTIFY .........................................................................................................................62 JD.LOCK.SLEEP ............................................................................................................................64 JD.LOCK.WAIT .............................................................................................................................65 JD.NEXT.........................................................................................................................................67 JD.OVER.........................................................................................................................................68 JD.RC.EXPR.CHECK.....................................................................................................................70
  • 4. ii Contents JD.RC.EXPR.DEAD .......................................................................................................................71 JD.RC.EXPR.FIELD.......................................................................................................................73 JD.ST.POS.......................................................................................................................................75 JD.SYNC.DCL ................................................................................................................................77 JD.SYNC.IN....................................................................................................................................79 JD.THREAD.RUN ..........................................................................................................................80 JD.UMC.FINALIZE........................................................................................................................82 JD.UMC.WAIT ...............................................................................................................................83 JD.UN.FIELD..................................................................................................................................85 JD.UN.MET ....................................................................................................................................86 JD.UN.PMET ..................................................................................................................................87 JD.UNCAUGHT .............................................................................................................................89 JD.VNU.EXIT.................................................................................................................................90 JD.VNU.PAR ..................................................................................................................................92 JD.VNU.RE.....................................................................................................................................95 JD.VNU.SI ......................................................................................................................................96 JI.REC .............................................................................................................................................98 MNA.CAP.....................................................................................................................................100 MNA.CNS.....................................................................................................................................101 MNA.SUS .....................................................................................................................................103 NPD.COND...................................................................................................................................104 NPD.CONST .................................................................................................................................106 NPD.PAR ......................................................................................................................................108 NPDS.EXPR..................................................................................................................................109 NPDS.VAR ...................................................................................................................................114 NPE.FIELD ...................................................................................................................................117 NPE.LOCAL .................................................................................................................................119 NPE.MUST ...................................................................................................................................122 NPE.PASS.....................................................................................................................................124 NPE.RET.......................................................................................................................................126 REDUN.DEF.................................................................................................................................129 REDUN.EQ...................................................................................................................................130 REDUN.EQNULL ........................................................................................................................131 REDUN.NULL..............................................................................................................................132 REDUN.OP ...................................................................................................................................134 RI.IGNOREDCALL......................................................................................................................135 RI.IGNOREDNEW .......................................................................................................................137 RLK.FIELD...................................................................................................................................138 RLK.IN..........................................................................................................................................141 RLK.OUT......................................................................................................................................143 RLK.SQLCON ..............................................................................................................................147 RLK.SWT......................................................................................................................................149 RNU.CHECK ................................................................................................................................151 RNU.DEREF .................................................................................................................................153 RNU.NCHECK .............................................................................................................................156 RNU.NEW ....................................................................................................................................158 RNU.NULL...................................................................................................................................159 RNU.THIS.....................................................................................................................................161 RR.IGNORED...............................................................................................................................162 RTC.CALL....................................................................................................................................164 STRCON.LOOP............................................................................................................................166 SYNCH.NESTED .........................................................................................................................167 SYNCH.NESTEDS .......................................................................................................................168 UC.BOOLB...................................................................................................................................170 UC.BOOLS ...................................................................................................................................171
  • 5. Contents iii UC.STRS.......................................................................................................................................173 UC.STRV ......................................................................................................................................175 UIR.CONSTR ...............................................................................................................................176 UMC.EXIT....................................................................................................................................178 UMC.GC .......................................................................................................................................179 UMC.SYSERR..............................................................................................................................181 UMC.SYSOUT .............................................................................................................................182 UMC.TOSTRING .........................................................................................................................184 Chapter 3 Security vulnerabilities detected by Klocwork 187 Security vulnerabilities: Java ....................................................................................................................187 CMP.CLASS .................................................................................................................................187 SV.CLASS.FINAL........................................................................................................................188 SV.CLEXT.CLLOADER..............................................................................................................190 SV.CLEXT.POLICY.....................................................................................................................191 SV.CLLOADER............................................................................................................................192 SV.CLONE.NOFIN ......................................................................................................................194 SV.CLONE.SUP ...........................................................................................................................195 SV.CLONE.UNDEF .....................................................................................................................197 SV.CLONE.UNSAFE ...................................................................................................................198 SV.DATA.BOUND.......................................................................................................................200 SV.DATA.DB ...............................................................................................................................202 SV.DOS.ARRINDEX ...................................................................................................................205 SV.DOS.ARRSIZE .......................................................................................................................208 SV.DOS.RESOURCE ...................................................................................................................210 SV.DOS.TMPFILEDEL................................................................................................................212 SV.DOS.TMPFILEEXIT ..............................................................................................................213 SV.EMAIL ....................................................................................................................................215 SV.EXEC ......................................................................................................................................218 SV.EXEC.DIR...............................................................................................................................220 SV.EXEC.ENV .............................................................................................................................222 SV.EXPOSE.FIELD......................................................................................................................224 SV.EXPOSE.FIN ..........................................................................................................................226 SV.EXPOSE.IFIELD ....................................................................................................................228 SV.EXPOSE.MUTABLEFIELD ..................................................................................................230 SV.EXPOSE.RET .........................................................................................................................231 SV.EXPOSE.STORE ....................................................................................................................233 SV.FIELD.ACC ............................................................................................................................234 SV.FIELD.FIN ..............................................................................................................................236 SV.HTTP_SPLIT ..........................................................................................................................238 SV.IL.DEV....................................................................................................................................240 SV.IL.FILE....................................................................................................................................243 SV.INNERCLASS ........................................................................................................................244 SV.INT_OVF ................................................................................................................................246 SV.LOG_FORGING .....................................................................................................................247 SV.METHOD.ACC.......................................................................................................................249 SV.METHOD.FINAL ...................................................................................................................251 SV.METHOD.NONFINAL.GS ....................................................................................................252 SV.METHOD.NONPRIVATE .....................................................................................................254 SV.OBJ.INIT.CHECK ..................................................................................................................256 SV.OBJ.INIT.DEF ........................................................................................................................258 SV.OBJ.INIT.SET.........................................................................................................................259 SV.PASSWD.HC ..........................................................................................................................261 SV.PASSWD.HC.EMPTY............................................................................................................263
  • 6. iv Contents SV.PASSWD.PLAIN ....................................................................................................................265 SV.PATH ......................................................................................................................................267 SV.PATH.INJ................................................................................................................................269 SV.RACE.FILE.............................................................................................................................271 SV.RANDOM ...............................................................................................................................272 SV.SERIAL.INON ........................................................................................................................274 SV.SERIAL.NON .........................................................................................................................275 SV.SERIAL.NONDE ....................................................................................................................276 SV.SERIAL.SAFE ........................................................................................................................278 SV.SHARED.VAR........................................................................................................................280 SV.SOCKETS ...............................................................................................................................282 SV.SQL .........................................................................................................................................285 SV.SQL.DBSOURCE ...................................................................................................................287 SV.STRBUF.CLEAN....................................................................................................................290 SV.STRUTS.NOTRESET.............................................................................................................292 SV.STRUTS.NOTVALID.............................................................................................................293 SV.STRUTS.PRIVATE ................................................................................................................296 SV.STRUTS.RESETMET.............................................................................................................297 SV.STRUTS.STATIC ...................................................................................................................299 SV.STRUTS.VALIDMET ............................................................................................................302 SV.TAINT.....................................................................................................................................303 SV.TAINT.OERR .........................................................................................................................305 SV.TAINT_NATIVE ....................................................................................................................307 SV.TMPFILE ................................................................................................................................308 SV.UMC.EXIT..............................................................................................................................310 SV.UMC.JDBC .............................................................................................................................312 SV.UMC.THREADS ....................................................................................................................314 SV.UMD.MAIN ............................................................................................................................317 SV.USE.POLICY ..........................................................................................................................319 SV.XSS..........................................................................................................................................320 SV.XSS.DB ...................................................................................................................................322 SV.XSS.REF .................................................................................................................................324 Descriptions of sample secure coding rules..............................................................................................326 Chapter 4 Parameters 331 What are defect parameters?.....................................................................................................................331 Knowledge base parameters ..........................................................................................................331 Other parameters ...........................................................................................................................332 About parameter types ..............................................................................................................................332 Table of parameter types ...............................................................................................................332 Source parameters .........................................................................................................................333 Sink parameters .............................................................................................................................334 Prop parameters .............................................................................................................................334 Method parameters ........................................................................................................................336 Shared parameter groups ..........................................................................................................................337 $MUTABLE.OBJECTS ................................................................................................................337 $SV.FILEPROP.............................................................................................................................337 $SV.MAPPROP ............................................................................................................................337 $SV.MAPSTOP.............................................................................................................................338 $SV.NUMERICPROP...................................................................................................................338 $SV.NUMERICSTOP...................................................................................................................338 $SV.PASSWDSINKS ...................................................................................................................338 $SV.PROP.....................................................................................................................................338 $SV.SQL .......................................................................................................................................338
  • 7. Contents v $SV.SYSINFO ..............................................................................................................................338 $SV.TAINT.AWT.........................................................................................................................338 $SV.TAINT.DB ............................................................................................................................339 $SV.TAINT.DBSOURCE.............................................................................................................339 $SV.TAINT.FILES .......................................................................................................................339 $SV.TAINT.HTTP.ATTRS ..........................................................................................................339 $SV.TAINT.HTTP.PARAM.........................................................................................................339 $SV.TAINT.HTTP.REQ ...............................................................................................................339 $SV.TAINT.SCK ..........................................................................................................................339 $SV.TAINT.SOAP........................................................................................................................339 $SV.TAINT.SOURCES ................................................................................................................340 $SV.TAINT.STRUTS ...................................................................................................................340 $SV.TAINT.SWING.....................................................................................................................340 $SV.VALIDATE...........................................................................................................................340 $SV.XSS........................................................................................................................................340 $UNCHECKER.FIELD ................................................................................................................340 Index 341
  • 8.
  • 9. 7 CHAPTER 1 About this document This document describes the specific Java defects that can be detected by Klocwork. It also describes defect parameters.
  • 10.
  • 11. 9 CHAPTER 2 Code problems detected by Klocwork In This Chapter Code problems: Java ..........................................................9 Code problems: Java ARRAY This error is reported when the index of array access can be less than zero or greater than the size of the array. Defect Attributes Name Value Defect Code ARRAY Category Code Quality/ Reliability/ Exceptions Title Array index is out of range Message Array {0} index {1} is out of range {2} Enabled (default) true Severity (default) Critical (1) Applicable language Java Customizable false
  • 12. 10 Detected Java Defects Vulnerability and risk If this situation occurs in Java, it will throw an IndexArrayOutOfBounds runtime exception. Rather than try to catch this exception, use index checking. Index checking can work up to 100 times faster than catching the exception. Also, an uncaught exception can cause a thread to finish, which can lead to deadlock in multi-thread environments or the death of an application. If a general exception is caught, an application may be restored, but it may be missing functionality or diagnostics, or it may have a logic flaw. Mitigation and prevention Check for array boundaries. Make sure the check is correct, that is, that upperIndex string is less than array.length. Novice programmers usually make mistakes using array.length as index. Example_001: Java Code Sample: ... 15: /** 16: * This method prints file number j from directory dir or 17: * error message if index is out of bounds 18: */ 19: public static void getNthFile(File dir, int j) { 20: System.err.println("Info: getting file number " + j 21: + " from directory " + dir); 22: File results[] = dir.listFiles(); 23: if (results != null && results.length >= j && j >= 0) { 24: System.out.println(j + " file is " + results[j]); 25: } else { 26: System.err.println("Error: not enough files"); 27: } 28: } ... Output: com/klocwork/examples/Example_001.java:24:Critical(1): ARRAY: Array results index j is out of range upper bound: j(j<results.length) from j(j<=results.length) See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_001.java
  • 13. Chapter 2 Code problems detected by Klocwork 11 Example_002: Java Code Sample: ... 15: /** 16: * This method validates input string. String has field 17: * separated by :, original string, result string and 18: * extra info First field sould be equal second field to 19: * match 20: */ 21: static boolean validate(String text) { 22: StringTokenizer tok = new StringTokenizer(text, ":"); 23: String[] result = new String[tok.countTokens()]; 24: int count = 0; 25: while (tok.hasMoreTokens()) { 26: result[count] = tok.nextToken(); 27: count++; 28: } 29: if ((result == null) || (result.length < 2) 30: || (result[2] == null)) { return false; } 31: String toCompare = result[1]; 32: if (toCompare.equalsIgnoreCase(result[0])) return true; 33: return false; 34: } ... Output: com/klocwork/examples/Example_002.java:29:Critical(1): ARRAY: Array result index 2 is out of range upper bound: result.length(2<result.length) from result.length(2<=result.length) See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_002.java CMP.OBJ This warning appears if object references are compared rather than objects themselves. Error produced only if compared object has different types and none of them has explicit Object type.
  • 14. 12 Detected Java Defects Defect Attributes Name Value Defect Code CMP.OBJ Category Code Quality/ Reliability/ Suspicious practices Title Comparing objects with == Message Comparing objects {0} and {1} with == Enabled (default) false Severity (default) Review (9) Applicable language Java Customizable false 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 objects are unique in the program, that is, that they don't have the equals method defined or 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_010: Java Code Sample: ... 14: /** 15: * Check that person is John 25 miner 16: */ 17: Proffesional john = new Proffesional("John", 25, "miner"); 18: public boolean checkJohn(Person p) { 19: return p == john; 20: } ...
  • 15. Chapter 2 Code problems detected by Klocwork 13 Output: com/klocwork/examples/Example_010.java:19:Review(9): CMP.OBJ: Comparing objects this.john and p with == See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_010.java CMP.STR This warning appears if string references are compared rather than strings themselves for String type. Defect Attributes Name Value Defect Code CMP.STR Category Code Quality/ Reliability/ Suspicious practices Title Comparing strings with == Message Comparing strings {0} and {1} with == Enabled (default) true Severity (default) Investigate (5) Applicable language Java Customizable false 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.
  • 16. 14 Detected Java Defects Example_009: Java Code Sample: ... 14: /** 15: * Return symbolic name of operation 16: */ 17: public String nameOperation(String key) { 18: if (key == "++") return "PLUS"; 19: if (key == "--") return "MINUS"; 20: return "UNKNOWN"; 21: } 22: 23: // test start 24: public static void main(String[] args) { 25: Example_009 ex = new Example_009(); 26: ex.test("++"); 27: ex.test("+++"); 28: String one = "+"; 29: ex.test("+" + one); 30: ex.test(new String("++")); 31: } 32: private void test(String str) { 33: System.err.println("Name of " + str + "=" 34: + nameOperation(str)); 35: } 36: //test end ... Output: com/klocwork/examples/Example_009.java:18:Investigate(5): CMP.STR: "Comparing strings "++" and key with ==" com/klocwork/examples/Example_009.java:19:Investigate(5): CMP.STR: "Comparing strings "--" and key with ==" See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_009.java CMPF.FLOAT Error printed when two float or double value compared using equals operator (==).
  • 17. Chapter 2 Code problems detected by Klocwork 15 Defect Attributes Name Value Defect Code CMPF.FLOAT Category Code Quality/ Reliability/ Suspicious practices Title Equality checks on floating point types should be avoided Message Equality checks on floating point types should be avoided Enabled (default) true Severity (default) Warning (6) Applicable language Java Customizable false 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).
  • 18. 16 Detected Java Defects Example_023: Java Code Sample: ... 14: /** 15: * Calculates define integral 16: */ 17: public static double integral(MyFunction f, double x1, 18: double x2) { 19: double x = x1; 20: double result = 0; 21: double step = (x2 - x1) / 700; 22: while (x != x2) { // should use (x <= x2) 23: result = result + f.valueFor(x) * step; 24: x = x + step; 25: } 26: return result; 27: } ... Output: com/klocwork/examples/Example_023.java:22:Warning(6): CMPF.FLOAT: Equality checks on floating point types should be avoided See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_023.java COV.CMP Error exists when method compareTo declared with signature different than int compareTo(Object).
  • 19. Chapter 2 Code problems detected by Klocwork 17 Defect Attributes Name Value Defect Code COV.CMP Category Code Quality/ Reliability/ Suspicious practices Title Method compareTo() should have signature int compareTo(Object) Message Method compareTo() should have signature int compareTo(Object) Enabled (default) true Severity (default) Warning (6) Applicable language Java Customizable false Vulnerability and risk Intent was probably to implement interface method of Comarible 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 Cloneable, declare int compareTo(Object) method. Example_024: Java Code Sample: ... 18: String name; 19: int compareTo(MyClass a) { 20: return name.compareTo(a.name); 21: } ... Output: com/klocwork/examples/Example_024.java:20:Warning(6): COV.CMP: Method compareTo() should have signature int compareTo(Object) See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_024.java
  • 20. 18 Detected Java Defects 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. Defect Attributes Name Value Defect Code ECC.EMPTY Category Code Quality/ Reliability/ Error Handling Title Empty catch clause Message Empty catch clause Enabled (default) true Severity (default) Investigate (5) Applicable language Java Customizable false Example_305: Java Code Sample: ... 20: public void openFile(String name) { 21: try { 22: FileInputStream is = new FileInputStream(name); 23: // read file ... 24: } catch (FileNotFoundException e) { 25: // TODO Auto-generated catch block 26: } 27: } ... Output: com/klocwork/examples/Example_305.java:24:Investigate(5): ECC.EMPTY: Empty catch clause See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_305.java
  • 21. Chapter 2 Code problems detected by Klocwork 19 EHC.EQ 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 a equals(). This may cause a problem with some collections that expect that equal objects to have equal hashcodes. Defect Attributes Name Value Defect Code EHC.EQ Category Code Quality/ Reliability/ Suspicious practices Title Class defines hashCode() but does not define equals() Message Class defines hashCode() but does not define equals() Enabled (default) true Severity (default) Warning (6) Applicable language Java Customizable false Example_307: Java Code Sample: ... 17: public class MyClass { 18: private int seed; 19: public MyClass(int seed) { 20: this.seed = seed; 21: } 22: public int hashCode() { 23: return seed; 24: } 25: // no equals(Object o) method defined 26: } ...
  • 22. 20 Detected Java Defects Output: com/klocwork/examples/Example_307.java:23:Warning(6): EHC.EQ: Class defines hashCode() but does not define equals() See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_307.java EHC.HASH 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. Defect Attributes Name Value Defect Code EHC.HASH Category Code Quality/ Reliability/ Suspicious practices Title Class defines equals() but does not define hashCode() Message Class defines equals() but does not define hashCode() Enabled (default) true Severity (default) Warning (6) Applicable language Java Customizable false
  • 23. Chapter 2 Code problems detected by Klocwork 21 Example_306: Java Code Sample: ... 17: public class MyClass { 18: private int seed; 19: public MyClass(int seed) { 20: this.seed = seed; 21: } 22: public boolean equals(Object o) { 23: return (o instanceof MyClass) 24: && ((MyClass) o).seed == seed; 25: } 26: // no hashCode method defined 27: } ... Output: com/klocwork/examples/Example_306.java:23:Warning(6): EHC.HASH: Class defines equals() but does not define hashCode() See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_306.java 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.
  • 24. 22 Detected Java Defects Defect Attributes Name Value Defect Code ESCMP.EMPTYSTR Category Code Quality/ Efficiency Title Inefficient empty string comparison Message Comparing strings {0} and {1} using equals(), instead of length() == 0 Enabled (default) false Severity (default) Suggestion (7) Applicable language Java Customizable false Example_003: Java Code Sample: ... 16: public boolean emptyCheck1() { 17: if (s.equals("")) return true; 18: return false; 19: } 20: public boolean emptyCheck2() { 21: if ("".equals(s)) return true; 22: return false; 23: } 24: // fixed code 25: public boolean emptyCheck3() { 26: if (s.length() == 0) return true; 27: return false; 28: } ... Output: com/klocwork/examples/Example_003.java:17:Suggestion(7): ESCMP.EMPTYSTR: "Comparing strings "" and this.s using equals(), instead of length() == 0" com/klocwork/examples/Example_003.java:21:Suggestion(7): ESCMP.EMPTYSTR: "Comparing strings this.s and "" using equals(), instead of length() == 0"
  • 25. Chapter 2 Code problems detected by Klocwork 23 See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_003.java 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 good error recovery. Defect Attributes Name Value Defect Code EXC.BROADTHROWS Category Code Quality/ Reliability/ Error Handling Title Method has an overly broad throws declaration Message The {0} method throws a generic exception {1} Enabled (default) false Severity (default) Style (8) Applicable language Java Customizable true 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. It raises the risk of improperly handled problems. 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.
  • 26. 24 Detected Java Defects Example_300: Java Code Sample: ... 23: public void processFile(String fileName) throws Exception { 24: InputStream is = new FileInputStream(fileName); 25: // do something 26: } 27: public int calculateSum(Collection data) throws Throwable { 28: int sum = 0; 29: for (Iterator it = data.iterator(); it.hasNext();) { 30: String element = (String) it.next(); 31: int i = Integer.parseInt(element); 32: sum += i; 33: } 34: return sum; 35: } ... Output: com/klocwork/examples/Example_300.java:24:Style(8): EXC.BROADTHROWS: The processFile method throws a generic exception java.lang.Exception com/klocwork/examples/Example_300.java:28:Style(8): EXC.BROADTHROWS: The calculateSum method throws a generic exception java.lang.Throwable See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_300.java FIN.EMPTY Empty finalize() method. FIN code problems have a questionable implementation of finalize method(). In this case, there is an empty finalize() method.
  • 27. Chapter 2 Code problems detected by Klocwork 25 Defect Attributes Name Value Defect Code FIN.EMPTY Category Code Quality/ Efficiency Title Empty finalize() method should be removed Message Empty finalize() method should be removed Enabled (default) true Severity (default) Suggestion (7) Applicable language Java Customizable false Example_004: Java Code Sample: ... 15: 16: public void test3() { 17: new Example_004() { 18: protected void finalize() throws Throwable { 19: 20: } 21: }; 22: } 23: // fixed code 24: public void test1() { 25: new Example_004() { 26: }; 27: } ... Output: com/klocwork/examples/Example_004.java:20:Suggestion(7): FIN.EMPTY: Empty finalize() method should be removed See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_004.java
  • 28. 26 Detected Java Defects FIN.NOSUPER Implementation of the finalize() method should call super.finalize(). FIN code problems have a questionable implementation of finalize method(). In this case there is a finalize() method implementation that does not call super.finalize(). Defect Attributes Name Value Defect Code FIN.NOSUPER Category Code Quality/ Reliability/ Suspicious practices Title Implementation of the finalize() method should call super.finalize() Message Implementation of the finalize() method should call super.finalize() Enabled (default) true Severity (default) Unexpected (4) Applicable language Java Customizable false 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_308: Java Code Sample: ... 16: public class Example_308 { 17: /* 18: * no super.finalize() was called 19: */ 20: public void finalize() { 21: System.err.println("finalized"); 22: } 23: } ...
  • 29. Chapter 2 Code problems detected by Klocwork 27 Output: com/klocwork/examples/Example_308.java:21:Unexpected(4): FIN.NOSUPER: Implementation of the finalize() method should call super.finalize() See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_308.java 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. Defect Attributes Name Value Defect Code FSC.PRT Category Code Quality/ Maintainability Title Class and its superclass have protected fields with the same name Message Class {0} hides field {2} of superclass {1} by declaring a protected or package-private field with the same name Enabled (default) false Severity (default) Review (9) Applicable language Java Customizable false
  • 30. 28 Detected Java Defects Example_309: Java Code Sample: ... 17: public class SuperClass { 18: protected int index; 19: // ... 20: } 21: public class SubClass extends SuperClass { 22: protected int index; 23: // ... 24: } ... Output: com/klocwork/examples/Example_309.java:21:Review(9): FSC.PRT: Class com.klocwork.examples.Example_309$SubClass and its superclass com.klocwork.examples.Example_309$SuperClass have protected fields with the same name: index See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_309.java 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.
  • 31. Chapter 2 Code problems detected by Klocwork 29 Defect Attributes Name Value Defect Code FSC.PRV Category Code Quality/ Maintainability Title Class and its superclass have private fields with the same name Message Class {0} hides field {2} of superclass {1} by declaring a private field with the same name Enabled (default) false Severity (default) Review (9) Applicable language Java Customizable false Example_310: Java Code Sample: ... 17: public class SuperClass { 18: private int index; 19: // ... 20: } 21: public class SubClass extends SuperClass { 22: private int index; 23: // ... 24: } ... Output: com/klocwork/examples/Example_310.java:21:Review(9): FSC.PRV: Class com.klocwork.examples.Example_310$SubClass and its superclass com.klocwork.examples.Example_310$SuperClass have private fields with the same name: index See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_310.java
  • 32. 30 Detected Java Defects 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. Defect Attributes Name Value Defect Code FSC.PUB Category Code Quality/ Maintainability Title Class and its superclass have public fields with the same name Message Class {0} hides field {2} of superclass {1} by declaring a public field with the same name Enabled (default) false Severity (default) Warning (6) Applicable language Java Customizable false Example_311: Java Code Sample: ... 17: public class SuperClass { 18: public int index; 19: // ... 20: } 21: public class SubClass extends SuperClass { 22: public int index; 23: // ... 24: } ... Output: com/klocwork/examples/Example_311.java:21:Warning(6): FSC.PUB: Class com.klocwork.examples.Example_311$SubClass and its superclass com.klocwork.examples.Example_311$SuperClass have public fields with the same name: index
  • 33. Chapter 2 Code problems detected by Klocwork 31 See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_311.java 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. Defect attributes Name Value Defect Code JD.BITCMP Category Code Quality/ Reliability/ Suspicious practices Title Using non short-circuit logic in expression Message Questionable use of bit operation '{0}' in expression. Did you mean '{1}'? Enabled (default) true Severity (default) Severe (2) Applicable language Java 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.
  • 34. 32 Detected Java Defects Example_043: Java Code Sample: ... 14: static void check(int arr[]) { 15: if (arr!=null & arr.length!=0) { 16: foo(); 17: } 18: return; 19: } ... Output: com/klocwork/examples/Example_043.java:15:Severe(2): JD.BITCMP: Questionable use of bit operation '&' in expression. Did you mean '&&'? See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_04 3.java See also: JD.BITMASK (on page 32) JD.BITR (on page 35) 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.
  • 35. Chapter 2 Code problems detected by Klocwork 33 Defect attributes Name Value Defect Code JD.BITMASK Category Code Quality/ Reliability/ Suspicious practices Title Possible error in bit operations Message Incompatible bitmasks '{0}' and '{1}' cause the expression to always be constant. Enabled (default) true Severity (default) Severe (2) Applicable language Java 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_041: Java Code Sample: ... 16: final static int FLAG = 0x01; 17: static boolean checkMask(int a) { 18: // mistyped, should be & 19: if ((a |FLAG) == 0) return true; 20: return false; 21: } ... Output: com/klocwork/examples/Example_041.java:19:Severe(2): JD.BITMASK: Incompatible bitmasks '0x1' and '0x0' cause the expression to always be constant.
  • 36. 34 Detected Java Defects See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_04 1.java See also: JD.BITCMP (on page 31) JD.BITR (on page 35) JD.BTO.SBS The JD.BTO.SBS checker triggers an error if a byte type is used with shift operations or with an OR bit operator. Usually, it is an error, because usually, the byte is perceived as unsigned and, if it contains a number greater than 128, it will be negative and the OR operator will produce unexpected results. Defect attributes Name Value Defect Code JD.BTO.SBS Category Code Quality/ Reliability/ Suspicious practices Title Bit operation used with signed value Message Bit operation '{1}' used with signed byte value of '{0}' Enabled (default) true Severity (default) Warning (6) Applicable language Java Vulnerability and risk JD.BTO.SBS defects result in incorrect program behavior. Mitigation and prevention Manually convert the unsigned value to signed and cast to the int, that is, if you want to store '160', make sure the int contains '160', not -96, as would be the case with an implicit cast.
  • 37. Chapter 2 Code problems detected by Klocwork 35 Example_040: Java Code Sample: ... 16: static int ipToInt(byte[] inet) { 17: int l = 0; 18: for (int i = 0; i < inet.length; i++) { 19: final byte b = inet[i]; 20: l=l<<8 | b; 21: } 22: return l; 23: } 24: // fixed 25: static int ipToInt2(byte[] inet) { 26: int l = 0; 27: for (int i = 0; i < inet.length; i++) { 28: final byte b = inet[i]; 29: int x = b<0?256+b:b; 30: l=l<<8 | x; 31: } 32: return l; 33: } ... Output: com/klocwork/examples/Example_040.java:20:Warning(6): JD.BTO.SBS: Bit operation '|' used with signed byte value of 'b' See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_04 0.java 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.
  • 38. 36 Detected Java Defects Defect attributes Name Value Defect Code JD.BITR Category Code Quality/ Reliability/ Suspicious practices Title Redundant expression Message Expression '{0}' is always '{1}'. Is there a typo? Enabled (default) true Severity (default) Severe (2) Applicable language Java 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_042: Java Code Sample: ... 14: static void check(boolean hasFields) { 15: if (hasFields = true) { 16: foo(); 17: } 18: return; 19: } ... Output: com/klocwork/examples/Example_042.java:15:Severe(2): JD.BITR: Expression '(...)' is always '1'. Is it a typo? See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_04 2.java
  • 39. Chapter 2 Code problems detected by Klocwork 37 See also: JD.BITCMP (on page 31) JD.BITMASK (on page 32) JD.RC.EXPR.CHECK (on page 70) JD.RC.EXPR.DEAD (on page 71) 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. Defect attributes Name Value Defect Code JD.CAST.COL Category Code Quality/ Reliability/ Exceptions Title Possible ClassCastException for collection Message Suspicious cast to '{0}' of collection element. Put the object into the collection as '{1}'. Enabled (default) true Severity (default) Error (3) Applicable language Java 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.
  • 40. 38 Detected Java Defects Example_071: Java Code Sample: ... 19: class Filter { 20: HashMap len=new HashMap(); 21: void fill(File dir){ 22: File[] list = dir.listFiles(); 23: for (int i = 0; i < list.length; i++) { 24: File file = list[i]; 25: len.put(file,new Long(file.length())); 26: } 27: } 28: int getLength(String file){ 29: Long l = (Long) len.get(file); 30: if (l!=null) return l.intValue(); 31: return 0; 32: } 33: } ... Output: com/klocwork/examples/Example_071.java:29:Error(3): JD.CAST.COL: Suspicious cast to 'java.lang.String' of collection element. Put the object into the collection as 'java.io.File'. -> get at com/klocwork/examples/Example_071.java:29 -> put at com/klocwork/examples/Example_071.java:25 See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_07 1.java See also: JD.CAST.UPCAST (on page 40) JD.CATCH (on page 41)
  • 41. Chapter 2 Code problems detected by Klocwork 39 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.) Defect attributes Name Value Defect Code JD.CAST.SUSP Category Code Quality/ Reliability/ Exceptions Title Possible ClassCastException for different types Message Suspicious cast of '{0}' from '{1}' to '{2}', {3}. Enabled (default) true Severity (default) Unexpected (4) Applicable language Java 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_069: Java Code Sample: ... 15: void setValue(Object a, Object value) { 16: if (a instanceof String) { 17: StringBuffer b = (StringBuffer) a; 18: b.append("="); 19: b.append(value); 20: } 21: } ...
  • 42. 40 Detected Java Defects Output: com/klocwork/examples/Example_069.java:17:Unexpected(4): JD.CAST.SUSP: Suspicious cast of 'a' from 'java.lang.String' to 'java.lang.StringBuffer', where types are unrelated. on trace 16 17 See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_06 9.java See also: JD.CAST.UPCAST (on page 40) 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. Defect attributes Name Value Defect Code JD.CAST.UPCAST Category Code Quality/ Reliability/ Exceptions Title Possible ClassCastException for subtypes Message Suspicious cast of '{0}' to '{2}', where '{2}' is a subtype of '{1}'. This object can hold other subtypes of '{1}' which can cause a ClassCastException. Enabled (default) true Severity (default) Warning (6) Applicable language Java 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.
  • 43. Chapter 2 Code problems detected by Klocwork 41 Example_070: Java Code Sample: ... 19: void setValue(Object a, Object value) { 20: if (a instanceof Map) { 21: HashMap b = (HashMap) a; 22: b.put(value, ""); 23: } else if (a instanceof List) { 24: List b = (List) a; 25: b.add(value); 26: } 27: } ... Output: com/klocwork/examples/Example_070.java:21:Warning(6): JD.CAST.UPCAST: Suspicious cast of 'a' to 'java.util.HashMap', where 'java.util.HashMap' is subtype of 'java.util.Map'. This object can hold other subtypes of 'java.util.Map' which can cause ClassCastException. on trace 20 21 See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_07 0.java See also: JD.CAST.SUSP (on page 39) JD.CATCH Klocwork reports a JD.CATCH defect 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.
  • 44. 42 Detected Java Defects Defect attributes Name Value Defect Code JD.CATCH Category Code Quality/ Reliability/ Error Handling Title Catching runtime exception Message Catching '{0}' explicitly is usually a bad practice. Use preventive checks on data instead. Enabled (default) true Severity (default) Investigate (5) Applicable language Java 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_058: Java Code Sample: ... 16: // horrible abuse of exceptions. Don't ever do this! 17: void foo(int arr[]) { 18: try { 19: int i = 0; 20: while (true) { 21: arr[i++]--; 22: } 23: } catch (ArrayIndexOutOfBoundsException e) { 24: return; 25: } 26: 27: } ...
  • 45. Chapter 2 Code problems detected by Klocwork 43 Output: com/klocwork/examples/Example_058.java:23:Investigate(5): JD.CATCH: Catching 'java.lang.ArrayIndexOutOfBoundsException' explicitly is usually a bad practice. Use preventive checks on data instead. See complete code sample: <Klocwork installation directory>/samples/inforcejava/com/klocwork/examples/Example_05 8.java References Effective Java, Item 39. 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. Defect attributes Name Value Defect Code JD.CONCUR Category Code Quality/ Reliability/ Exceptions Title Possible ConcurrentModificationException Message Possible 'ConcurrentModificationException' can be thrown by method '{0}' while iterating over '{1}'. You cannot remove a collection element while iterating over the same collection. Enabled (default) true Severity (default) Critical (1) Applicable Java language Vulnerability and risk On the following invocation of the "next" method, the code will throw a ConcurrentModificationException.