1 //=== CastSizeChecker.cpp ---------------------------------------*- 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 // CastSizeChecker checks when casting a malloc'ed symbolic region to type T, 11 // whether the size of the symbolic region is a multiple of the size of T. 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 #include "clang/AST/CharUnits.h" 20 21 using namespace clang; 22 using namespace ento; 23 24 namespace { 25 class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > { 26 mutable llvm::OwningPtr<BuiltinBug> BT; 27 public: 28 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const; 29 }; 30 } 31 checkPreStmt(const CastExpr * CE,CheckerContext & C) const32void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const { 33 const Expr *E = CE->getSubExpr(); 34 ASTContext &Ctx = C.getASTContext(); 35 QualType ToTy = Ctx.getCanonicalType(CE->getType()); 36 const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr()); 37 38 if (!ToPTy) 39 return; 40 41 QualType ToPointeeTy = ToPTy->getPointeeType(); 42 43 // Only perform the check if 'ToPointeeTy' is a complete type. 44 if (ToPointeeTy->isIncompleteType()) 45 return; 46 47 const GRState *state = C.getState(); 48 const MemRegion *R = state->getSVal(E).getAsRegion(); 49 if (R == 0) 50 return; 51 52 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R); 53 if (SR == 0) 54 return; 55 56 SValBuilder &svalBuilder = C.getSValBuilder(); 57 SVal extent = SR->getExtent(svalBuilder); 58 const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent); 59 if (!extentInt) 60 return; 61 62 CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue()); 63 CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy); 64 65 // Ignore void, and a few other un-sizeable types. 66 if (typeSize.isZero()) 67 return; 68 69 if (regionSize % typeSize != 0) { 70 if (ExplodedNode *errorNode = C.generateSink()) { 71 if (!BT) 72 BT.reset(new BuiltinBug("Cast region with wrong size.", 73 "Cast a region whose size is not a multiple of the" 74 " destination type size.")); 75 RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), 76 errorNode); 77 R->addRange(CE->getSourceRange()); 78 C.EmitReport(R); 79 } 80 } 81 } 82 83 registerCastSizeChecker(CheckerManager & mgr)84void ento::registerCastSizeChecker(CheckerManager &mgr) { 85 mgr.registerChecker<CastSizeChecker>(); 86 } 87