codeql icon indicating copy to clipboard operation
codeql copied to clipboard

C: Question aboutDataFlow Analyse

Open icy17 opened this issue 3 years ago • 2 comments
trafficstars

Hi, I learn how to write ql to do dataflow analyse, and then I want to detect memory leak like missing free after malloc. But I met a problem, I don't know how to solve this problem. C demo:

char* gen_ptr(void)
{
    char* a = malloc(1);
    return a;
}
int main(void)
{
    char* a;
    a = gen_ptr();
    a = gen_ptr();
    free(a);
    return 0;
}

In this code, gen_ptr is called twice, but only freed in the end, there is a memory leak because the first a is not freed. I use dataflow analyse and want to detect malloc in the first gen_ptr doesn't have a free as sink. But I faild....because malloc in gen_ptr does have a sink in the second one!!! I think for a long time but do not know how to solve this problem :(

icy17 avatar Sep 22 '22 12:09 icy17

One potential solution to the problem you're facing could be to add a barrier in your dataflow that stops the data flow when a is re-defined. Adding this barrier would mean that there would be no flow from the first a = gen_ptr(); to free(a); because the second a = gen_ptr(); would act as a barrier. For an example of how this works in practice, I'd recommend you take a look at this query which does something similar to what you're trying to do (it's detecting usage of memory that has been freed) and uses this technique: https://github.com/github/codeql/blob/main/cpp/ql/src/Critical/UseAfterFree.ql

In particular, the barrier condition is here: https://github.com/github/codeql/blob/2fe6d1f562ba47f6299b1114c3d49062d654a34c/cpp/ql/src/Critical/UseAfterFree.ql#L57-L60

edoardopirovano avatar Sep 22 '22 13:09 edoardopirovano

@edoardopirovano Thank you for your answer. I know how to detect re-defined in a local scope, but when I want to detect a re-defined in a global scope, it become a little bit difficult, and I don't know how to detect it.... Is there a simple method for global detection?

icy17 avatar Sep 23 '22 09:09 icy17