CastToStructChecker.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //=== CastToStructChecker.cpp - Fixed address usage checker ----*- 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 files defines CastToStructChecker, a builtin checker that checks for
  11. // cast from non-struct pointer to struct pointer.
  12. // This check corresponds to CWE-588.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "ClangSACheckers.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/CheckerContext.h"
  20. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. class CastToStructChecker : public Checker< check::PreStmt<CastExpr> > {
  24. mutable std::unique_ptr<BuiltinBug> BT;
  25. public:
  26. void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
  27. };
  28. }
  29. void CastToStructChecker::checkPreStmt(const CastExpr *CE,
  30. CheckerContext &C) const {
  31. const Expr *E = CE->getSubExpr();
  32. ASTContext &Ctx = C.getASTContext();
  33. QualType OrigTy = Ctx.getCanonicalType(E->getType());
  34. QualType ToTy = Ctx.getCanonicalType(CE->getType());
  35. const PointerType *OrigPTy = dyn_cast<PointerType>(OrigTy.getTypePtr());
  36. const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
  37. if (!ToPTy || !OrigPTy)
  38. return;
  39. QualType OrigPointeeTy = OrigPTy->getPointeeType();
  40. QualType ToPointeeTy = ToPTy->getPointeeType();
  41. if (!ToPointeeTy->isStructureOrClassType())
  42. return;
  43. // We allow cast from void*.
  44. if (OrigPointeeTy->isVoidType())
  45. return;
  46. // Now the cast-to-type is struct pointer, the original type is not void*.
  47. if (!OrigPointeeTy->isRecordType()) {
  48. if (ExplodedNode *N = C.addTransition()) {
  49. if (!BT)
  50. BT.reset(
  51. new BuiltinBug(this, "Cast from non-struct type to struct type",
  52. "Casting a non-structure type to a structure type "
  53. "and accessing a field can lead to memory access "
  54. "errors or data corruption."));
  55. auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), N);
  56. R->addRange(CE->getSourceRange());
  57. C.emitReport(std::move(R));
  58. }
  59. }
  60. }
  61. void ento::registerCastToStructChecker(CheckerManager &mgr) {
  62. mgr.registerChecker<CastToStructChecker>();
  63. }