[clang] [clang][analyzer] Support 'fflush' in the StdLibraryFunctionsChecker (PR #76557)

Ben Shi via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 29 00:46:03 PST 2023


https://github.com/benshi001 created https://github.com/llvm/llvm-project/pull/76557

None

>From 2eebb462b8a7865684d3baaffbad7560eed10e57 Mon Sep 17 00:00:00 2001
From: Ben Shi <bennshi at tencent.com>
Date: Fri, 29 Dec 2023 16:44:47 +0800
Subject: [PATCH] [clang][analyzer] Support 'fflush' in the
 StdLibraryFunctionsChecker

---
 .../Checkers/StdLibraryFunctionsChecker.cpp   |  8 ++++++
 clang/test/Analysis/stream-errno.c            | 26 +++++++++++++++++++
 2 files changed, 34 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index fffcaf7ed18fb7..4ca49b9c0546d9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2244,6 +2244,14 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
             .ArgConstraint(NotNull(ArgNo(0)))
             .ArgConstraint(NotNull(ArgNo(1))));
 
+    // int fflush(FILE *stream);
+    addToFunctionSummaryMap(
+        "fflush", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
+        Summary(NoEvalCall)
+            .Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg)
+            .Case({ReturnValueCondition(WithinRange, SingleValue(EOFv))},
+                  ErrnoNEZeroIrrelevant, GenericFailureMsg));
+
     // long ftell(FILE *stream);
     // From 'The Open Group Base Specifications Issue 7, 2018 edition':
     // "The ftell() function shall not change the setting of errno if
diff --git a/clang/test/Analysis/stream-errno.c b/clang/test/Analysis/stream-errno.c
index bf0a61db2424f9..d52480741d4cd1 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -222,3 +222,29 @@ void check_fileno(void) {
   }
   if (errno) {} // expected-warning{{An undefined value may be read from 'errno'}}
 }
+
+void check_fflush_0(void) {
+  FILE *F = tmpfile();
+  if (!F)
+    return;
+  int N = fflush(F);
+  if (N == EOF) {
+    clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+    if (errno) {}                    // no-warning
+  } else {
+    clang_analyzer_eval(N == 0);     // expected-warning{{TRUE}}
+    if (errno) {}                    // expected-warning{{An undefined value may be read from 'errno'}}
+  }
+  fclose(F);
+}
+
+void check_fflush_1(void) {
+  int N = fflush(NULL);
+  if (N == 0) {
+    if (errno) {}                    // expected-warning{{An undefined value may be read from 'errno'}}
+  } else {
+    clang_analyzer_eval(N == EOF);   // expected-warning{{TRUE}}
+    clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+    if (errno) {}                    // no-warning
+  }
+}



More information about the cfe-commits mailing list