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 std::unique_ptr<BuiltinBug> BT;
29 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
33 /// Check if we are casting to a struct with a flexible array at the end.
37 /// struct bar data[];
44 /// struct bar data[0];
47 /// In these cases it is also valid to allocate size of struct foo + a multiple
49 static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize,
50 CharUnits TypeSize, QualType ToPointeeTy) {
51 const RecordType *RT = ToPointeeTy->getAs<RecordType>();
55 const RecordDecl *RD = RT->getDecl();
56 RecordDecl::field_iterator Iter(RD->field_begin());
57 RecordDecl::field_iterator End(RD->field_end());
58 const FieldDecl *Last = nullptr;
59 for (; Iter != End; ++Iter)
61 assert(Last && "empty structs should already be handled");
63 const Type *ElemType = Last->getType()->getArrayElementTypeNoTypeQual();
65 if (const ConstantArrayType *ArrayTy =
66 Ctx.getAsConstantArrayType(Last->getType())) {
67 FlexSize = Ctx.getTypeSizeInChars(ElemType);
68 if (ArrayTy->getSize() == 1 && TypeSize > FlexSize)
70 else if (ArrayTy->getSize() != 0)
72 } else if (RD->hasFlexibleArrayMember()) {
73 FlexSize = Ctx.getTypeSizeInChars(ElemType);
78 if (FlexSize.isZero())
81 CharUnits Left = RegionSize - TypeSize;
82 if (Left.isNegative())
85 return Left % FlexSize == 0;
88 void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
89 const Expr *E = CE->getSubExpr();
90 ASTContext &Ctx = C.getASTContext();
91 QualType ToTy = Ctx.getCanonicalType(CE->getType());
92 const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
97 QualType ToPointeeTy = ToPTy->getPointeeType();
99 // Only perform the check if 'ToPointeeTy' is a complete type.
100 if (ToPointeeTy->isIncompleteType())
103 ProgramStateRef state = C.getState();
104 const MemRegion *R = state->getSVal(E, C.getLocationContext()).getAsRegion();
108 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
112 SValBuilder &svalBuilder = C.getSValBuilder();
113 SVal extent = SR->getExtent(svalBuilder);
114 const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent);
118 CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue());
119 CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
121 // Ignore void, and a few other un-sizeable types.
122 if (typeSize.isZero())
125 if (regionSize % typeSize == 0)
128 if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
131 if (ExplodedNode *errorNode = C.generateErrorNode()) {
133 BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
134 "Cast a region whose size is not a multiple"
135 " of the destination type size."));
136 auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), errorNode);
137 R->addRange(CE->getSourceRange());
138 C.emitReport(std::move(R));
142 void ento::registerCastSizeChecker(CheckerManager &mgr) {
143 // PR31226: C++ is more complicated than what this checker currently supports.
144 // There are derived-to-base casts, there are different rules for 0-size
145 // structures, no flexible arrays, etc.
146 // FIXME: Disabled on C++ for now.
147 if (!mgr.getLangOpts().CPlusPlus)
148 mgr.registerChecker<CastSizeChecker>();