xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/GTestChecker.cpp (revision 8beac28564e9769efa9f473bafe6a5ff8d0e88b3)
1 //==- GTestChecker.cpp - Model gtest API --*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This checker models the behavior of un-inlined APIs from the the gtest
11 // unit-testing library to avoid false positives when using assertions from
12 // that library.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "ClangSACheckers.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 using namespace clang;
26 using namespace ento;
27 
28 // Modeling of un-inlined AssertionResult constructors
29 //
30 // The gtest unit testing API provides macros for assertions that expand
31 // into an if statement that calls a series of constructors and returns
32 // when the "assertion" is false.
33 //
34 // For example,
35 //
36 //   ASSERT_TRUE(a == b)
37 //
38 // expands into:
39 //
40 //   switch (0)
41 //   case 0:
42 //   default:
43 //     if (const ::testing::AssertionResult gtest_ar_ =
44 //             ::testing::AssertionResult((a == b)))
45 //       ;
46 //     else
47 //       return ::testing::internal::AssertHelper(
48 //                  ::testing::TestPartResult::kFatalFailure,
49 //                  "<path to project>",
50 //                  <line number>,
51 //                  ::testing::internal::GetBoolAssertionFailureMessage(
52 //                      gtest_ar_, "a == b", "false", "true")
53 //                      .c_str()) = ::testing::Message();
54 //
55 // where AssertionResult is defined similarly to
56 //
57 //   class AssertionResult {
58 //   public:
59 //     AssertionResult(const AssertionResult& other);
60 //     explicit AssertionResult(bool success) : success_(success) {}
61 //     operator bool() const { return success_; }
62 //     ...
63 //     private:
64 //     bool success_;
65 //   };
66 //
67 // In order for the analyzer to correctly handle this assertion, it needs to
68 // know that the boolean value of the expression "a == b" is stored the
69 // 'success_' field of the original AssertionResult temporary and propagated
70 // (via the copy constructor) into the 'success_' field of the object stored
71 // in 'gtest_ar_'.  That boolean value will then be returned from the bool
72 // conversion method in the if statement. This guarantees that the assertion
73 // holds when the return path is not taken.
74 //
75 // If the success value is not properly propagated, then the eager case split
76 // on evaluating the expression can cause pernicious false positives
77 // on the non-return path:
78 //
79 //   ASSERT(ptr != NULL)
80 //   *ptr = 7; // False positive null pointer dereference here
81 //
82 // Unfortunately, the bool constructor cannot be inlined (because its
83 // implementation is not present in the headers) and the copy constructor is
84 // not inlined (because it is constructed into a temporary and the analyzer
85 // does not inline these since it does not yet reliably call temporary
86 // destructors).
87 //
88 // This checker compensates for the missing inlining by propgagating the
89 // _success value across the bool and copy constructors so the assertion behaves
90 // as expected.
91 
92 namespace {
93 class GTestChecker : public Checker<check::PostCall> {
94 
95   mutable IdentifierInfo *AssertionResultII;
96   mutable IdentifierInfo *SuccessII;
97 
98 public:
99   GTestChecker();
100 
101   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
102 
103 private:
104   void modelAssertionResultBoolConstructor(const CXXConstructorCall *Call,
105                                            CheckerContext &C) const;
106 
107   void modelAssertionResultCopyConstructor(const CXXConstructorCall *Call,
108                                            CheckerContext &C) const;
109 
110   void initIdentifierInfo(ASTContext &Ctx) const;
111 
112   SVal
113   getAssertionResultSuccessFieldValue(const CXXRecordDecl *AssertionResultDecl,
114                                       SVal Instance,
115                                       ProgramStateRef State) const;
116 
117   static ProgramStateRef assumeValuesEqual(SVal Val1, SVal Val2,
118                                            ProgramStateRef State,
119                                            CheckerContext &C);
120 };
121 } // End anonymous namespace.
122 
123 GTestChecker::GTestChecker() : AssertionResultII(nullptr), SuccessII(nullptr) {}
124 
125 /// Model a call to an un-inlined AssertionResult(boolean expression).
126 /// To do so, constrain the value of the newly-constructed instance's 'success_'
127 /// field to be equal to the passed-in boolean value.
128 void GTestChecker::modelAssertionResultBoolConstructor(
129     const CXXConstructorCall *Call, CheckerContext &C) const {
130   assert(Call->getNumArgs() > 0);
131 
132   // Depending on the version of gtest the constructor can be either of:
133   //
134   // v1.7 and earlier:
135   //      AssertionResult(bool success)
136   //
137   // v1.8 and greater:
138   //      template <typename T>
139   //      AssertionResult(const T& success,
140   //                      typename internal::EnableIf<
141   //                          !internal::ImplicitlyConvertible<T,
142   //                              AssertionResult>::value>::type*)
143 
144   SVal BooleanArgVal = Call->getArgSVal(0);
145   if (Call->getDecl()->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
146     // We have v1.8+, so load the value from the reference.
147     if (!BooleanArgVal.getAs<Loc>())
148       return;
149     BooleanArgVal = C.getState()->getSVal(BooleanArgVal.castAs<Loc>());
150   }
151 
152   ProgramStateRef State = C.getState();
153 
154   SVal ThisVal = Call->getCXXThisVal();
155 
156   SVal ThisSuccess = getAssertionResultSuccessFieldValue(
157       Call->getDecl()->getParent(), ThisVal, State);
158 
159   State = assumeValuesEqual(ThisSuccess, BooleanArgVal, State, C);
160   C.addTransition(State);
161 }
162 
163 /// Model a call to an un-inlined AssertionResult copy constructor:
164 ///
165 ///   AssertionResult(const &AssertionResult other)
166 ///
167 /// To do so, constrain the value of the newly-constructed instance's
168 /// 'success_' field to be equal to the value of the pass-in instance's
169 /// 'success_' field.
170 void GTestChecker::modelAssertionResultCopyConstructor(
171     const CXXConstructorCall *Call, CheckerContext &C) const {
172   assert(Call->getNumArgs() > 0);
173 
174   // The first parameter of the the copy constructor must be the other
175   // instance to initialize this instances fields from.
176   SVal OtherVal = Call->getArgSVal(0);
177   SVal ThisVal = Call->getCXXThisVal();
178 
179   const CXXRecordDecl *AssertResultClassDecl = Call->getDecl()->getParent();
180   ProgramStateRef State = C.getState();
181 
182   SVal ThisSuccess = getAssertionResultSuccessFieldValue(AssertResultClassDecl,
183                                                          ThisVal, State);
184   SVal OtherSuccess = getAssertionResultSuccessFieldValue(AssertResultClassDecl,
185                                                           OtherVal, State);
186 
187   State = assumeValuesEqual(ThisSuccess, OtherSuccess, State, C);
188   C.addTransition(State);
189 }
190 
191 /// Model calls to AssertionResult constructors that are not inlined.
192 void GTestChecker::checkPostCall(const CallEvent &Call,
193                                  CheckerContext &C) const {
194   /// If the constructor was inlined, there is no need model it.
195   if (C.wasInlined)
196     return;
197 
198   initIdentifierInfo(C.getASTContext());
199 
200   auto *CtorCall = dyn_cast<CXXConstructorCall>(&Call);
201   if (!CtorCall)
202     return;
203 
204   const CXXConstructorDecl *CtorDecl = CtorCall->getDecl();
205   const CXXRecordDecl *CtorParent = CtorDecl->getParent();
206   if (CtorParent->getIdentifier() != AssertionResultII)
207     return;
208 
209   if (CtorDecl->getNumParams() == 0)
210     return;
211 
212 
213   // Call the appropriate modeling method based on the type of the first
214   // constructor parameter.
215   const ParmVarDecl *ParamDecl = CtorDecl->getParamDecl(0);
216   QualType ParamType = ParamDecl->getType();
217   if (CtorDecl->getNumParams() <= 2 &&
218       ParamType.getNonReferenceType()->getCanonicalTypeUnqualified() ==
219       C.getASTContext().BoolTy) {
220     // The first parameter is either a boolean or reference to a boolean
221     modelAssertionResultBoolConstructor(CtorCall, C);
222 
223   } else if (CtorDecl->isCopyConstructor()) {
224     modelAssertionResultCopyConstructor(CtorCall, C);
225   }
226 }
227 
228 void GTestChecker::initIdentifierInfo(ASTContext &Ctx) const {
229   if (AssertionResultII)
230     return;
231 
232   AssertionResultII = &Ctx.Idents.get("AssertionResult");
233   SuccessII = &Ctx.Idents.get("success_");
234 }
235 
236 /// Returns the value stored in the 'success_' field of the passed-in
237 /// AssertionResult instance.
238 SVal GTestChecker::getAssertionResultSuccessFieldValue(
239     const CXXRecordDecl *AssertionResultDecl, SVal Instance,
240     ProgramStateRef State) const {
241 
242   DeclContext::lookup_result Result = AssertionResultDecl->lookup(SuccessII);
243   if (Result.empty())
244     return UnknownVal();
245 
246   auto *SuccessField = dyn_cast<FieldDecl>(Result.front());
247   if (!SuccessField)
248     return UnknownVal();
249 
250   Optional<Loc> FieldLoc =
251       State->getLValue(SuccessField, Instance).getAs<Loc>();
252   if (!FieldLoc.hasValue())
253     return UnknownVal();
254 
255   return State->getSVal(*FieldLoc);
256 }
257 
258 /// Constrain the passed-in state to assume two values are equal.
259 ProgramStateRef GTestChecker::assumeValuesEqual(SVal Val1, SVal Val2,
260                                                 ProgramStateRef State,
261                                                 CheckerContext &C) {
262   if (!Val1.getAs<DefinedOrUnknownSVal>() ||
263       !Val2.getAs<DefinedOrUnknownSVal>())
264     return State;
265 
266   auto ValuesEqual =
267       C.getSValBuilder().evalEQ(State, Val1.castAs<DefinedOrUnknownSVal>(),
268                                 Val2.castAs<DefinedOrUnknownSVal>());
269 
270   if (!ValuesEqual.getAs<DefinedSVal>())
271     return State;
272 
273   State = C.getConstraintManager().assume(
274       State, ValuesEqual.castAs<DefinedSVal>(), true);
275 
276   return State;
277 }
278 
279 void ento::registerGTestChecker(CheckerManager &Mgr) {
280   const LangOptions &LangOpts = Mgr.getLangOpts();
281   // gtest is a C++ API so there is no sense running the checker
282   // if not compiling for C++.
283   if (!LangOpts.CPlusPlus)
284     return;
285 
286   Mgr.registerChecker<GTestChecker>();
287 }
288