llvm / llvm-project

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

`-Wuninitialized` does not take `malloc` function attribute into account #66448

Open kees opened 12 months ago

kees commented 12 months ago

The malloc function attribute indicates that the newly allocated memory is uninitialized. This doesn't appear to be informing the -Wuninitialized diagnostics, though:

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

void foo(void)
{
        int *p = malloc(sizeof(*p));
        printf("%d\n", *p);
}

Building with -Wall, Clang produces no warnings, but GCC does:

https://godbolt.org/z/K8Ga18KoM

It looks like the IR does know that malloc is allockind("alloc,uninitialized"), so I imagine something isn't fully wired up:

; Function Attrs: mustprogress nofree nounwind willreturn allockind("alloc,uninitialized") allocsize(0)
memory(inaccessiblemem: readwrite)
declare noalias noundef ptr @malloc(i64 noundef) local_unnamed_addr #3
...
attributes #3 = { mustprogress nofree nounwind willreturn allockind("alloc,uninitialized") allocsize(0)
memory(inaccessiblemem: readwrite) "alloc-family"="malloc" "no-trapping-math"="true" "stack-protector-buffer-size"="8"
"target-cpu"="x86-64" "target-features"="+cmov,+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }

@nickdesaulniers @isanbard

kees commented 12 months ago

Hm, it's not a false positive, it's a false negative. :)

dwblaikie commented 11 months ago

& generally clang's diagnostics can't handle dynamic/indirect memory like this - so I wouldn't expect this to be covered by a compiler warning - /maybe/ by a static analysis tool, but even then, that's going to be challenging.

hstk30-hw commented 11 months ago

So, can we compromise to warning just for malloc? I think malloc is a special function. Is easy to impl? Maybe I can do it.

dwblaikie commented 11 months ago

It's not so much a question of special casing malloc, but tracking memory that's pointed to by a pointer. That's outside the scope of the sort of analysis we can do at compile time.