SmartPtrModeling.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include "Move.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/Core/Checker.h"
  18. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  20. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  21. using namespace clang;
  22. using namespace ento;
  23. namespace {
  24. class SmartPtrModeling : public Checker<eval::Call> {
  25. bool isNullAfterMoveMethod(const CallEvent &Call) const;
  26. public:
  27. bool evalCall(const CallEvent &Call, CheckerContext &C) const;
  28. };
  29. } // end of anonymous namespace
  30. bool SmartPtrModeling::isNullAfterMoveMethod(const CallEvent &Call) const {
  31. // TODO: Update CallDescription to support anonymous calls?
  32. // TODO: Handle other methods, such as .get() or .release().
  33. // But once we do, we'd need a visitor to explain null dereferences
  34. // that are found via such modeling.
  35. const auto *CD = dyn_cast_or_null<CXXConversionDecl>(Call.getDecl());
  36. return CD && CD->getConversionType()->isBooleanType();
  37. }
  38. bool SmartPtrModeling::evalCall(const CallEvent &Call,
  39. CheckerContext &C) const {
  40. if (!isNullAfterMoveMethod(Call))
  41. return false;
  42. ProgramStateRef State = C.getState();
  43. const MemRegion *ThisR =
  44. cast<CXXInstanceCall>(&Call)->getCXXThisVal().getAsRegion();
  45. if (!move::isMovedFrom(State, ThisR)) {
  46. // TODO: Model this case as well. At least, avoid invalidation of globals.
  47. return false;
  48. }
  49. // TODO: Add a note to bug reports describing this decision.
  50. C.addTransition(
  51. State->BindExpr(Call.getOriginExpr(), C.getLocationContext(),
  52. C.getSValBuilder().makeZeroVal(Call.getResultType())));
  53. return true;
  54. }
  55. void ento::registerSmartPtrModeling(CheckerManager &Mgr) {
  56. Mgr.registerChecker<SmartPtrModeling>();
  57. }
  58. bool ento::shouldRegisterSmartPtrModeling(const LangOptions &LO) {
  59. return LO.CPlusPlus;
  60. }