You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写CodeQL脚本检查链式指针字段访问前的空值校验

CodeQL 实现多级指针访问非空检查的问题

目标场景C代码示例

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int name;
} type4;

typedef struct {
    int name;
    type4 *p4;
} type3;

typedef struct {
    int name;
    type3 *p3;
} type2;

typedef struct {
    int name;
    type2* p2;
} type1;

int main(void){

    type1 *p1       = malloc(sizeof(type1));
    p1->p2          = malloc(sizeof(type2));
    p1->p2->p3      = malloc(sizeof(type3));
    p1->p2->p3->p4  = malloc(sizeof(type4));

    printf("p4: %d\n", p1->p2->p3->p4->name);

    free(p1->p2->p3->p4);
    free(p1->p2->p3);
    free(p1->p2);
    free(p1);

    return 0;
}

需求说明

需要编写CodeQL脚本实现以下校验:

  • 访问p1->p2前,检查p1的非空性,即if(p1) { p1->p2; }
  • 访问p1->p2->p3前,检查p1->p2的非空性,即if(p1->p2){ p1->p2->p3; }
  • ……(以此类推)

当前遇到的问题

在使用污点追踪等技术前,需要先找到能表示p1、p1->p2、p1->p2->p3这类完整指针链的方法,但目前无法实现。

现有尝试的脚本仅能返回单个字段(如p1、p2、p3等),无法捕获p1->p2->p3这类完整指针链,且concat不支持PointerFieldAccess这类复杂类型,无法合并结果。

尝试的CodeQL脚本

/**
* @id pointers-test
* @kind problem
* @problem.severity warning
*/

import cpp

class StartOfPointerFieldAccess extends Variable {
    StartOfPointerFieldAccess(){
    exists(PointerFieldAccess pfa, LocalVariable v|
        v.getType() instanceof PointerType
        and pfa.getQualifier+().(VariableAccess).getTarget() = v
        and this = v
        )
    }
}

from PointerFieldAccess pfa, StartOfPointerFieldAccess pv
where pfa.getQualifier+().(VariableAccess).getTarget() = pv
select pfa, "Interesting Pointer Field Access."

内容的提问来源于stack exchange,提问作者pitboy1o1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 23:33:29