UndefinedAssignmentChecker.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 llvm::OwningPtr<BugType> BT;
  25. public:
  26. void checkBind(SVal location, SVal val, CheckerContext &C) const;
  27. };
  28. }
  29. void UndefinedAssignmentChecker::checkBind(SVal location, SVal val,
  30. CheckerContext &C) const {
  31. if (!val.isUndef())
  32. return;
  33. ExplodedNode *N = C.generateSink();
  34. if (!N)
  35. return;
  36. const char *str = "Assigned value is garbage or undefined";
  37. if (!BT)
  38. BT.reset(new BuiltinBug(str));
  39. // Generate a report for this bug.
  40. const Expr *ex = 0;
  41. const Stmt *StoreE = C.getStmt();
  42. while (StoreE) {
  43. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(StoreE)) {
  44. if (B->isCompoundAssignmentOp()) {
  45. const ProgramState *state = C.getState();
  46. if (state->getSVal(B->getLHS()).isUndef()) {
  47. str = "The left expression of the compound assignment is an "
  48. "uninitialized value. The computed value will also be garbage";
  49. ex = B->getLHS();
  50. break;
  51. }
  52. }
  53. ex = B->getRHS();
  54. break;
  55. }
  56. if (const DeclStmt *DS = dyn_cast<DeclStmt>(StoreE)) {
  57. const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  58. ex = VD->getInit();
  59. }
  60. break;
  61. }
  62. BugReport *R = new BugReport(*BT, str, N);
  63. if (ex) {
  64. R->addRange(ex->getSourceRange());
  65. R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, ex);
  66. }
  67. C.EmitReport(R);
  68. }
  69. void ento::registerUndefinedAssignmentChecker(CheckerManager &mgr) {
  70. mgr.registerChecker<UndefinedAssignmentChecker>();
  71. }