2

作为回归测试的一部分,我想使用静态分析来确保标头中定义的 C 符号与 a 的基本类型具有相同的类型typedef,后者也在同一个标​​头中定义。

鉴于我正在使用gcc(连同它的扩展)并且可以生成 DWARF 调试信息,我实现这一点的策略如下:

test.c

#include <my/header.h>

my_type x;
typeof (MY_SYMBOL) y;

/* MY_SYMBOL should be of the same type as my_type.  */

然后执行:

$ gcc -O0 -g -c test.c -o test.o
$ dwarfdump test.o > test.dump

这是来自的相关片段test.dump

LOCAL_SYMBOLS:
< 1><0x00000032>    DW_TAG_typedef
                      DW_AT_name                  my_type
                      DW_AT_decl_file             0x00000002 my/header.h
                      DW_AT_decl_line             0x00000145
                      DW_AT_type                  <0x0000003e>
< 1><0x0000003e>    DW_TAG_base_type
                      DW_AT_byte_size             0x00000004
                      DW_AT_encoding              DW_ATE_signed
                      DW_AT_name                  int
< 1><0x00000053>    DW_TAG_variable
                      DW_AT_name                  x
                      DW_AT_decl_file             0x00000001 test.c
                      DW_AT_decl_line             0x00000003
                      DW_AT_type                  <0x00000032>
                      DW_AT_external              yes(1)
< 1><0x00000068>    DW_TAG_variable
                      DW_AT_name                  y
                      DW_AT_decl_file             0x00000001 test.c
                      DW_AT_decl_line             0x00000004
                      DW_AT_type                  <0x0000003e>

如果您按照DW_AT_typeDWARF 信息中的地址,您将看到typedef( my_type) 和符号 ( MY_SYMBOL) 确实属于同一类型 ( int)。即这个测试通过了。

当然,我需要解析这个调试信息(可能是一个 perl/python 脚本),以证明每次测试用例运行时都会自动证明这一点。我的问题是:有没有更清洁/更简单的方法来做到这一点?

4

1 回答 1

2

由于您使用的是 GCC,因此您可以使用__builtin_types_compatible_p内置:

if (__builtin_types_compatible_p(typeof(x), typeof(y))) {
    // x and y are of the same type
}

引用GCC 内置手册

您可以使用内置函数 __builtin_types_compatible_p 来确定两种类型是否相同。

如果类型 type1 和 type2(它们是类型,不是表达式)的非限定版本兼容,则此内置函数返回 1,否则返回 0。此内置函数的结果可用于整数常量表达式。

此内置函数忽略顶级限定符(例如,const、volatile)。例如,int 等价于 const int。

int[] 和 int[5] 类型是兼容的。另一方面,int 和 char * 是不兼容的,即使它们的类型的大小在特定架构上是相同的。此外,在确定相似度时还要考虑指针间接的数量。因此,short * 与 short ** 不同。此外,如果它们的基础类型兼容,则类型定义的两种类型被认为是兼容的。

于 2014-09-25T13:58:51.160 回答