【问题标题】:Using Sparse to check C code使用 Sparse 检查 C 代码
【发布时间】:2010-12-21 13:37:00
【问题描述】:

有人有Sparse 的经验吗?我似乎找不到任何文档,因此我不清楚它产生的警告和错误。我尝试检查邮件列表和手册页,但两者都没有。

例如,我在我的一个文件中使用了 INT_MAX。即使我#include limits.h,这也会产生错误(未定义的标识符)。

有没有地方解释过错误和警告?

【问题讨论】:

    标签: c linux sparse-matrix static-analysis


    【解决方案1】:

    说,Sparse 并不是要成为 lint。 Sparse 旨在生成任意代码的解析树,以便对其进行进一步分析。

    在您的示例中,您要么想要定义 GNU_SOURCE(我相信它会打开 __GNUC__),它会在 limits.h 中公开您需要的位

    我会避免自己定义 __GNUC__,因为它激活的一些东西可能会以未定义的方式运行,而没有定义 GNU_SOURCE 打开的所有其他开关。

    我的意思不是要帮助您逐个错误地消除错误,而是要重申 sparse 主要用作库,而不是作为独立的静态分析工具。

    来自我的 README 副本(不确定我是否拥有当前版本):

    This means that a user of the library will literally just need to do
    
      struct string_list *filelist = NULL;
      char *file;
    
      action(sparse_initialize(argc, argv, filelist));
    
      FOR_EACH_PTR_NOTAG(filelist, file) {
        action(sparse(file));
      } END_FOR_EACH_PTR_NOTAG(file);
    
    and he is now done - having a full C parse of the file he opened.  The
    library doesn't need any more setup, and once done does not impose any
    more requirements.  The user is free to do whatever he wants with the
    parse tree that got built up, and needs not worry about the library ever
    again.  There is no extra state, there are no parser callbacks, there is
    only the parse tree that is described by the header files. The action
    function takes a pointer to a symbol_list and does whatever it likes with it.
    
    The library also contains (as an example user) a few clients that do the
    preprocessing, parsing and type evaluation and just print out the
    results.  These clients were done to verify and debug the library, and
    also as trivial examples of what you can do with the parse tree once it
    is formed, so that users can see how the tree is organized.
    

    包含的客户端比任何东西都更像是“功能测试套件和示例”。它是一个非常有用的工具,但如果你想使用它,你可以考虑另一个使用角度。我喜欢它,因为它不使用 *lex / bison ,这使得它更容易破解。

    【讨论】:

    • 好的,我想我会坚持使用夹板。不过,感谢您解释这一点。
    • 我同时使用了 sparse 和 splint,sparse 有一些不被 clang/gcc/splint/mvcs/splint/cppcheck 发现的漂亮警告,它们是 1) 0 用作 NULL - 取决于在您的代码风格上,但这可以使代码更具可读性。 2) 建议函数是静态的 - 或包含声明它们的标头,事实上我发现这可以修复真正的错误,因为如果标头中的声明和源中的声明不匹配调用很容易崩溃。
    • 只有当我们使用像 __le32_to_cpu() 这样的宏时,稀疏工具是否会识别与字节序相关的问题(make c=2 cf="-D__CHECK_ENDIAN__")?或者它能否识别所有类型的字节序相关问题,如位域、联合等?
    【解决方案2】:

    如果您查看limits.h,您会发现INT_MAX 是在此#if 中定义的

    /* If we are not using GNU CC we have to define all the symbols ourself.
     Otherwise use gcc's definitions (see below).  */
    #if !defined __GNUC__ || __GNUC__ < 2
    

    为了让它工作,你应该在包含limits.h之前取消定义__GNUC__

    【讨论】:

    • 实际上在我的limits.h中看起来并不是这样。没有#ifdef 并且INT_MAX 设置为INT_MAX。这至少是包含 KDevelop 提供的。但我想我按照 tinkertim 的解释跳过夹板。我会给他“正确答案”,因为他解释了这个概念,即使你的答案也是正确的。
    猜你喜欢
    • 2018-07-02
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2011-06-29
    • 2014-03-27
    相关资源
    最近更新 更多