1 //=== CastSizeChecker.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
14 #include "ClangSACheckers.h"
15 #include "clang/AST/CharUnits.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"
21 using namespace clang;
25 class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > {
26 mutable OwningPtr<BuiltinBug> BT;
28 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
32 void 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());
41 QualType ToPointeeTy = ToPTy->getPointeeType();
43 // Only perform the check if 'ToPointeeTy' is a complete type.
44 if (ToPointeeTy->isIncompleteType())
47 ProgramStateRef state = C.getState();
48 const MemRegion *R = state->getSVal(E, C.getLocationContext()).getAsRegion();
52 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
56 SValBuilder &svalBuilder = C.getSValBuilder();
57 SVal extent = SR->getExtent(svalBuilder);
58 const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent);
62 CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue());
63 CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
65 // Ignore void, and a few other un-sizeable types.
66 if (typeSize.isZero())
69 if (regionSize % typeSize != 0) {
70 if (ExplodedNode *errorNode = C.generateSink()) {
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 BugReport *R = new BugReport(*BT, BT->getDescription(),
77 R->addRange(CE->getSourceRange());
84 void ento::registerCastSizeChecker(CheckerManager &mgr) {
85 mgr.registerChecker<CastSizeChecker>();