首页 > 解决方案 > 如何查找某种类型的所有赋值表达式

问题描述

假设我有一些结构定义,例如

struct sql_subtype {
    sql_type *type;
    unsigned int digits;
    unsigned int scale;
}

这个结构 sql_subtype 在我的代码库中到处使用,它非常庞大。这种类型的对象通常是其他对象的成员。如此简单的字符串匹配不足以找到分配位置。是否有一些不错的技巧或开源静态分析工具可以为我提供代码库中任何此类对象被设置为某个值的位置?查找所有类似的位置

struct sql_subtype type1 = type2;

或者

c1->t = c2->t; // where the t's are of the type of interest.

等等

一般问题:给定涉及返回某种类型的某个运算符的表达式类,我如何找到包含该类表达式的所有语句?

标签: cstatic-analysis

解决方案


这不是一个通用的解决方案,但有一种方法可以struct单独使用 C 编译器找到分配。C 允许您将struct 的成员声明为,因此您可以在声明为const的 中添加一个额外的成员,并且只有分配会失败:structconst

struct sql_subtype {
    unsigned int digits;
    unsigned int scale;
    const unsigned int poison_pill;
};

void function_call(struct sql_subtype foo) {
    struct sql_subtype initialized_from_copy = foo;
    initialized_from_copy.digits = 42;
    struct sql_subtype another = {0};
    another = foo;
}

// if the const member is the last one even initializer lists will work!
struct sql_subtype initialized = {1, 2};

int main(void) {
    function_call(initialized);
}

用 GCC 编译,你得到的唯一诊断是

constmemberhack.c: In function ‘function_call’:
constmemberhack.c:10:13: error: assignment of read-only variable ‘another’
     another = foo;
             ^

推荐阅读