静态代码分析工具简介

什么是静态代码分析

静态代码分析是指无需运行被测代码,仅通过分析或检查源程序的语法、结构、过程、接口等来检查程序的正确性,找出代码隐藏的错误和缺陷,如参数不匹配,有歧义的嵌套语句,错误的递归,非法计算,可能出现的空指针引用等等。

在软件开发过程中,静态代码分析往往先于动态测试之前进行,同时也可以作为制定动态测试用例的参考。统计证明,在整个软件开发生命周期中,30% 至 70% 的代码逻辑设计和编码缺陷是可以通过静态代码分析来发现和修复的。

但是,由于静态代码分析往往要求大量的时间消耗和相关知识的积累,因此对于软件开发团队来说,使用静态代码分析工具自动化执行代码检查和分析,能够极大地提高软件可靠性并节省软件开发和测试成本。

静态代码分析工具的优势

  1. 帮助程序开发人员自动执行静态代码分析,快速定位代码隐藏错误和缺陷。
  2. 帮助代码设计人员更专注于分析和解决代码设计缺陷。
  3. 显著减少在代码逐行检查上花费的时间,提高软件可靠性并节省软件开发和测试成本。

三款主流静态源代码安全检测工具比较(付费)

Fortify SCA(Source Code Analysis)

Fortify Software公司是一家总部位于美国硅谷,致力于提供应用软件安全开发工具和管理方案的厂商。Fortify为应用软件开发组织、安全审计人员和应用 安全管理人员提供工具并确立最佳的应用软件安全实践和策略,帮助他们在软件开发生命周期中花最少的时间和成本去识别和修复软件源代码中的安全隐患。 Fortify SCA是Fortify360产品套装中的一部分,它使用fortify公司特有的X-Tier Dataflow™ analysis技术去检测软件安全问题。

优点:目前全球最大静态源代码检测厂商、支持语言最多

缺点:价格昂贵、使用不方便

Checkmarx CxSuite

Checkmarx 是以色列的一家高科技软件公司。它的产品CheckmarxCxSuite专门设计为识别、跟踪和修复软件源代码上的技术和逻辑方面的安全风险。首创了以查询语言定位代码安全问题,其采用独特的词汇分析技术和CxQL专利查询技术来扫描和分析源代码中的安全漏洞和弱点。

优点:利用CxQL 查询语言自定义规则

缺点:输出报告不够美观、语言支持种类不全面

Armorize CodeSecure

阿码科技成立于2006年,总部设立于美国加州圣克拉拉市,研发中心位于台湾的南港软件工业园区。阿码科技提供全方位网络安全解决方案,捍卫企业免于受到黑客利用 Web 应用程序的漏洞所发动的攻击。阿码科技 CodeSecure可有效地协助企业与开发人员在软件开发过程及项目上线后找出 Web 应用程序风险,并清楚交代风险的来龙去脉 (如何进入程序,如何造成问题) 。CodeSecure内建语法剖析功能无需依赖编译环境,任何人员均可利用 Web操作与集成开发环境双接口,找出存在信息安全问题的源代码,并提供修补建议进行调整。CodeSecure依托于自行开发的主机进行远程源代码检 测,在保证速度稳定的同时方便用户进行Web远程操作。

优点:Web结合硬件,速度快、独具特色的深度分析

缺点:支持语言种类较少、价格不菲

对比

SCA CxSuite CodeSecure
厂商 Fortify Software Checkmarx 阿码科技
支持语言 Java,JSP,ASP.NET,C#, VB.NET,C,C++,COBOL, ColdFusion,Transact-SQL, PL/SQL,JavaScript/Ajax, Classic,ASP,VBScript,VB6,PHP JAVA、ASP.NET(C#、VB.NET)、JavaScript、Jscript、C/C++、APEX ASP.NET(C#、VB.NET)、ASP、JAVA、PHP
风险种类 400种 300种 参考CWE
风险类型参考来源 CWE、OWASP CWE、OWASP CWE、OWASP
漏报率 最低
误报率 稍高
是否支持SaaS
软硬件类型 纯软件 纯软件 Web结合硬件设备
运行平台 无限制 WindowsNET Framework 2.0 无限制
运行速度 取决于电脑配置速度不定 取决于电脑配置速度不定 由主机配置决定速度恒定
报告格式 PDF PDF、XML、CSV、HTML Web、PDF
报告内容 完整按照风险级别不同分为多个文件 核心内容完整扫描信息等缺失 非常完整但修改建议放于最后
报价 100万/软件 70万/软件 100万/软硬件
性价比

Java 静态代码分析理论基础和主要技术

  • 缺陷模式匹配:缺陷模式匹配事先从代码分析经验中收集足够多的共性缺陷模式,将待分析代码与已有的共性缺陷模式进行模式匹配,从而完成软件的安全分析。这种方式的优点是简单方便,但是要求内置足够多缺陷模式,且容易产生误报。
  • 类型推断:类型推断技术是指通过对代码中运算对象类型进行推理,从而保证代码中每条语句都针对正确的类型执行。这种技术首先将预定义一套类型机制,包括类 型等价、类型包含等推理规则,而后基于这一规则进行推理计算。类型推断可以检查代码中的类型错误,简单,高效,适合代码缺陷的快速检测。
  • 模型检查:模型检验建立于有限状态自动机的概念基础之上,这一理论将被分析代码抽象为一个自动机系统,并且假设该系统是有限状态的、或者是可以通过抽象归 结为有限状态。模型检验过程中,首先将被分析代码中的每条语句产生的影响抽象为一个有限状态自动机的一个状态,而后通过分析有限状态机从而达到代码分析的 目的。模型检验主要适合检验程序并发等时序特性,但是对于数据值域数据类型等方面作用较弱。
  • 数据流分析:数据流分析也是一种软件验证技术,这种技术通过收集代码中引用到的变量信息,从而分析变量在程序中的赋值、引用以及传递等情况。对数据流进行 分析可以确定变量的定义以及在代码中被引用的情况,同时还能够检查代码数据流异常,如引用在前赋值在后、只赋值无引用等。数据流分析主要适合检验程序中的 数据域特性。

现有主流 Java 静态分析工具(开源)

Checkstyle

Checkstyle 是 SourceForge 的开源项目,通过检查对代码编码格式,命名约定,Javadoc,类设计等方面进行代码规范和风格的检查,从而有效约束开发人员更好地遵循代码编写规范。

Checkstyle 提供了支持大多数常见 IDE 的插件,文本主要使用 Eclipse 中的 Checkstyle 插件。如下图 1 所示,Checkstyle 对代码进行编码风格检查,并将检查结果显示在 Problems 视图中。图中,代码编辑器中每个放大镜图标表示一个 Checkstyle 找到的代码缺陷。开发人员可通过在 Problems 视图中查看错误或警告详细信息。

图 1. 使用 Checkstyle 进行编码风格检查

此外,Checkstyle 支持用户根据需求自定义代码检查规范,在下图 2 中的配置面板中,用户可以在已有检查规范如命名约定,Javadoc,块,类设计等方面的基础上添加或删除自定义检查规范。

图 2. 使用 Checkstyle 添加自定义代码检查规范

FindBugs

FindBugs 是由马里兰大学提供的一款开源 Java 静态代码分析工具。FindBugs 通过检查类文件或 JAR 文件,将字节码与一组缺陷模式进行对比从而发现代码缺陷,完成静态代码分析。FindBugs 既提供可视化 UI 界面,同时也可以作为 Eclipse 插件使用。文本将主要使用将 FindBugs 作为 Eclipse 插件。在安装成功后会在 eclipse 中增加 FindBugs perspective,用户可以对指定 Java 类或 JAR 文件运行 FindBugs,此时 FindBugs 会遍历指定文件,进行静态代码分析,并将代码分析结果显示在 FindBugs perspective 的 bugs explorer 中,如下图 3 所示:

图 3. 使用 FindBugs 进行静态代码分析

此外,FindBugs 还为用户提供定制 Bug Pattern 的功能。用户可以根据需求自定义 FindBugs 的代码检查条件,如下图 4 所示:

图 4. 使用 FindBugs 添加自定义代码检查规范

PMD

PMD 是由 DARPA 在 SourceForge 上发布的开源 Java 代码静态分析工具。PMD 通过其内置的编码规则对 Java 代码进行静态检查,主要包括对潜在的 bug,未使用的代码,重复的代码,循环体创建新对象等问题的检验。PMD 提供了和多种 Java IDE 的集成,例如 Eclipse,IDEA,NetBean 等。本文主要使用 PMD 以插件方式与 Eclipse 集成。如下图 5 所示:在 Violations Overview 视图中,按照代码缺陷严重性集中显示了 PMD 静态代码分析的结果。

图 5. 使用 PMD 进行静态代码分析

图 6. 使用 PMD 添加自定义代码检查规范

Jtest

Jtest 是 Parasoft 公司推出的一款针对 Java 语言的自动化代码优化和测试工具,Jtest 的静态代码分析功能能够按照其内置的超过 800 条的 Java 编码规范自动检查并纠正这些隐蔽且难以修复的编码错误。同时,还支持用户自定义编码规则,帮助用户预防一些特殊用法的错误。Jtest 提供了基于 Eclipse 的插件安装。Jtest 支持开发人员对 Java 代码进行编码规范检查,并在 Jtask 窗口中集中显示检查结果,如下图 7 所示:

图 7. 使用 Jtest 进行静态代码分析

图 8. 使用 Jtest 添加自定义代码检查规范

Java 静态分析工具对比

本章节将从以下几个方面对上述 Java 静态分析工具进行比较:

应用技术及分析对象

下表 1 列出了不同工具的分析对象及应用技术对比:

表 1. 不同工具的分析对象及应用技术对比

Java 静态分析工具 分析对象 应用技术
Checkstyle Java 源文件 缺陷模式匹配
FindBugs 字节码 缺陷模式匹配;数据流分析
PMD Java 源代码 缺陷模式匹配
Jtest Java 源代码 缺陷模式匹配;数据流分析

内置编程规范

Checkstyle:

  • Javadoc 注释:检查类及方法的 Javadoc 注释
  • 命名约定:检查命名是否符合命名规范
  • 标题:检查文件是否以某些行开头
  • Import 语句:检查 Import 语句是否符合定义规范
  • 代码块大小,即检查类、方法等代码块的行数
  • 空白:检查空白符,如 tab,回车符等
  • 修饰符:修饰符号的检查,如修饰符的定义顺序
  • 块:检查是否有空块或无效块
  • 代码问题:检查重复代码,条件判断,魔数等问题
  • 类设计:检查类的定义是否符合规范,如构造函数的定义等问题

FindBugs:

  • Bad practice 坏的实践:常见代码错误,用于静态代码检查时进行缺陷模式匹配
  • Correctness 可能导致错误的代码,如空指针引用等
  • 国际化相关问题:如错误的字符串转换
  • 可能受到的恶意攻击,如访问权限修饰符的定义等
  • 多线程的正确性:如多线程编程时常见的同步,线程调度问题。
  • 运行时性能问题:如由变量定义,方法调用导致的代码低效问题。

PMD:

  • 可能的 Bugs:检查潜在代码错误,如空 try/catch/finally/switch 语句
  • 未使用代码(Dead code):检查未使用的变量,参数,方法
  • 复杂的表达式:检查不必要的 if 语句,可被 while 替代的 for 循环
  • 重复的代码:检查重复的代码
  • 循环体创建新对象:检查在循环体内实例化新对象
  • 资源关闭:检查 Connect,Result,Statement 等资源使用之后是否被关闭掉

Jtest

  • 可能的错误:如内存破坏、内存泄露、指针错误、库错误、逻辑错误和算法错误等
  • 未使用代码:检查未使用的变量,参数,方法
  • 初始化错误:内存分配错误、变量初始化错误、变量定义冲突
  • 命名约定:检查命名是否符合命名规范
  • Javadoc 注释:检查类及方法的 Javadoc 注释
  • 线程和同步:检验多线程编程时常见的同步,线程调度问题
  • 国际化问题:
  • 垃圾回收:检查变量及 JDBC 资源是否存在内存泄露隐患

错误检查能力

为比较上述 Java 静态分析工具的代码缺陷检测能力,本文将使用一段示例代码进行试验,示例代码中将涵盖我们开发中的几类常见错误,如引用操作、对象操作、表达式复杂化、数 组使用、未使用变量或代码段、资源回收、方法调用及代码设计几个方面。最后本文将分别记录在默认检查规范设置下,不同工具对该示例代码的分析结果。以下为 示例代码 Test.java。其中,代码的注释部分列举了代码中可能存在的缺陷。

清单 1. Test.java 示例代码

package Test;
import java.io.*;
public class Test {/*** Write the bytes from input stream to output stream.* The input stream and output stream are not closed.* @param is* @param os* @throws IOException*/public  boolean copy(InputStream is, OutputStream os) throws IOException {int count = 0;//缺少空指针判断byte[] buffer = new byte[1024];while ((count = is.read(buffer)) >= 0) {os.write(buffer, 0, count);}//未关闭I/O流return true;}/*** * @param a* @param b* @param ending* @return copy the elements from a to b, and stop when meet element ending*/public void copy(String[] a, String[] b, String ending){int index;String temp = null;//空指针错误System.out.println(temp.length());//未使用变量int length=a.length;for(index=0; index < a.length; index++){//多余的if语句if(true){//对象比较 应使用equalsif(temp==ending){break;}//缺少 数组下标越界检查b[index]=temp;}}}/*** * @param file* @return file contents as string; null if file does not exist*/public  void  readFile(File file) {InputStream is = null;OutputStream os = null;try {is = new BufferedInputStream(new FileInputStream(file));os = new ByteArrayOutputStream();//未使用方法返回值copy(is,os);is.close();os.close();} catch (IOException e) {//可能造成I/O流未关闭e.printStackTrace();} finally{//空的try/catch/finally块}}
}

通过以上测试代码,我们对已有 Java 静态代码分析工具的检验结果做了如下比较,如下表 2 所示。
表 2. Java 静态代码分析工具对比

代码缺陷分类 示例 Checkstyle FindBugs PMD Jtest
引用操作 空指针引用
对象操作 对象比较(使用 == 而不是 equals)
表达式复杂化 多余的 if 语句
数组使用 数组下标越界
未使用变量或代码段 未使用变量
资源回收 I/O 未关闭
方法调用 未使用方法返回值
代码设计 空的 try/catch/finally 块

由表中可以看出几种工具对于代码检查各有侧重。其中,Checkstyle 更偏重于代码编写格式,及是否符合编码规范的检验,对代码 bug 的发现功能较弱;而 FindBugs,PMD,Jtest 着重于发现代码缺陷。在对代码缺陷检查中,这三种工具在针对的代码缺陷类别也各有不同,且类别之间有重叠。

总结

本文分别从功能、特性和内置编程规范等方面详细介绍了包括 Checkstyle,FindBugs,PMD,Jtest 在内的四种主流 Java 静态代码分析工具,并通过一段 Java 代码示例对这四种工具的代码分析能力进行比较。由于这四种工具内置编程规范各有不同,因此它们对不同种类的代码问题的发现能力也有所不同。其中 Checkstyle 更加偏重于代码编写格式检查,而 FindBugs,PMD,Jtest 着重于发现代码缺陷。最后,希望本文能够帮助 Java 软件开发和测试人员进一步了解以上四种主流 Java 静态分析工具,并帮助他们根据需求选择合适的工具。

现有主流 C/C++静态分析工具(开源)

splint

splint介绍

splint是一个静态检查C语言程序安全弱点和编写错误的工具。splint会进行多种常规检查,包括未使 用的变量,类型不一致,使用未定义变量,无法执行的代码,忽略返回值,执行路径未返回,无限循环等错误。同 时通过在源码中添加注记给出的附加信息,使其可以进行功能更加强大的检查。而注记,则是对文件中的函数、变 量、参数以及类型进行假定的一种的程式化的注释。

splint的安装

官网:http://splint.org/

最新版本:Splint Version 3.1.2

支持平台

windows(旧版本支持)

[外链图片转存失败(img-ALXTzv9B-1569412951252)(C:%5CUsers%5Chaizhou.song%5CDesktop%5C%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%5Cjava%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7.assets%5C1569382210558.png)]

Linux:

sudo apt-get install splint

[外链图片转存失败(img-a9Ay89CE-1569412951252)(C:%5CUsers%5Chaizhou.song%5CDesktop%5C%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%5Cjava%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7.assets%5C1569382151967.png)]

可检查错误类型

  1. Dereferencing a possibly null pointer
  2. Using possibly undefined storage or returning storage that is not properly defined
  3. Type mismatches, with greater precision and flexibility than provided by C compilers
  4. Violations of information hiding
  5. Memory management errors including uses of dangling references and memory leaks
  6. Dangerous aliasing
  7. Modifications and global variable uses that are inconsistent with specified interfaces
  8. Problematic control flow such as likely infinite loops
  9. Buffer overflow vulnerabilities
  10. Dangerous macro implementations or invocations
  11. Violations of customized naming conventions

Cppcheck

介绍

Cppcheck is a static analysis tool for C/C++ code. It provides unique code analysis to detect bugs and focuses on detecting undefined behaviour and dangerous coding constructs. The goal is to detect only real errors in the code (i.e. have very few false positives).

安装

官网:http://cppcheck.sourceforge.net/

最新版本:Cppcheck 1.89

支持平台

windows

[外链图片转存失败(img-uQrjFeSm-1569412951253)(C:%5CUsers%5Chaizhou.song%5CDesktop%5C%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%5Cjava%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7.assets%5C1569382268226.png)]

linux:

sudo apt-get install cppcheck

[外链图片转存失败(img-h68RzBzI-1569412951253)(C:%5CUsers%5Chaizhou.song%5CDesktop%5C%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7%5Cjava%E9%9D%99%E6%80%81%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7.assets%5C1569382310710.png)]

可检查错误类型

# get list of checks
cppcheck --doc

64-bit portability

Check if there is 64-bit portability issues:

  • assign address to/from int/long

  • casting address from/to integer when returning from function

    Assert

    Warn if there are side effects in assert statements (since this cause different behaviour in debug/release builds).

    Auto Variables

    A pointer to a variable is only valid as long as the variable is in scope.

    Check:

  • returning a pointer to auto or temporary variable

  • assigning address of an variable to an effective parameter of a function

  • returning reference to local/temporary variable

  • returning address of function parameter

  • suspicious assignment of pointer argument

  • useless assignment of function argument

    Boolean

    Boolean type checks

  • using increment on boolean

  • comparison of a boolean expression with an integer other than 0 or 1

  • comparison of a function returning boolean value using relational operator

  • comparison of a boolean value with boolean value using relational operator

  • using bool in bitwise expression

  • pointer addition in condition (either dereference is forgot or pointer overflow is required to make the condition false)

  • Assigning bool value to pointer or float

    Boost usage

    Check for invalid usage of Boost:

  • container modification during BOOST_FOREACH

    Bounds checking

    Out of bounds checking:

  • Array index out of bounds detection by value flow analysis

  • Dangerous usage of strncat()

  • char constant passed as size to function like memset()

  • strncpy() leaving string unterminated

  • Accessing array with negative index

  • Unsafe usage of main(argv, argc) arguments

  • Accessing array with index variable before checking its value

  • Check for large enough arrays being passed to functions

  • Allocating memory with a negative size

    Check function usage

    Check function usage:

  • return value of certain functions not used

  • invalid input values for functions

  • Warn if a function is called whose usage is discouraged

  • memset() third argument is zero

  • memset() with a value out of range as the 2nd parameter

  • memset() with a float as the 2nd parameter

    Class

    Check the code for each class.

  • Missing constructors and copy constructors

  • Constructors which should be explicit

  • Are all variables initialized by the constructors?

  • Are all variables assigned by ‘operator=’?

  • Warn if memset, memcpy etc are used on a class

  • Warn if memory for classes is allocated with malloc()

  • If it’s a base class, check that the destructor is virtual

  • Are there unused private functions?

  • ‘operator=’ should return reference to self

  • ‘operator=’ should check for assignment to self

  • Constness for member functions

  • Order of initializations

  • Suggest usage of initialization list

  • Initialization of a member with itself

  • Suspicious subtraction from ‘this’

  • Call of pure virtual function in constructor/destructor

  • Duplicated inherited data members

  • If ‘copy constructor’ defined, ‘operator=’ also should be defined and vice versa

  • Check that arbitrary usage of public interface does not result in division by zero

    Condition

    Match conditions with assignments and other conditions:

  • Mismatching assignment and comparison => comparison is always true/false

  • Mismatching lhs and rhs in comparison => comparison is always true/false

  • Detect usage of | where & should be used

  • Detect matching ‘if’ and ‘else if’ conditions

  • Mismatching bitand (a &= 0xf0; a &= 1; => a = 0)

  • Opposite inner condition is always false

  • Identical condition after early exit is always false

  • Condition that is always true/false

  • Mutual exclusion over || always evaluating to true

  • Comparisons of modulo results that are always true/false.

  • Known variable values => condition is always true/false

  • Invalid test for overflow (for example ‘ptr+u < ptr’). Condition is always false unless there is overflow, and overflow is undefined behaviour.

    Exception Safety

    Checking exception safety

  • Throwing exceptions in destructors

  • Throwing exception during invalid state

  • Throwing a copy of a caught exception instead of rethrowing the original exception

  • Exception caught by value instead of by reference

  • Throwing exception in noexcept, nothrow(), attribute((nothrow)) or __declspec(nothrow) function

  • Unhandled exception specification when calling function foo()

    IO using format string

    Check format string input/output operations.

  • Bad usage of the function ‘sprintf’ (overlapping data)

  • Missing or wrong width specifiers in ‘scanf’ format string

  • Use a file that has been closed

  • File input/output without positioning results in undefined behaviour

  • Read to a file that has only been opened for writing (or vice versa)

  • Repositioning operation on a file opened in append mode

  • Using fflush() on an input stream

  • Invalid usage of output stream. For example: ‘std::cout << std::cout;’

  • Wrong number of arguments given to ‘printf’ or ‘scanf;’

    Leaks (auto variables)

    Detect when a auto variable is allocated but not deallocated or deallocated twice.

    Memory leaks (address not taken)

    Not taking the address to allocated memory

    Memory leaks (class variables)

    If the constructor allocate memory then the destructor must deallocate it.

    Memory leaks (function variables)

    Is there any allocated memory when a function goes out of scope

    Memory leaks (struct members)

    Don’t forget to deallocate struct members

    Null pointer

    Null pointers

  • null pointer dereferencing

  • undefined null pointer arithmetic

    Other

    Other checks

  • division with zero

  • scoped object destroyed immediately after construction

  • assignment in an assert statement

  • free() or delete of an invalid memory location

  • bitwise operation with negative right operand

  • provide wrong dimensioned array to pipe() system command (–std=posix)

  • cast the return values of getc(),fgetc() and getchar() to character and compare it to EOF

  • race condition with non-interlocked access after InterlockedDecrement() call

  • expression ‘x = x++;’ depends on order of evaluation of side effects

  • either division by zero or useless condition

  • access of moved or forwarded variable.

  • redundant data copying for const variable

  • subsequent assignment or copying to a variable or buffer

  • passing parameter by value

  • Passing NULL pointer to function with variable number of arguments leads to UB.

  • C-style pointer cast in C++ code

  • casting between incompatible pointer types

  • Incomplete statement

  • check how signed char variables are used

  • variable scope can be limited

  • unusual pointer arithmetic. For example: “abc” + ‘d’

  • redundant assignment, increment, or bitwise operation in a switch statement

  • redundant strcpy in a switch statement

  • Suspicious case labels in switch()

  • assignment of a variable to itself

  • Comparison of values leading always to true or false

  • Clarify calculation with parentheses

  • suspicious comparison of ‘\0’ with a char* variable

  • duplicate break statement

  • unreachable code

  • testing if unsigned variable is negative/positive

  • Suspicious use of ; at the end of ‘if/for/while’ statement.

  • Array filled incompletely using memset/memcpy/memmove.

  • NaN (not a number) value used in arithmetic expression.

  • comma in return statement (the comma can easily be misread as a semicolon).

  • prefer erfc, expm1 or log1p to avoid loss of precision.

  • identical code in both branches of if/else or ternary operator.

  • redundant pointer operation on pointer like &*some_ptr.

  • find unused ‘goto’ labels.

  • function declaration and definition argument names different.

  • function declaration and definition argument order different.

    STL usage

    Check for invalid usage of STL:

  • out of bounds errors

  • misuse of iterators when iterating through a container

  • mismatching containers in calls

  • dereferencing an erased iterator

  • for vectors: using iterator/pointer after push_back has been used

  • optimisation: use empty() instead of size() to guarantee fast code

  • suspicious condition when using find

  • redundant condition

  • common mistakes when using string::c_str()

  • using auto pointer (auto_ptr)

  • useless calls of string and STL functions

  • dereferencing an invalid iterator

  • reading from empty STL container

    Sizeof

    sizeof() usage checks

  • sizeof for array given as function argument

  • sizeof for numeric given as function argument

  • using sizeof(pointer) instead of the size of pointed data

  • look for ‘sizeof sizeof …’

  • look for calculations inside sizeof()

  • look for suspicious calculations with sizeof()

  • using ‘sizeof(void)’ which is undefined

    String

    Detect misusage of C-style strings:

  • overlapping buffers passed to sprintf as source and destination

  • incorrect length arguments for ‘substr’ and ‘strncmp’

  • suspicious condition (runtime comparison of string literals)

  • suspicious condition (string literals as boolean)

  • suspicious comparison of a string literal with a char* variable

  • suspicious comparison of ‘\0’ with a char* variable

  • overlapping strcmp() expression

    Type

    Type checks

  • bitwise shift by too many bits (only enabled when --platform is used)

  • signed integer overflow (only enabled when --platform is used)

  • dangerous sign conversion, when signed value can be negative

  • possible loss of information when assigning int result to long variable

  • possible loss of information when returning int result as long return value

  • float conversion overflow

    Uninitialized variables

    Uninitialized variables

  • using uninitialized local variables

  • using allocated data before it has been initialized

  • using dead pointer

    Unused functions

    Check for functions that are never called

    UnusedVar

    UnusedVar checks

  • unused variable

  • allocated but unused variable

  • unred variable

  • unassigned variable

  • unused struct member

    Using postfix operators

    Warn if using postfix operators ++ or – rather than prefix operator

    Vaarg

    Check for misusage of variable argument lists:

  • Wrong parameter passed to va_start()

  • Reference passed to va_start()

  • Missing va_end()

  • Using va_list before it is opened

  • Subsequent calls to va_start/va_copy()

错误检查能力对比

清单 1. test_1.c 示例代码

#include <stdio.h>
#include <stdlib.h>int main()
{//类型转换警告unsigned char ch = 128;signed char sch = ch;printf("%d", sch);//数组溢出int a[12];a[12] = 12; //空指针引用int *b = NULL;(*b)++; // 野指针引用int *q = (int*)malloc(1000*sizeof(int)); free(q);(*q)++;// 内存泄漏 p没freeint *p = (int*)malloc(1000*sizeof(int));            //return 0;  函数返回值
}

清单 2. test_2.c 示例代码

#include <stdio.h>
#include <stdlib.h>int main()
{//死循环while (1) printf("hello world!\n");return 0;
}//死循环会影响其他检测结果 原因未知

通过以上测试代码,我们对已有 C 静态代码分析工具的检验结果做了如下比较,如下表 2 所示。

表 1.C 静态代码分析工具对比

代码问题 splint Cppcheck
类型转换
数组溢出
空指针引用
野指针引用
内存泄露
函数返回值
死循环
变量未使用

静态代码分析工具简介相关推荐

  1. 软文推荐:常用 Java 静态代码分析工具的分析与比较

    http://www.uml.org.cn/j2ee/201107114.asp 常用 Java 静态代码分析工具的分析与比较 作者:赵卓 , 发布于2011-07-11 , IBM 简介: 本文首先 ...

  2. 静态代码检查工具简介

    静态代码检查工具简介 在 Java 软件开发过程中,开发团队往往要花费大量的时间和精力发现并修改代码缺陷.传统的代码复审.同行评审,通过人工方式来检查缺陷仍然是一件耗时耗力的事情.Java 静态代码分 ...

  3. 静态代码分析工具列表--常用静态代码分析工具介绍

    代码检测简介 本文是一个静态代码分析工具的清单,但是为公司产品需要付费使用.共有37个公司,有些公司包含多个工具.其中27个公司有多语言 工具,1个公司为PHP工具.2个公司为.NET工具.1个公司为 ...

  4. PVS-Studio C/C++/C++11 静态代码分析工具

    PVS-Studio C/C++/C++11 静态代码分析工具 静态代码分析仪是一种检测代码缺陷.分析对比 商业代码的工具,它分析源代码和它生成的目标 文件,但并不实际运行源代码.应用于对安全性. 稳 ...

  5. 2021.C/C++静态代码分析工具

    静态代码分析工具 1 cppcheck 静态代码分析工具 1 cppcheck 静态代码分析工具 参考博客 使用cppcheck检测代码警告.错误 ubuntu下安装cppcheck sudo apt ...

  6. OOM分析(1) Android 源,如何分析android的OOM,与java静态代码分析工具

    用MAT分析OOM 很多OOM看似发生在bitmap 分配得时候,但它一般不是rootcause.根本原因都在于本应该自动释放的资源,因为代码的错误,而导致某些对象一直被引用(Reference),例 ...

  7. 如何分析android的OOM,与java静态代码分析工具

    2019独角兽企业重金招聘Python工程师标准>>> 用MAT分析OOM 很多OOM看似发生在bitmap 分配得时候,但它一般不是rootcause.根本原因都在于本应该自动释放 ...

  8. 静态代码分析工具列表分析---代码分析工具列表(30款工具)

    本文是一个静态代码分析工具的清单,共有30个工具.包括4个.NET工具.2个Ada工具.7个C++工具.4个Java工具.2个JavaScript工具.1个Opa工具.2个Packaging工具.3个 ...

  9. 静态代码分析工具清单:开源篇(各语言)

    本文是一个静态代码分析工具的清单,共有26个工具.包括4个.NET工具.2个Ada工具.7个C++工具.4个Java工具.2个JavaScript工具.1个Opa工具.2个Packaging工具.3个 ...

最新文章

  1. 在CentOS 6.6 64bit上编译安装LLVM3.7,Clang,Libc++和libc++abi
  2. macOS下使用anaconda相关系列
  3. 领扣(LeetCode)寻找旋转排序数组中的最小值 个人题解
  4. qbuttongroup如何都不选中_全程马拉松,半程马拉松该如何跑?很多人都不知道这些细节...
  5. 常用的sql语句用法
  6. Cream Finance已批准将BAC作为抵押资产
  7. java语言数组实现栈的操作_基于自定义的动态数组实现一个栈(Java语言)
  8. Powershell 自定义对象小技巧
  9. CCF NOI1070 汉诺塔游戏
  10. Android 设置闹铃步骤和基础代码
  11. 解决办法:configure后,没有更新Makefile
  12. 【背包问题】基于matlab遗传算法求解背包问题【含Matlab源码 578期】
  13. 微信小程序使用VantUI框架
  14. PTP(IEEE1588),TSN时间同步方法
  15. C#正则判断手机号 邮箱 网址 日期 IP 身份证等
  16. 思科计算机网络(1)计算机网络概述
  17. 2022年最新山东建筑八大员(市政)模拟考试题库及答案
  18. 局域网和广域网的传输流程
  19. 孙悟空吃蟠桃c语言编程,孙悟空吃光蟠桃是爱国行为
  20. 计算机设备维修预算申,维修费用申请报告

热门文章

  1. 日记侠:关于朋友圈文案策划,你如何理解?
  2. Day8_ElectronicAlbum
  3. 利用pycharm简单实现多进程
  4. 2022年第八届美亚杯个人赛复盘
  5. 12道vue高频原理面试题,你能答出几道?
  6. 使用simhash计算文本相似度
  7. 国内外建筑信息化企业产品分析
  8. revit二次开发-创建族
  9. 一个LED的N种玩法--多线程
  10. linux 字节类型,int数据类型占几个字节?