UndefinedAssignmentChecker.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 UndefinedAssginmentChecker, a builtin check in ExprEngine that
  11. // checks for assigning undefined values.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "InternalChecks.h"
  15. #include "clang/StaticAnalyzer/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/PathSensitive/CheckerVisitor.h"
  17. using namespace clang;
  18. using namespace ento;
  19. namespace {
  20. class UndefinedAssignmentChecker
  21. : public CheckerVisitor<UndefinedAssignmentChecker> {
  22. BugType *BT;
  23. public:
  24. UndefinedAssignmentChecker() : BT(0) {}
  25. static void *getTag();
  26. virtual void PreVisitBind(CheckerContext &C, const Stmt *StoreE,
  27. SVal location, SVal val);
  28. };
  29. }
  30. void ento::RegisterUndefinedAssignmentChecker(ExprEngine &Eng){
  31. Eng.registerCheck(new UndefinedAssignmentChecker());
  32. }
  33. void *UndefinedAssignmentChecker::getTag() {
  34. static int x = 0;
  35. return &x;
  36. }
  37. void UndefinedAssignmentChecker::PreVisitBind(CheckerContext &C,
  38. const Stmt *StoreE,
  39. SVal location,
  40. SVal val) {
  41. if (!val.isUndef())
  42. return;
  43. ExplodedNode *N = C.generateSink();
  44. if (!N)
  45. return;
  46. const char *str = "Assigned value is garbage or undefined";
  47. if (!BT)
  48. BT = new BuiltinBug(str);
  49. // Generate a report for this bug.
  50. const Expr *ex = 0;
  51. while (StoreE) {
  52. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(StoreE)) {
  53. if (B->isCompoundAssignmentOp()) {
  54. const GRState *state = C.getState();
  55. if (state->getSVal(B->getLHS()).isUndef()) {
  56. str = "The left expression of the compound assignment is an "
  57. "uninitialized value. The computed value will also be garbage";
  58. ex = B->getLHS();
  59. break;
  60. }
  61. }
  62. ex = B->getRHS();
  63. break;
  64. }
  65. if (const DeclStmt *DS = dyn_cast<DeclStmt>(StoreE)) {
  66. const VarDecl* VD = dyn_cast<VarDecl>(DS->getSingleDecl());
  67. ex = VD->getInit();
  68. }
  69. break;
  70. }
  71. EnhancedBugReport *R = new EnhancedBugReport(*BT, str, N);
  72. if (ex) {
  73. R->addRange(ex->getSourceRange());
  74. R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, ex);
  75. }
  76. C.EmitReport(R);
  77. }