CastToStructChecker.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/Checker.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  19. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  20. using namespace clang;
  21. using namespace ento;
  22. namespace {
  23. class CastToStructChecker : public Checker< check::PreStmt<CastExpr> > {
  24. mutable llvm::OwningPtr<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.generateNode()) {
  49. if (!BT)
  50. BT.reset(new BuiltinBug("Cast from non-struct type to struct type",
  51. "Casting a non-structure type to a structure type "
  52. "and accessing a field can lead to memory access "
  53. "errors or data corruption."));
  54. BugReport *R = new BugReport(*BT,BT->getDescription(), N);
  55. R->addRange(CE->getSourceRange());
  56. C.EmitReport(R);
  57. }
  58. }
  59. }
  60. void ento::registerCastToStructChecker(CheckerManager &mgr) {
  61. mgr.registerChecker<CastToStructChecker>();
  62. }