llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.81k stars 11.91k forks source link

[clang static analyzer] core.NullDereference false positive with `*r = 42` #60026

Open 0-0x41 opened 1 year ago

0-0x41 commented 1 year ago

I got a false positive error when compiling the following program with clang(trunk) --analyze -Xclang -analyzer-stats -Xclang -analyzer-checker=core,debug.ExprInspection https://godbolt.org/z/Pae9xqrWT.

In this case, the eval result on line 17 is TRUE, and apparently analyzer is known to fact that the result of (-g.e.b && g.e.c) is FALSE, yet it continues to do analysis of the code inside the if statement, which is unreachable code.

Here is the analysis result of the case. Thank you for taking the time to review this case.

Input:

#include "stdio.h"
#include "stdbool.h"
void clang_analyzer_eval();

struct a
{
    int b;
    int c;
};

union d
{
    struct a e
} main()
{
    union d g = {};
    int *r = (int *)0;
    clang_analyzer_eval((-g.e.b && g.e.c) == false);
    if (-g.e.b && g.e.c)
    {
        *r = 42;
    }
}

Output:

<source>:17:5: warning: TRUE [debug.ExprInspection]
    clang_analyzer_eval((-g.e.b && g.e.c) == false);
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:20:12: warning: Dereference of null pointer (loaded from variable 'r') [core.NullDereference]
        *r = 42;
llvmbot commented 1 year ago

@llvm/issue-subscribers-clang-static-analyzer

davidstone commented 1 year ago

Reduced:

void clang_analyzer_eval();

union d {
    int e;
};

int main() {
    union d g = {};
    clang_analyzer_eval(-g.e && g.e);
    if (-g.e && g.e) {
        *(int *)0;
    }
}

Outputs

<source>:9:2: warning: FALSE [debug.ExprInspection]
        clang_analyzer_eval(-g.e && g.e);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:11:3: warning: Dereference of null pointer [core.NullDereference]
                *(int *)0;
                ^~~~~~~~~

See it live: https://godbolt.org/z/MaKbjbGxK