1 // SmartPtrModeling.cpp - Model behavior of C++ smart pointers - C++ ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a checker that models various aspects of 10 // C++ smart pointer behavior. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "Move.h" 15 16 #include "clang/AST/ExprCXX.h" 17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" 18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 19 #include "clang/StaticAnalyzer/Core/Checker.h" 20 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 23 24 using namespace clang; 25 using namespace ento; 26 27 namespace { 28 class SmartPtrModeling : public Checker<eval::Call> { 29 bool isNullAfterMoveMethod(const CXXInstanceCall *Call) const; 30 31 public: 32 bool evalCall(const CallExpr *CE, CheckerContext &C) const; 33 }; 34 } // end of anonymous namespace 35 36 bool SmartPtrModeling::isNullAfterMoveMethod( 37 const CXXInstanceCall *Call) const { 38 // TODO: Update CallDescription to support anonymous calls? 39 // TODO: Handle other methods, such as .get() or .release(). 40 // But once we do, we'd need a visitor to explain null dereferences 41 // that are found via such modeling. 42 const auto *CD = dyn_cast_or_null<CXXConversionDecl>(Call->getDecl()); 43 return CD && CD->getConversionType()->isBooleanType(); 44 } 45 46 bool SmartPtrModeling::evalCall(const CallExpr *CE, CheckerContext &C) const { 47 CallEventRef<> CallRef = C.getStateManager().getCallEventManager().getCall( 48 CE, C.getState(), C.getLocationContext()); 49 const auto *Call = dyn_cast_or_null<CXXInstanceCall>(CallRef); 50 if (!Call || !isNullAfterMoveMethod(Call)) 51 return false; 52 53 ProgramStateRef State = C.getState(); 54 const MemRegion *ThisR = Call->getCXXThisVal().getAsRegion(); 55 56 if (!move::isMovedFrom(State, ThisR)) { 57 // TODO: Model this case as well. At least, avoid invalidation of globals. 58 return false; 59 } 60 61 // TODO: Add a note to bug reports describing this decision. 62 C.addTransition( 63 State->BindExpr(CE, C.getLocationContext(), 64 C.getSValBuilder().makeZeroVal(CE->getType()))); 65 return true; 66 } 67 68 void ento::registerSmartPtrModeling(CheckerManager &Mgr) { 69 Mgr.registerChecker<SmartPtrModeling>(); 70 } 71 72 bool ento::shouldRegisterSmartPtrModeling(const LangOptions &LO) { 73 return LO.CPlusPlus; 74 } 75