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
24using namespace clang;
25using namespace ento;
26
27namespace {
28class SmartPtrModeling : public Checker<eval::Call> {
29  bool isNullAfterMoveMethod(const CallEvent &Call) const;
30
31public:
32  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
33};
34} // end of anonymous namespace
35
36bool 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();
43}
44
45bool SmartPtrModeling::evalCall(const CallEvent &Call,
46                                CheckerContext &C) const {
47  if (!isNullAfterMoveMethod(Call))
48    return false;
49
50  ProgramStateRef State = C.getState();
51  const MemRegion *ThisR =
52      cast<CXXInstanceCall>(&Call)->getCXXThisVal().getAsRegion();
53
54  if (!move::isMovedFrom(State, ThisR)) {
55    // TODO: Model this case as well. At least, avoid invalidation of globals.
56    return false;
57  }
58
59  // TODO: Add a note to bug reports describing this decision.
60  C.addTransition(
61      State->BindExpr(Call.getOriginExpr(), C.getLocationContext(),
62                      C.getSValBuilder().makeZeroVal(Call.getResultType())));
63  return true;
64}
65
66void ento::registerSmartPtrModeling(CheckerManager &Mgr) {
67  Mgr.registerChecker<SmartPtrModeling>();
68}
69
70bool ento::shouldRegisterSmartPtrModeling(const LangOptions &LO) {
71  return LO.CPlusPlus;
72}
73