FindBugs Report安全代码检查工具问题解析

来源:互联网 发布:手机淘宝举报有用吗 编辑:程序博客网 时间:2024/05/19 11:49

1、LI_LAZY_INIT_UPDATE_STATIC:Incorrect lazy initialization and update of static field

Thismethod contains an unsynchronized lazy initialization of a static field. Afterthe field is set, the object stored into that location is further updated oraccessed. The setting of the field is visible to other threads as soon as it isset. If the futher accesses in the method that set the field serve toinitialize the object, then you have a veryseriousmultithreading bug, unless something else prevents any otherthread from accessing the stored object until it is fully initialized.

原因分析:

该方法的初始化中包含了一个迟缓初始化的静态变量。你的方法引用了一个静态变量,估计是类静态变量,那么多线程调用这个方法时,你的变量就会面临线程安全的问题了,除非别的东西阻止任何其他线程访问存储对象从直到它完全被初始化。

解决方法:给该方法加上synchronized同步锁,并且给有调用到该静态变量的方法也加上synchronized同步锁。

2RR_NOT_CHECKED: Method ignores results ofInputStream.read()

This method ignores the return value ofone of the variants of java.io.InputStream.read() which can returnmultiple bytes.  If the return value is not checked, the caller will notbe able to correctly handle the case where fewer bytes were read than thecaller requested.  This is a particularly insidious kind of bug, becausein many programs, reads from input streams usually do read the full amount ofdata requested, causing the program to fail only sporadically.

原因分析:

InputStream.read方法忽略返回的多个字符,如果对结果没有检查就没法正确处理用户读取少量字符请求的情况。

解决方法:定义一个变量接收该方法返回值,如while((number = is.read(bs))!= -1) {}

3、RV_RETURN_VALUE_IGNORED_BAD_PRACTICE:Method ignores exceptional return value

This methodreturns a value that is not checked. The return value should be checked sinceit can indicate an unusual or unexpected function execution. For example, the File.delete() methodreturns false if the file could not be successfully deleted (rather thanthrowing an Exception). If you don't check the result, you won't notice if themethod invocation signals unexpected behavior by returning an atypical returnvalue.

原因分析:方法忽略返回值的异常信息

解决方法:

原代码:if (file.exists()) {

    file.delete();

   }

修改后的代码:try {

     file.delete();

    }catch(SecurityException e){

     Utils.logger.info(e);

    }catch(NullPointerException e){

     Utils.logger.info(e);

    }

4、SE_BAD_FIELD:Non-transient non-serializable instance field in serializable class

This Serializableclass defines a non-primitive instance field which is neither transient,Serializable, or java.lang.Object, and does not appear to implement theExternalizable interfaceor the readObject() and writeObject() methods. Objects of this class will not be deserialized correctly if a non-Serializableobject is stored in this field.

原因分析:序列化的类里面定义了一个非序列化的字段

解决方法:给该字段加上transient表明这是一个序列化字段

5、NP_NULL_ON_SOME_PATH_EXCEPTION:Possible null pointer dereference in method on exception path

Areference value which is null on some exception control path is dereferencedhere.  This may lead to a NullPointerException when the code isexecuted.  Note that because FindBugs currently does not prune infeasibleexception paths, this may be a false warning.

Alsonote that FindBugs considers the default case of a switch statement to be anexception path, since the default case is often infeasible.

原因分析:有些代码可能会发生空指针异常

解决方法:进行判空就好了

6、NP_NULL_PARAM_DEREF:Method call passes null for nonnull parameter

Thismethod call passes a null value for a nonnull method parameter. Either theparameter is annotated as a parameter that should always be nonnull, oranalysis has shown that it will always be dereferenced

原因分析:对参数为空的未进行处理

解决方法:进行判空就好了

7、NP_NULL_ON_SOME_PATH:Possible null pointer dereference

Thereis a branch of statement that, if executed, guarantees that a nullvalue will be dereferenced, which would generate a NullPointerException whenthe code is executed. Of course, the problem might be that the branch orstatement is infeasible and that the null pointer exception can't ever beexecuted; deciding that is beyond the ability of FindBugs

原因分析:可能存在空的引用

解决方法:要么判空,要么注释掉,如System.out等

8、NP_UNWRITTEN_FIELD:Read of unwritten field

Theprogram is dereferencing a field that does not seem to ever have a non-nullvalue written to it. Dereferencing this value will generate a null pointerexception.

原因分析:此字段是永远不会写入值,如果不需要的话就删除掉

解决方法:要么复制,要么注释掉

9、DMI_INVOKING_TOSTRING_ON_ARRAY:Invocation of toString on an array

Thecode invokes toString on an array, which will generate a fairly useless resultsuch as [C@16f0472. Consider using Arrays.toString to convert the array into areadable String that gives the contents of the array. See Programming Puzzlers,chapter 3, puzzle 12.

原因分析:该代码调用上数组的toString()方法,产生的结果形如[@ 16f0472并不能显示数组的真实内容。

解决方法:用Arrays.toString方法或者new String(X,“gbk”)来转换

10、UWF_UNWRITTEN_FIELD:Unwritten field

Thisfield is never written.  All reads of it will return the default value.Check for errors (should it have been initialized?), or remove it if it isuseless

原因分析:该字段从未被赋值过

解决办法:要么注释掉该字段,要么给它初始化

11、RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE:Redundant nullcheck of value known to be non-null

Thismethod contains a redundant check of a known non-null value against theconstant null.

原因分析:方法中包含没有检查可能为空的地方

解决办法:先检查是否为空再进行相关操作

12、EI_EXPOSE_REP:May expose internal representation by returning reference to mutable object

Returninga reference to a mutable object value stored in one of the object's fieldsexposes the internal representation of the object.  If instances are accessed by untrusted code,and unchecked changes to the mutable object would compromise security or otherimportant properties, you will need to do something different. Returning a newcopy of the object is better approach in many situations.

原因分析:返回一个易变对象引用并把它保存在对象字段中时会暴露对象内部的字段描述,如果接受不守信任的代码访问或者没有检查就去改变易变对象的会涉及对象的安全和其他重要属性的安全。返回一个对象的新副本,在很多情况下更好的办法。在编写JavaBean时,如果类内部的成员变量为一个对象类型,就有可能产生这种情况。

解决方法:

源代码:

publicclass StudentBean

{

       private Date addDate;

       public Date getAddDate()

       {

              return addDate;

       }

}

修改后的代码:

publicclass StudentBean

{

       private Date addDate;

 

       public Date getAddDate()

       {

              if (addDate == null)

              {

                     return null;

              }

              return (Date)addDate.clone();

       }

}

13、EI_EXPOSE_REP2:May expose internal representation by incorporating reference to mutable object

Thiscode stores a reference to an externally mutable object into the internalrepresentation of the object.  Ifinstances are accessed by untrusted code, and unchecked changes to the mutableobject would compromise security or other important properties, you will needto do something different. Storing a copy of the object is better approach inmany situations.

原因分析:此代码把外部可变对象引用存储到对象的内部表示。如果实例受到不信任的代码的访问和没有检查的变化危及对象和重要属性的安全。存储一个对象的副本,在很多情况下是更好的办法。

解决方法:

源代码:

publicclass StudentBean

{

       private Date addDate;

       public void setAddDate(Date addDate)

       {

              this.addDate = addDate;

       }

}

修改后的代码:

publicclass StudentBean

{

       private Date addDate;

       public void setAddDate(Date addDate)

       {

              if (addDate == null)

              {

                     this.addDate = null;

              } else {

                     this.addDate =(Date)addDate.clone();

              }

       }

}

14、IS2_INCONSISTENT_SYNC:Inconsistent synchronization

Thefields of this class appear to be accessed inconsistently with respect tosynchronization.  This bug reportindicates that the bug pattern detector judged that

 

Theclass contains a mix of locked and unlocked accesses,

Atleast one locked access was performed by one of the class's own methods, and

Thenumber of unsynchronized field accesses (reads and writes) was no more than onethird of all accesses, with writes being weighed twice as high as reads

Atypical bug matching this bug pattern is forgetting to synchronize one of themethods in a class that is intended to be thread-safe.

 

Youcan select the nodes labeled "Unsynchronized access" to show the codelocations where the detector believed that a field was accessed withoutsynchronization.

 

Notethat there are various sources of inaccuracy in this detector; for example, thedetector cannot statically detect all situations in which a lock is held.  Also, even when the detector is accurate indistinguishing locked vs. unlocked accesses, the code in question may still becorrect.

原因分析:没有同步

解决方法:涉及到该字段的方法都加上synchronized

15、OBL_UNSATISFIED_OBLIGATION:Method may fail to clean up stream or resource

Thismethod may fail to clean up (close, dispose of) a stream, database object, orother resource requiring an explicit cleanup operation.

 

Ingeneral, if a method opens a stream or other resource, the method should use atry/finally block to ensure that the stream or resource is cleaned up beforethe method returns.

 

Thisbug pattern is essentially the same as the OS_OPEN_STREAM andODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (andhopefully better) static analysis technique. We are interested is gettingfeedback about the usefulness of this bug pattern.

原因分析:这种方法可能无法清除(关闭,处置)一个流,数据库对象,或其他资源需要一个明确的清理行动。一般来说,如果一个方法打开一个流或其他资源,该方法应该使用try /finally块来确保在方法返回之前流或资源已经被清除了。这种错误模式基本上和OS_OPEN_STREAM和ODR_OPEN_DATABASE_RESOURCE错误模式相同,但是是在不同在静态分析技术。

解决方法:流的关闭都写在finally里面

16、DM_NUMBER_CTOR:Method invokes inefficient Number constructor; use static valueOf instead

Usingnew Integer(int) is guaranteed to always result in a new object whereasInteger.valueOf(int) allows caching of values to be done by the compiler, classlibrary, or JVM. Using of cached values avoids object allocation and the codewill be faster.Values between -128 and 127 are guaranteed to have correspondingcached instances and using valueOf is approximately 3.5 times faster than usingconstructor. For values outside the constant range the performance of bothstyles is the same.Unless the class must be compatible with JVMs predating Java1.5, use either autoboxing or the valueOf() method when creating instances ofLong, Integer, Short, Character, and Byte.

原因分析:使用new Integer(int)方法总是会创建一个新的对象,然而使用Integer.valueOf(int)方法可以把值保存在编辑器或者classlibrary、JVM中。使用存储值的方式来避免对象的分配可以或得更好的代码性能除非类必须符合Java1.5以前的JVM,否则请使用自动装箱或valueOf()方法创建Long, Integer,Short, Character, Byte实例。

解决方法:Integer创建时把new Integer改成Integer.valueOf

17、DM_NEXTINT_VIA_NEXTDOUBLE:Use the nextInt method of Random rather than nextDouble to generate a randominteger if r is a java.util.Random, you can generate a randomnumber from 0 to n-1 using r.nextInt(n), rather thanusing (int)(r.nextDouble() * n).

原因分析:如果r是一个java.util.Random对象,你可以使r.nextInt(n)生成一个0到n-1之前的随机数,而不是使用(int)(r.nextDouble()* n)

解决方法:分析已经说的很明显了

18、SBSC_USE_STRINGBUFFER_CONCATENATION:Method concatenates strings using + in a loop

Themethod seems to be building a String using concatenation in a loop. In eachiteration, the String is converted to a StringBuffer/StringBuilder, appendedto, and converted back to a String. This can lead to a cost quadratic in thenumber of iterations, as the growing string is recopied in each iteration.

Better performance can be obtained by using aStringBuffer (or StringBuilder in Java 1.5) explicitly.

原因分析:字符串操作问题

解决方法:

For example:

  // This is bad

  String s = "";

  for (int i = 0; i <field.length; ++i) {

    s = s + field[i];

  }

 

  // This is better

  StringBuffer buf = newStringBuffer();

  for (int i = 0; i <field.length; ++i) {

    buf.append(field[i]);

  }

  String s = buf.toString();

19、SS_SHOULD_BE_STATIC:Unread field: should this field be static?

Thisclass contains an instance final field that is initialized to a compile-timestatic value. Consider making the field static.

原因分析:类中所包含的final属性字段在编译器中初始化为静态的值。考虑在定义时就把它定义为static类型的。

解决方法:final的字段可以定义为static类型

20、URF_UNREAD_FIELD:Unread field

Thisfield is never read.  Consider removing it from the class.

原因分析:字段没有被使用过,可以注释掉

解决方法:删掉或者注释掉

21、DB_DUPLICATE_BRANCHES:Method uses the same code for two branches

Thismethod uses the same code to implement two branches of a conditional branch.Check to ensure that this isn't a coding mistake

原因分析:两个不同分支使用了相同代码

解决方法:代码优化合并

22、DLS_DEAD_LOCAL_STORE:Dead store to local variable

Thisinstruction assigns a value to a local variable, but the value is not read orused in any subsequent instruction. Often, this indicates an error, because thevalue computed is never used.Note that Sun's javac compiler often generatesdead stores for final local variables. Because FindBugs is a bytecode-basedtool, there is no easy way to eliminate these false positives.

原因分析:该指令为局部变量赋值,但在其后的没有对她做任何使用。通常,这表明一个错误,因为值从未使用过。

解决方法:代码优化注释掉

23、IM_BAD_CHECK_FOR_ODD:Check for oddness that won't work for negative numbers

Thecode uses x % 2 == 1 to check to see if a value is odd, but this won't work fornegative numbers (e.g., (-5) % 2 == -1). If this code is intending to check foroddness, consider using x & 1 == 1, or x % 2 != 0.

原因分析:如果row是负奇数,那么row % 2 ==-1

解决方法:如上所示

24、NP_DEREFERENCE_OF_READLINE_VALUE:Dereference of the result of readLine() without nullcheck

Theresult of invoking readLine() is dereferenced without checking to see if theresult is null. If there are no more lines of text to read, readLine() willreturn null and dereferencing that will generate a null pointer exception.

原因分析:对readLine()的结果值没有进行判空操作就去重新赋值,这样的操作可以会抛出空指针异常

解决方法:

对readLine()的结果值没有进行判空操作就去重新赋值,这样的操作可以会抛出空指针异常

解决方法:当要对readLine方法进行操作的时候判个空先

25、REC_CATCH_EXCEPTION:Exception is caught when Exception is not thrown

Thismethod uses a try-catch block that catches Exception objects, but Exception isnot thrown within the try block, and RuntimeException is not explicitly caught.It is a common bug pattern to say try { ... } catch (Exception e) { something }as a shorthand for catching a number of types of exception each of whose catchblocks is identical, but this construct also accidentally catchesRuntimeException as well, masking potential bugs.

原因分析:在try/catch块中捕获异常,但是异常没有在try语句中抛出而RuntimeException又没有明确的被捕获。这么写会无意中把RuntimeException也捕获了,有可能导致潜在的bug。 JVM对RuntimeException有统一的捕获机制,让JVM来处理。

解放方法:只需要捕获具体的异常信息即可,嫑把所有异常都抛给Exception,java并不推荐这么做。如:

源代码:catch (Exception e) {

               return l8Date;

           }

修改后的代码:catch(UnsupportedEncodingException e){

   Utils.logger.error("积分明细查询,调用1017报文接口异常!");

    returnUtils.makeErrorResponse("");

   }

26、ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD: Write to staticfield from instance method

Thisinstance method writes to a static field. This is tricky to get correct ifmultiple instances are being manipulated, and generally bad practice.

原因分析:静态私有的成员变量不能在public类里面直接赋值,最好是通过get/set方法进行操作。一般常见于常量类,直接通过类名.常量名获取的方式违背了封装的原则,findbugs不提倡使用,而如果将常量改成静态成员变量,又因为spring不支持静态注入导致不能实现,解决方法是非静态的setter调用静态的setter方法给静态成员变量赋值。

解决方法:通过get/set方法提供操作


0 0
原创粉丝点击