[clang] 5a2e595 - [analyzer] Fix Static Analyzer g_memdup false-positive

Balazs Benics via cfe-commits cfe-commits at lists.llvm.org
Mon May 2 01:36:16 PDT 2022


Author: Balazs Benics
Date: 2022-05-02T10:35:51+02:00
New Revision: 5a2e595eb8337e6e36da8ec2289b5c4097522f5b

URL: https://github.com/llvm/llvm-project/commit/5a2e595eb8337e6e36da8ec2289b5c4097522f5b
DIFF: https://github.com/llvm/llvm-project/commit/5a2e595eb8337e6e36da8ec2289b5c4097522f5b.diff

LOG: [analyzer] Fix Static Analyzer g_memdup false-positive

`g_memdup()` allocates and copies memory, thus we should not assume that
the returned memory region is uninitialized because it might not be the
case.

PS: It would be even better to copy the bindings to mimic the actual
content of the buffer, but this works too.

Fixes #53617

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D124436

Added: 
    

Modified: 
    clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
    clang/test/Analysis/gmalloc.c

Removed: 
    


################################################################################
diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 0bbef394f43e5..ae9a7bc6a3914 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1408,8 +1408,8 @@ void MallocChecker::checkGMalloc0(const CallEvent &Call,
 void MallocChecker::checkGMemdup(const CallEvent &Call,
                                  CheckerContext &C) const {
   ProgramStateRef State = C.getState();
-  State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
-                       AF_Malloc);
+  State =
+      MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State, AF_Malloc);
   State = ProcessZeroAllocCheck(Call, 1, State);
   C.addTransition(State);
 }

diff  --git a/clang/test/Analysis/gmalloc.c b/clang/test/Analysis/gmalloc.c
index 51f972856b1bb..240138e8a7a05 100644
--- a/clang/test/Analysis/gmalloc.c
+++ b/clang/test/Analysis/gmalloc.c
@@ -21,6 +21,7 @@ gpointer g_try_malloc0_n(gsize n_blocks, gsize n_block_bytes);
 gpointer g_try_realloc_n(gpointer mem, gsize n_blocks, gsize n_block_bytes);
 void g_free(gpointer mem);
 gpointer g_memdup(gconstpointer mem, guint byte_size);
+gpointer g_strconcat(gconstpointer string1, ...);
 
 static const gsize n_bytes = 1024;
 
@@ -167,3 +168,16 @@ void f7(void) {
   g_free(g6);
   g_free(g7);
 }
+
+void f8(void) {
+  typedef struct {
+    gpointer str;
+  } test_struct;
+
+  test_struct *s1 = (test_struct *)g_malloc0(sizeof(test_struct));
+  test_struct *s2 = (test_struct *)g_memdup(s1, sizeof(test_struct));
+  gpointer str = g_strconcat("text", s1->str, s2->str, NULL); // no-warning
+  g_free(str);
+  g_free(s2);
+  g_free(s1);
+}


        


More information about the cfe-commits mailing list