r365582 - [analyzer] CastValueChecker: Model casts

Csaba Dabis via cfe-commits cfe-commits at lists.llvm.org
Tue Jul 9 16:33:23 PDT 2019


Author: charusso
Date: Tue Jul  9 16:33:23 2019
New Revision: 365582

URL: http://llvm.org/viewvc/llvm-project?rev=365582&view=rev
Log:
[analyzer] CastValueChecker: Model casts

Summary:
It models the LLVM casts:
- `cast<>`
- `dyn_cast<>`
- `cast_or_null<>`
- `dyn_cast_or_null<>`

It has a very basic support without checking the `classof()` function.

Reviewed By: NoQ

Tags: #clang

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

Added:
    cfe/trunk/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
    cfe/trunk/test/Analysis/cast-value.cpp
Modified:
    cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
    cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
    cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
    cfe/trunk/test/Analysis/return-value-guaranteed.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=365582&r1=365581&r2=365582&view=diff
==============================================================================
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Tue Jul  9 16:33:23 2019
@@ -100,6 +100,7 @@ def LLVMAlpha : Package<"llvm">, ParentP
 // intended for API modeling that is not controlled by the target triple.
 def APIModeling : Package<"apiModeling">, Hidden;
 def GoogleAPIModeling : Package<"google">, ParentPackage<APIModeling>, Hidden;
+def LLVMAPIModeling : Package<"llvm">, ParentPackage<APIModeling>, Hidden;
 
 def Debug : Package<"debug">, Hidden;
 
@@ -274,10 +275,6 @@ def NullableReturnedFromNonnullChecker :
 
 let ParentPackage = APIModeling in {
 
-def ReturnValueChecker : Checker<"ReturnValue">,
-  HelpText<"Model the guaranteed boolean return value of function calls">,
-  Documentation<NotDocumented>;
-
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
   Documentation<NotDocumented>;
@@ -1109,6 +1106,18 @@ def LLVMConventionsChecker : Checker<"Co
 
 } // end "llvm"
 
+let ParentPackage = LLVMAPIModeling in {
+
+def CastValueChecker : Checker<"CastValue">,
+  HelpText<"Model implementation of custom RTTIs">,
+  Documentation<NotDocumented>;
+
+def ReturnValueChecker : Checker<"ReturnValue">,
+  HelpText<"Model the guaranteed boolean return value of function calls">,
+  Documentation<NotDocumented>;
+
+} // end "apiModeling.llvm"
+
 //===----------------------------------------------------------------------===//
 // Checkers modeling Google APIs.
 //===----------------------------------------------------------------------===//

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h?rev=365582&r1=365581&r2=365582&view=diff
==============================================================================
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h Tue Jul  9 16:33:23 2019
@@ -247,6 +247,17 @@ public:
         IsPrunable);
   }
 
+  /// A shorthand version of getNoteTag that accepts a plain note.
+  ///
+  /// @param Note The note.
+  /// @param IsPrunable Whether the note is prunable. It allows BugReporter
+  ///        to omit the note from the report if it would make the displayed
+  ///        bug path significantly shorter.
+  const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
+    return getNoteTag(
+        [Note](BugReporterContext &, BugReport &) { return Note; }, IsPrunable);
+  }
+
   /// Returns the word that should be used to refer to the declaration
   /// in the report.
   StringRef getDeclDescription(const Decl *D);

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=365582&r1=365581&r2=365582&view=diff
==============================================================================
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Tue Jul  9 16:33:23 2019
@@ -16,6 +16,7 @@ add_clang_library(clangStaticAnalyzerChe
   CallAndMessageChecker.cpp
   CastSizeChecker.cpp
   CastToStructChecker.cpp
+  CastValueChecker.cpp
   CheckObjCDealloc.cpp
   CheckObjCInstMethSignature.cpp
   CheckSecuritySyntaxOnly.cpp

Added: cfe/trunk/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp?rev=365582&view=auto
==============================================================================
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp (added)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp Tue Jul  9 16:33:23 2019
@@ -0,0 +1,190 @@
+//===- CastValueChecker - Model implementation of custom RTTIs --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This defines CastValueChecker which models casts of custom RTTIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/Optional.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class CastValueChecker : public Checker<eval::Call> {
+  using CastCheck =
+      std::function<void(const CastValueChecker *, const CallExpr *,
+                         DefinedOrUnknownSVal, CheckerContext &)>;
+
+public:
+  // We have three cases to evaluate a cast:
+  // 1) The parameter is non-null, the return value is non-null
+  // 2) The parameter is non-null, the return value is null
+  // 3) The parameter is null, the return value is null
+  //
+  // cast: 1;  dyn_cast: 1, 2;  cast_or_null: 1, 3;  dyn_cast_or_null: 1, 2, 3.
+  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
+
+private:
+  // These are known in the LLVM project.
+  const CallDescriptionMap<CastCheck> CDM = {
+      {{{"llvm", "cast"}, 1}, &CastValueChecker::evalCast},
+      {{{"llvm", "dyn_cast"}, 1}, &CastValueChecker::evalDynCast},
+      {{{"llvm", "cast_or_null"}, 1}, &CastValueChecker::evalCastOrNull},
+      {{{"llvm", "dyn_cast_or_null"}, 1},
+       &CastValueChecker::evalDynCastOrNull}};
+
+  void evalCast(const CallExpr *CE, DefinedOrUnknownSVal ParamDV,
+                CheckerContext &C) const;
+  void evalDynCast(const CallExpr *CE, DefinedOrUnknownSVal ParamDV,
+                   CheckerContext &C) const;
+  void evalCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal ParamDV,
+                      CheckerContext &C) const;
+  void evalDynCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal ParamDV,
+                         CheckerContext &C) const;
+};
+} // namespace
+
+static std::string getCastName(const Expr *Cast) {
+  return Cast->getType()->getPointeeCXXRecordDecl()->getNameAsString();
+}
+
+static void evalNonNullParamNonNullReturn(const CallExpr *CE,
+                                          DefinedOrUnknownSVal ParamDV,
+                                          CheckerContext &C) {
+  ProgramStateRef State = C.getState()->assume(ParamDV, true);
+  if (!State)
+    return;
+
+  State = State->BindExpr(CE, C.getLocationContext(), ParamDV, false);
+
+  std::string CastFromName = getCastName(CE->getArg(0));
+  std::string CastToName = getCastName(CE);
+
+  const NoteTag *CastTag = C.getNoteTag(
+      [CastFromName, CastToName](BugReport &) -> std::string {
+        SmallString<128> Msg;
+        llvm::raw_svector_ostream Out(Msg);
+
+        Out << "Assuming dynamic cast from '" << CastFromName << "' to '"
+            << CastToName << "' succeeds";
+        return Out.str();
+      },
+      /*IsPrunable=*/true);
+
+  C.addTransition(State, CastTag);
+}
+
+static void evalNonNullParamNullReturn(const CallExpr *CE,
+                                       DefinedOrUnknownSVal ParamDV,
+                                       CheckerContext &C) {
+  ProgramStateRef State = C.getState()->assume(ParamDV, true);
+  if (!State)
+    return;
+
+  State = State->BindExpr(CE, C.getLocationContext(),
+                          C.getSValBuilder().makeNull(), false);
+
+  std::string CastFromName = getCastName(CE->getArg(0));
+  std::string CastToName = getCastName(CE);
+
+  const NoteTag *CastTag = C.getNoteTag(
+      [CastFromName, CastToName](BugReport &) -> std::string {
+        SmallString<128> Msg;
+        llvm::raw_svector_ostream Out(Msg);
+
+        Out << "Assuming dynamic cast from '" << CastFromName << "' to '"
+            << CastToName << "' fails";
+        return Out.str();
+      },
+      /*IsPrunable=*/true);
+
+  C.addTransition(State, CastTag);
+}
+
+static void evalNullParamNullReturn(const CallExpr *CE,
+                                    DefinedOrUnknownSVal ParamDV,
+                                    CheckerContext &C) {
+  ProgramStateRef State = C.getState()->assume(ParamDV, false);
+  if (!State)
+    return;
+
+  State = State->BindExpr(CE, C.getLocationContext(),
+                          C.getSValBuilder().makeNull(), false);
+
+  const NoteTag *CastTag =
+      C.getNoteTag("Assuming null pointer is passed into cast",
+                   /*IsPrunable=*/true);
+
+  C.addTransition(State, CastTag);
+}
+
+void CastValueChecker::evalCast(const CallExpr *CE,
+                                DefinedOrUnknownSVal ParamDV,
+                                CheckerContext &C) const {
+  evalNonNullParamNonNullReturn(CE, ParamDV, C);
+}
+
+void CastValueChecker::evalDynCast(const CallExpr *CE,
+                                   DefinedOrUnknownSVal ParamDV,
+                                   CheckerContext &C) const {
+  evalNonNullParamNonNullReturn(CE, ParamDV, C);
+  evalNonNullParamNullReturn(CE, ParamDV, C);
+}
+
+void CastValueChecker::evalCastOrNull(const CallExpr *CE,
+                                      DefinedOrUnknownSVal ParamDV,
+                                      CheckerContext &C) const {
+  evalNonNullParamNonNullReturn(CE, ParamDV, C);
+  evalNullParamNullReturn(CE, ParamDV, C);
+}
+
+void CastValueChecker::evalDynCastOrNull(const CallExpr *CE,
+                                         DefinedOrUnknownSVal ParamDV,
+                                         CheckerContext &C) const {
+  evalNonNullParamNonNullReturn(CE, ParamDV, C);
+  evalNonNullParamNullReturn(CE, ParamDV, C);
+  evalNullParamNullReturn(CE, ParamDV, C);
+}
+
+bool CastValueChecker::evalCall(const CallEvent &Call,
+                                CheckerContext &C) const {
+  const CastCheck *Check = CDM.lookup(Call);
+  if (!Check)
+    return false;
+
+  const auto *CE = cast<CallExpr>(Call.getOriginExpr());
+  if (!CE)
+    return false;
+
+  // If we cannot obtain both of the classes we cannot be sure how to model it.
+  if (!CE->getType()->getPointeeCXXRecordDecl() ||
+      !CE->getArg(0)->getType()->getPointeeCXXRecordDecl())
+    return false;
+
+  SVal ParamV = Call.getArgSVal(0);
+  auto ParamDV = ParamV.getAs<DefinedOrUnknownSVal>();
+  if (!ParamDV)
+    return false;
+
+  (*Check)(this, CE, *ParamDV, C);
+  return true;
+}
+
+void ento::registerCastValueChecker(CheckerManager &Mgr) {
+  Mgr.registerChecker<CastValueChecker>();
+}
+
+bool ento::shouldRegisterCastValueChecker(const LangOptions &LO) {
+  return true;
+}

Added: cfe/trunk/test/Analysis/cast-value.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cast-value.cpp?rev=365582&view=auto
==============================================================================
--- cfe/trunk/test/Analysis/cast-value.cpp (added)
+++ cfe/trunk/test/Analysis/cast-value.cpp Tue Jul  9 16:33:23 2019
@@ -0,0 +1,133 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -verify=logic %s
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue \
+// RUN:  -analyzer-output=text -verify %s
+
+void clang_analyzer_numTimesReached();
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(bool);
+
+template <class X, class Y>
+const X *cast(Y Value);
+
+template <class X, class Y>
+const X *dyn_cast(Y Value);
+
+template <class X, class Y>
+const X *cast_or_null(Y Value);
+
+template <class X, class Y>
+const X *dyn_cast_or_null(Y Value);
+
+class Shape {};
+class Triangle : public Shape {};
+class Circle : public Shape {};
+
+namespace test_cast {
+void evalLogic(const Shape *S) {
+  const Circle *C = cast<Circle>(S);
+  clang_analyzer_numTimesReached(); // logic-warning {{1}}
+
+  if (S && C)
+    clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+  if (S && !C)
+    clang_analyzer_warnIfReached(); // no-warning
+
+  if (!S)
+    clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_cast
+
+namespace test_dyn_cast {
+void evalLogic(const Shape *S) {
+  const Circle *C = dyn_cast<Circle>(S);
+  clang_analyzer_numTimesReached(); // logic-warning {{2}}
+
+  if (S && C)
+    clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+  if (S && !C)
+    clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
+
+  if (!S)
+    clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_dyn_cast
+
+namespace test_cast_or_null {
+void evalLogic(const Shape *S) {
+  const Circle *C = cast_or_null<Circle>(S);
+  clang_analyzer_numTimesReached(); // logic-warning {{2}}
+
+  if (S && C)
+    clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+  if (S && !C)
+    clang_analyzer_warnIfReached(); // no-warning
+
+  if (!S)
+    clang_analyzer_eval(!C); // logic-warning {{TRUE}}
+}
+} // namespace test_cast_or_null
+
+namespace test_dyn_cast_or_null {
+void evalLogic(const Shape *S) {
+  const Circle *C = dyn_cast_or_null<Circle>(S);
+  clang_analyzer_numTimesReached(); // logic-warning {{3}}
+
+  if (S && C)
+    clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+  if (S && !C)
+    clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
+
+  if (!S)
+    clang_analyzer_eval(!C); // logic-warning {{TRUE}}
+}
+
+void evalNonNullParamNonNullReturn(const Shape *S) {
+  const auto *C = dyn_cast_or_null<Circle>(S);
+  // expected-note at -1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}}
+  // expected-note at -2 {{Assuming pointer value is null}}
+  // expected-note at -3 {{'C' initialized here}}
+
+  (void)(1 / !(bool)C);
+  // expected-note at -1 {{'C' is non-null}}
+  // expected-note at -2 {{Division by zero}}
+  // expected-warning at -3 {{Division by zero}}
+  // logic-warning at -4 {{Division by zero}}
+}
+
+void evalNonNullParamNullReturn(const Shape *S) {
+  const auto *C = dyn_cast_or_null<Circle>(S);
+  // expected-note at -1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}}
+  // expected-note at -2 {{Assuming pointer value is null}}
+
+  if (const auto *T = dyn_cast_or_null<Triangle>(S)) {
+    // expected-note at -1 {{Assuming dynamic cast from 'Shape' to 'Triangle' succeeds}}
+    // expected-note at -2 {{'T' initialized here}}
+    // expected-note at -3 {{'T' is non-null}}
+    // expected-note at -4 {{Taking true branch}}
+
+    (void)(1 / !T);
+    // expected-note at -1 {{'T' is non-null}}
+    // expected-note at -2 {{Division by zero}}
+    // expected-warning at -3 {{Division by zero}}
+    // logic-warning at -4 {{Division by zero}}
+  }
+}
+
+void evalNullParamNullReturn(const Shape *S) {
+  const auto *C = dyn_cast_or_null<Circle>(S);
+  // expected-note at -1 {{Assuming null pointer is passed into cast}}
+  // expected-note at -2 {{'C' initialized to a null pointer value}}
+
+  (void)(1 / (bool)C);
+  // expected-note at -1 {{Division by zero}}
+  // expected-warning at -2 {{Division by zero}}
+  // logic-warning at -3 {{Division by zero}}
+}
+} // namespace test_dyn_cast_or_null

Modified: cfe/trunk/test/Analysis/return-value-guaranteed.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/return-value-guaranteed.cpp?rev=365582&r1=365581&r2=365582&view=diff
==============================================================================
--- cfe/trunk/test/Analysis/return-value-guaranteed.cpp (original)
+++ cfe/trunk/test/Analysis/return-value-guaranteed.cpp Tue Jul  9 16:33:23 2019
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 \
-// RUN:  -analyzer-checker=core,apiModeling.ReturnValue \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.ReturnValue \
 // RUN:  -analyzer-output=text -verify=class %s
 
 struct Foo { int Field; };




More information about the cfe-commits mailing list