[clang] [clang][analyzer] Restrict 'fopen' & 'tmpfile' modeling to POSIX versions in StreamChecker (PR #70540)

Ben Shi via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 2 01:17:02 PDT 2023


https://github.com/benshi001 updated https://github.com/llvm/llvm-project/pull/70540

>From bf36469281f52fe34866e6df5eeafdc51d28819c Mon Sep 17 00:00:00 2001
From: Ben Shi <bennshi at tencent.com>
Date: Tue, 31 Oct 2023 13:05:19 +0800
Subject: [PATCH] [clang][analyzer] Restrict 'fopen' & 'tmpfile' modeling to
 POSIX versions in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp |  4 ++--
 .../test/Analysis/stream-non-posix-function.c | 20 +++++++++++++++++++
 2 files changed, 22 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/Analysis/stream-non-posix-function.c

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 4b7103c20557cc4..7e8031c7545f691 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -238,10 +238,10 @@ class StreamChecker : public Checker<check::PreCall, eval::Call,
 
 private:
   CallDescriptionMap<FnDescription> FnDescriptions = {
-      {{{"fopen"}}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
+      {{{"fopen"}, 2}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
       {{{"freopen"}, 3},
        {&StreamChecker::preFreopen, &StreamChecker::evalFreopen, 2}},
-      {{{"tmpfile"}}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
+      {{{"tmpfile"}, 0}, {nullptr, &StreamChecker::evalFopen, ArgNone}},
       {{{"fclose"}, 1},
        {&StreamChecker::preDefault, &StreamChecker::evalFclose, 0}},
       {{{"fread"}, 4},
diff --git a/clang/test/Analysis/stream-non-posix-function.c b/clang/test/Analysis/stream-non-posix-function.c
new file mode 100644
index 000000000000000..3caabb4b097384a
--- /dev/null
+++ b/clang/test/Analysis/stream-non-posix-function.c
@@ -0,0 +1,20 @@
+// RUN: %clang_analyze_cc1 -fno-builtin -analyzer-checker=core,alpha.unix.Stream -verify %s
+// expected-no-diagnostics
+
+typedef struct _FILE FILE;
+
+// These functions are not standard C library functions.
+FILE *tmpfile(const char *restrict path); // Real 'tmpfile' should have exactly 0 formal parameters.
+FILE *fopen(const char *restrict path);   // Real 'fopen' should have exactly 2 formal parameters.
+
+void test_fopen_non_posix(void) {
+  FILE *fp = fopen("file");
+  // no-leak: this isn't the standard POSIX fopen, so we do not treat
+  // `fp` as a new opened local file stream.
+}
+
+void test_tmpfile_non_posix(void) {
+  FILE *fp = tmpfile("file");
+  // no-leak: this isn't the standard POSIX tmpfile, so we do not treat
+  // `fp` as a new opened local file stream.
+}



More information about the cfe-commits mailing list