UndefinedAssignmentChecker.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //===--- UndefinedAssignmentChecker.h ---------------------------*- C++ -*--==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This defines UndefinedAssignmentChecker, a builtin check in ExprEngine that
  11. // checks for assigning undefined values.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "clang/StaticAnalyzer/Core/Checker.h"
  16. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. using namespace clang;
  20. using namespace ento;
  21. namespace {
  22. class UndefinedAssignmentChecker
  23. : public Checker<check::Bind> {
  24. mutable OwningPtr<BugType> BT;
  25. public:
  26. void checkBind(SVal location, SVal val, const Stmt *S,
  27. CheckerContext &C) const;
  28. };
  29. }
  30. void UndefinedAssignmentChecker::checkBind(SVal location, SVal val,
  31. const Stmt *StoreE,
  32. CheckerContext &C) const {
  33. if (!val.isUndef())
  34. return;
  35. ExplodedNode *N = C.generateSink();
  36. if (!N)
  37. return;
  38. const char *str = "Assigned value is garbage or undefined";
  39. if (!BT)
  40. BT.reset(new BuiltinBug(str));
  41. // Generate a report for this bug.
  42. const Expr *ex = 0;
  43. while (StoreE) {
  44. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(StoreE)) {
  45. if (B->isCompoundAssignmentOp()) {
  46. ProgramStateRef state = C.getState();
  47. if (state->getSVal(B->getLHS(), C.getLocationContext()).isUndef()) {
  48. str = "The left expression of the compound assignment is an "
  49. "uninitialized value. The computed value will also be garbage";
  50. ex = B->getLHS();
  51. break;
  52. }
  53. }
  54. ex = B->getRHS();
  55. break;
  56. }
  57. if (const DeclStmt *DS = dyn_cast<DeclStmt>(StoreE)) {
  58. const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  59. ex = VD->getInit();
  60. }
  61. break;
  62. }
  63. BugReport *R = new BugReport(*BT, str, N);
  64. if (ex) {
  65. R->addRange(ex->getSourceRange());
  66. bugreporter::trackNullOrUndefValue(N, ex, *R);
  67. }
  68. R->disablePathPruning();
  69. C.EmitReport(R);
  70. }
  71. void ento::registerUndefinedAssignmentChecker(CheckerManager &mgr) {
  72. mgr.registerChecker<UndefinedAssignmentChecker>();
  73. }