1 // SmartPtrModeling.cpp - Model behavior of C++ smart pointers - C++ ------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines a checker that models various aspects of
10 // C++ smart pointer behavior.
12 //===----------------------------------------------------------------------===//
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"
24 using namespace clang;
28 class SmartPtrModeling : public Checker<eval::Call> {
29 bool isNullAfterMoveMethod(const CallEvent &Call) const;
32 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
34 } // end of anonymous namespace
36 bool SmartPtrModeling::isNullAfterMoveMethod(const CallEvent &Call) const {
37 // TODO: Update CallDescription to support anonymous calls?
38 // TODO: Handle other methods, such as .get() or .release().
39 // But once we do, we'd need a visitor to explain null dereferences
40 // that are found via such modeling.
41 const auto *CD = dyn_cast_or_null<CXXConversionDecl>(Call.getDecl());
42 return CD && CD->getConversionType()->isBooleanType();
45 bool SmartPtrModeling::evalCall(const CallEvent &Call,
46 CheckerContext &C) const {
47 if (!isNullAfterMoveMethod(Call))
50 ProgramStateRef State = C.getState();
51 const MemRegion *ThisR =
52 cast<CXXInstanceCall>(&Call)->getCXXThisVal().getAsRegion();
54 if (!move::isMovedFrom(State, ThisR)) {
55 // TODO: Model this case as well. At least, avoid invalidation of globals.
59 // TODO: Add a note to bug reports describing this decision.
61 State->BindExpr(Call.getOriginExpr(), C.getLocationContext(),
62 C.getSValBuilder().makeZeroVal(Call.getResultType())));
66 void ento::registerSmartPtrModeling(CheckerManager &Mgr) {
67 Mgr.registerChecker<SmartPtrModeling>();
70 bool ento::shouldRegisterSmartPtrModeling(const LangOptions &LO) {