1 //==- GTestChecker.cpp - Model gtest API --*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This checker models the behavior of un-inlined APIs from the gtest
11 // unit-testing library to avoid false positives when using assertions from
14 //===----------------------------------------------------------------------===//
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"
25 using namespace clang;
28 // Modeling of un-inlined AssertionResult constructors
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.
36 // ASSERT_TRUE(a == b)
43 // if (const ::testing::AssertionResult gtest_ar_ =
44 // ::testing::AssertionResult((a == b)))
47 // return ::testing::internal::AssertHelper(
48 // ::testing::TestPartResult::kFatalFailure,
49 // "<path to project>",
51 // ::testing::internal::GetBoolAssertionFailureMessage(
52 // gtest_ar_, "a == b", "false", "true")
53 // .c_str()) = ::testing::Message();
55 // where AssertionResult is defined similarly to
57 // class AssertionResult {
59 // AssertionResult(const AssertionResult& other);
60 // explicit AssertionResult(bool success) : success_(success) {}
61 // operator bool() const { return success_; }
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.
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:
79 // ASSERT(ptr != NULL)
80 // *ptr = 7; // False positive null pointer dereference here
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
88 // This checker compensates for the missing inlining by propagating the
89 // _success value across the bool and copy constructors so the assertion behaves
93 class GTestChecker : public Checker<check::PostCall> {
95 mutable IdentifierInfo *AssertionResultII;
96 mutable IdentifierInfo *SuccessII;
101 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
104 void modelAssertionResultBoolConstructor(const CXXConstructorCall *Call,
105 bool IsRef, CheckerContext &C) const;
107 void modelAssertionResultCopyConstructor(const CXXConstructorCall *Call,
108 CheckerContext &C) const;
110 void initIdentifierInfo(ASTContext &Ctx) const;
113 getAssertionResultSuccessFieldValue(const CXXRecordDecl *AssertionResultDecl,
115 ProgramStateRef State) const;
117 static ProgramStateRef assumeValuesEqual(SVal Val1, SVal Val2,
118 ProgramStateRef State,
121 } // End anonymous namespace.
123 GTestChecker::GTestChecker() : AssertionResultII(nullptr), SuccessII(nullptr) {}
125 /// Model a call to an un-inlined AssertionResult(bool) or
126 /// AssertionResult(bool &, ...).
127 /// To do so, constrain the value of the newly-constructed instance's 'success_'
128 /// field to be equal to the passed-in boolean value.
130 /// \param IsRef Whether the boolean parameter is a reference or not.
131 void GTestChecker::modelAssertionResultBoolConstructor(
132 const CXXConstructorCall *Call, bool IsRef, CheckerContext &C) const {
133 assert(Call->getNumArgs() >= 1 && Call->getNumArgs() <= 2);
135 ProgramStateRef State = C.getState();
136 SVal BooleanArgVal = Call->getArgSVal(0);
138 // The argument is a reference, so load from it to get the boolean value.
139 if (!BooleanArgVal.getAs<Loc>())
141 BooleanArgVal = C.getState()->getSVal(BooleanArgVal.castAs<Loc>());
144 SVal ThisVal = Call->getCXXThisVal();
146 SVal ThisSuccess = getAssertionResultSuccessFieldValue(
147 Call->getDecl()->getParent(), ThisVal, State);
149 State = assumeValuesEqual(ThisSuccess, BooleanArgVal, State, C);
150 C.addTransition(State);
153 /// Model a call to an un-inlined AssertionResult copy constructor:
155 /// AssertionResult(const &AssertionResult other)
157 /// To do so, constrain the value of the newly-constructed instance's
158 /// 'success_' field to be equal to the value of the pass-in instance's
159 /// 'success_' field.
160 void GTestChecker::modelAssertionResultCopyConstructor(
161 const CXXConstructorCall *Call, CheckerContext &C) const {
162 assert(Call->getNumArgs() == 1);
164 // The first parameter of the the copy constructor must be the other
165 // instance to initialize this instances fields from.
166 SVal OtherVal = Call->getArgSVal(0);
167 SVal ThisVal = Call->getCXXThisVal();
169 const CXXRecordDecl *AssertResultClassDecl = Call->getDecl()->getParent();
170 ProgramStateRef State = C.getState();
172 SVal ThisSuccess = getAssertionResultSuccessFieldValue(AssertResultClassDecl,
174 SVal OtherSuccess = getAssertionResultSuccessFieldValue(AssertResultClassDecl,
177 State = assumeValuesEqual(ThisSuccess, OtherSuccess, State, C);
178 C.addTransition(State);
181 /// Model calls to AssertionResult constructors that are not inlined.
182 void GTestChecker::checkPostCall(const CallEvent &Call,
183 CheckerContext &C) const {
184 /// If the constructor was inlined, there is no need model it.
188 initIdentifierInfo(C.getASTContext());
190 auto *CtorCall = dyn_cast<CXXConstructorCall>(&Call);
194 const CXXConstructorDecl *CtorDecl = CtorCall->getDecl();
195 const CXXRecordDecl *CtorParent = CtorDecl->getParent();
196 if (CtorParent->getIdentifier() != AssertionResultII)
199 unsigned ParamCount = CtorDecl->getNumParams();
201 // Call the appropriate modeling method based the parameters and their
204 // We have AssertionResult(const &AssertionResult)
205 if (CtorDecl->isCopyConstructor() && ParamCount == 1) {
206 modelAssertionResultCopyConstructor(CtorCall, C);
210 // There are two possible boolean constructors, depending on which
211 // version of gtest is being used:
214 // AssertionResult(bool success)
217 // template <typename T>
218 // AssertionResult(const T& success,
219 // typename internal::EnableIf<
220 // !internal::ImplicitlyConvertible<T,
221 // AssertionResult>::value>::type*)
223 CanQualType BoolTy = C.getASTContext().BoolTy;
224 if (ParamCount == 1 && CtorDecl->getParamDecl(0)->getType() == BoolTy) {
225 // We have AssertionResult(bool)
226 modelAssertionResultBoolConstructor(CtorCall, /*IsRef=*/false, C);
229 if (ParamCount == 2){
230 auto *RefTy = CtorDecl->getParamDecl(0)->getType()->getAs<ReferenceType>();
232 RefTy->getPointeeType()->getCanonicalTypeUnqualified() == BoolTy) {
233 // We have AssertionResult(bool &, ...)
234 modelAssertionResultBoolConstructor(CtorCall, /*IsRef=*/true, C);
240 void GTestChecker::initIdentifierInfo(ASTContext &Ctx) const {
241 if (AssertionResultII)
244 AssertionResultII = &Ctx.Idents.get("AssertionResult");
245 SuccessII = &Ctx.Idents.get("success_");
248 /// Returns the value stored in the 'success_' field of the passed-in
249 /// AssertionResult instance.
250 SVal GTestChecker::getAssertionResultSuccessFieldValue(
251 const CXXRecordDecl *AssertionResultDecl, SVal Instance,
252 ProgramStateRef State) const {
254 DeclContext::lookup_result Result = AssertionResultDecl->lookup(SuccessII);
258 auto *SuccessField = dyn_cast<FieldDecl>(Result.front());
262 Optional<Loc> FieldLoc =
263 State->getLValue(SuccessField, Instance).getAs<Loc>();
264 if (!FieldLoc.hasValue())
267 return State->getSVal(*FieldLoc);
270 /// Constrain the passed-in state to assume two values are equal.
271 ProgramStateRef GTestChecker::assumeValuesEqual(SVal Val1, SVal Val2,
272 ProgramStateRef State,
274 if (!Val1.getAs<DefinedOrUnknownSVal>() ||
275 !Val2.getAs<DefinedOrUnknownSVal>())
279 C.getSValBuilder().evalEQ(State, Val1.castAs<DefinedOrUnknownSVal>(),
280 Val2.castAs<DefinedOrUnknownSVal>());
282 if (!ValuesEqual.getAs<DefinedSVal>())
285 State = C.getConstraintManager().assume(
286 State, ValuesEqual.castAs<DefinedSVal>(), true);
291 void ento::registerGTestChecker(CheckerManager &Mgr) {
292 const LangOptions &LangOpts = Mgr.getLangOpts();
293 // gtest is a C++ API so there is no sense running the checker
294 // if not compiling for C++.
295 if (!LangOpts.CPlusPlus)
298 Mgr.registerChecker<GTestChecker>();