曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 8740|回复: 2
打印 上一主题 下一主题

sparse 工具的介绍及简单应用

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-4-15 17:40:02 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Sparse - a Semantic Parser for C
sparse 是用于 C 语言的语法分析器,用以对 C 代码进行静态检查,它不但可以检查 ANSI C 而且还能检查具有 gcc 扩展的 C 。在 Linux 中,不但可以检查用户端代码,还可以检查内核代码。起初它由 linus 编写,后来交给其他人维护。

可以从下面的网址获得该工具:
http://www.kernel.org/pub/software/devel/sparse/dist/

也可以通过 GIT 工具获得:
git clone git://git.kernel.org/pub/scm/devel/sparse/sparse.git

要获得最新的开发版还可以从下面的网址获得:
http://www.codemonkey.org.uk/projects/git-snapshots/sparse/

要么直接最新的下载压缩包:
下载 sparse 并解压缩后,可以在其源码目录下简单执行以下命令编译安装:
make
make install

简单使用示例:
程序一:
[C++] 纯文本查看 复制代码
#include <stdio.h>
int main()
{
        printf ("hello world\n");
        return 0;
}

使用 sparse 检查这个程序:
[beyes@SLinux sparse]$ ./sparse /home/beyes/C/gcc/context.c
/home/beyes/C/gcc/context.c:6:10: warning: non-ANSI function declaration of function 'main'
警告提示我们这个程序中的 main 函数不符合 ANSI 函数的声明标准。
改进方法是为 main() 函数添加上参数,即:
[Plain Text] 纯文本查看 复制代码
main(int argc, char **argv)

这样修改后再次检查时,则不会出现此警告。

程序二:
[C++] 纯文本查看 复制代码
#include <stdio.h>

#define __acquire(x) __context__(x,1)
#define __release(x) __context__(x,-1)

int main(int argc, char **argv)
{
      __acquire(10);

        printf ("hello world\n");
        return 0;
}

上面从 linux 内核代码中直接拷贝了用以实现 spinlock 的两个宏 __acquire(x) 和 __release(x) 。在这两个宏中,出现了 __context__ 标签,这个 __context__ 是一种 sparse 支持的检查特性。这里,如果函数里单独 __acquire() 而没有使用 __release() 与之匹配的话,sparse 会发出警告。顺便说一下,像自旋锁这种锁,如果忘记释放(不匹配使用),那么会造成整个内核死锁,这时候只能重启系统。使用 sparse 检查上面的程序会发现:
[beyes@SLinux sparse]$ ./sparse /home/beyes/C/gcc/context.c
/home/beyes/C/gcc/context.c:6:5: warning: context imbalance in 'main' - wrong count at exit
如果将 __release() 加上和 __acquire() 匹配的话,则警告消除。

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
沙发
 楼主| 发表于 2011-4-15 18:01:28 | 只看该作者

cgcc man page

Name
cgcc - Compiler wrapper to run Sparse after compiling


Synopsis
cgcc [SPARSE OPTIONS]... [COMPILER OPTIONS]... [INPUT FILES]...
make CC=cgcc


Description
cgcc provides a wrapper around a C compiler (cc by default) which also invokes the Sparse static analysis tool.
cgcc accepts all Sparse command-line options, such as warning options, and passes all other options through to the compiler.
By providing the same interface as the C compiler, cgcc allows projects to run Sparse as part of their build without modifying their build system, by using cgcc as the compiler. For many projects, setting CC=cgcc on the make command-line will work.

Environment
REAL_CC If set, cgcc will use this as the compiler to invoke, rather than the default cc. CHECK If set, cgcc will use this as the Sparse program to invoke, rather than the default sparse.

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
板凳
 楼主| 发表于 2011-4-15 17:48:04 | 只看该作者

sparse man page

Name
sparse - Semantic Parser for C
Synopsis
sparse [WARNING OPTIONS]... file.c

Description
Sparse parses C source and looks for errors, producing warnings on standard error.
Sparse accepts options controlling the set of warnings to generate. To turn on warnings Sparse does not issue by default, use the corresponding warning option -Wsomething. Sparse issues some warnings by default; to turn off those warnings, pass the negation of the associated warning option, -Wno-something.

Warning Options
-Waddress-space
Warn about code which mixes pointers to different address spaces.
Sparse allows an extended attribute __attribute__((address_space(num))) on pointers, which designates a pointer target in address space num (a constant integer). With -Waddress-space, Sparse treats pointers with identical target types but different address spaces as distinct types. To override this warning, such as for functions which convert pointers between address spaces, use a type that includes __attribute__((force)).

Sparse issues these warnings by default. To turn them off, use -Wno-address-space.

-Wbitwise
Warn about unsupported operations or type mismatches with restricted integer types.
Sparse supports an extended attribute, __attribute__((bitwise)), which creates a new restricted integer type from a base integer type, distinct from the base integer type and from any other restricted integer type not declared in the same declaration or typedef. For example, this allows programs to create typedefs for integer types with specific endianness. With -Wbitwise, Sparse will warn on any use of a restricted type in arithmetic operations other than bitwise operations, and on any conversion of one restricted type into another, except via a cast that includes __attribute__((force)).

Sparse does not issue these warnings by default.

-Wcast-to-as
Warn about casts which add an address space to a pointer type.
A cast that includes __attribute__((force)) will suppress this warning.

Sparse does not issue these warnings by default.

-Wcast-truncate
Warn about casts that truncate constant values.
Sparse issues these warnings by default. To turn them off, use -Wno-cast-truncate.

-Wcontext
Warn about potential errors in synchronization or other delimited contexts.
Sparse supports several means of designating functions or statements that delimit contexts, such as synchronization. Functions with the extended attribute __attribute__((context(expression,in_context,out_context)) require the context expression (for instance, a lock) to have the value in_context (a constant nonnegative integer) when called, and return with the value out_context (a constant nonnegative integer). For APIs defined via macros, use the statement form __context__(expression,in_value,out_value) in the body of the macro.

With -Wcontext Sparse will warn when it sees a function change the context without indicating this with a context attribute, either by decreasing a context below zero (such as by releasing a lock without acquiring it), or returning with a changed context (such as by acquiring a lock without releasing it). Sparse will also warn about blocks of code which may potentially execute with different contexts.

Sparse issues these warnings by default. To turn them off, use -Wno-context.

-Wdecl
Warn about any non-static variable or function definition that has no previous declaration.
Private symbols (functions and variables) internal to a given source file should use static, to allow additional compiler optimizations, allow detection of unused symbols, and prevent other code from relying on these internal symbols. Public symbols used by other source files will need declarations visible to those other source files, such as in a header file. All declarations should fall into one of these two categories. Thus, with -Wdecl, Sparse warns about any symbol definition with neither static nor a declaration. To fix this warning, declare private symbols static, and ensure that the files defining public symbols have the symbol declarations available first (such as by including the appropriate header file).

Sparse issues these warnings by default. To turn them off, use -Wno-decl.

-Wdefault-bitfield-sign
Warn about any bitfield with no explicit signedness.
Bitfields have no standard-specified default signedness. (C99 6.7.2) A bitfield without an explicit signed or unsigned creates a portability problem for software that relies on the available range of values. To fix this, specify the bitfield type as signed or unsigned explicitly.

Sparse does not issue these warnings by default.

-Wdo-while
Warn about do-while loops that do not delimit the loop body with braces.
Sparse does not issue these warnings by default.

-Wenum-mismatch
Warn about the use of an expression of an incorrect enum type when initializing another enum type, assigning to another enum type, or passing an argument to a function which expects another enum type.
Sparse issues these warnings by default. To turn them off, use -Wno-enum-mismatch.

-Wnon-pointer-null
Warn about the use of 0 as a NULL pointer.
0 has integer type. NULL has pointer type.

Sparse issues these warnings by default. To turn them off, use -Wno-non-pointer-null.

-Wold-initializer
Warn about the use of the pre-C99 GCC syntax for designated initializers.
C99 provides a standard syntax for designated fields in struct or union initializers:

struct structname var = { .field = value };
GCC also has an old, non-standard syntax for designated initializers which predates C99:
struct structname var = { field: value };
Sparse will warn about the use of GCC's non-standard syntax for designated initializers. To fix this warning, convert designated initializers to use the standard C99 syntax.
Sparse issues these warnings by default. To turn them off, use -Wno-old-initializer.

-Wone-bit-signed-bitfield
Warn about any one-bit signed bitfields.
A one-bit signed bitfield can only have the values 0 and -1, or with some compilers only 0; this results in unexpected behavior for programs which expected the ability to store 0 and 1.

Sparse issues these warnings by default. To turn them off, use -Wno-one-bit-signed-bitfield.

-Wparen-string
Warn about the use of a parenthesized string to initialize an array.
Standard C syntax does not permit a parenthesized string as an array initializer. GCC allows this syntax as an extension. With -Wparen-string, Sparse will warn about this syntax.

Sparse does not issue these warnings by default.

-Wptr-subtraction-blows
Warn when subtracting two pointers to a type with a non-power-of-two size.
Subtracting two pointers to a given type gives a difference in terms of the number of items of that type. To generate this value, compilers will usually need to divide the difference by the size of the type, an potentially expensive operation for sizes other than powers of two.

Code written using pointer subtraction can often use another approach instead, such as array indexing with an explicit array index variable, which may allow compilers to generate more efficient code.

Sparse does not issue these warnings by default.

-Wreturn-void
Warn if a function with return type void returns a void expression.
C99 permits this, and in some cases this allows for more generic code in macros that use typeof or take a type as a macro argument. However, some programs consider this poor style, and those programs can use -Wreturn-void to get warnings about it.

Sparse does not issue these warnings by default.

-Wshadow
Warn when declaring a symbol which shadows a declaration with the same name in an outer scope.
Such declarations can lead to error-prone code.

Sparse does not issue these warnings by default.

-Wtransparent-union
Warn about any declaration using the GCC extension __attribute__((transparent_union)).
Sparse issues these warnings by default. To turn them off, use -Wno-transparent-union.

-Wtypesign
Warn when converting a pointer to an integer type into a pointer to an integer type with different signedness.
Sparse does not issue these warnings by default.

-Wundef
Warn about preprocessor conditionals that use the value of an undefined preprocessor symbol.
Standard C (C99 6.10.1) permits using the value of an undefined preprocessor symbol in preprocessor conditionals, and specifies it has have a value of 0. However, this behavior can lead to subtle errors.

Sparse does not issue these warnings by default.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 16:51 , Processed in 0.090058 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表