clang  9.0.0svn
CastSizeChecker.cpp
Go to the documentation of this file.
1 //=== CastSizeChecker.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // CastSizeChecker checks when casting a malloc'ed symbolic region to type T,
10 // whether the size of the symbolic region is a multiple of the size of T.
11 //
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/CharUnits.h"
19 
20 using namespace clang;
21 using namespace ento;
22 
23 namespace {
24 class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > {
25  mutable std::unique_ptr<BuiltinBug> BT;
26 
27 public:
28  void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
29 };
30 }
31 
32 /// Check if we are casting to a struct with a flexible array at the end.
33 /// \code
34 /// struct foo {
35 /// size_t len;
36 /// struct bar data[];
37 /// };
38 /// \endcode
39 /// or
40 /// \code
41 /// struct foo {
42 /// size_t len;
43 /// struct bar data[0];
44 /// }
45 /// \endcode
46 /// In these cases it is also valid to allocate size of struct foo + a multiple
47 /// of struct bar.
48 static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize,
49  CharUnits TypeSize, QualType ToPointeeTy) {
50  const RecordType *RT = ToPointeeTy->getAs<RecordType>();
51  if (!RT)
52  return false;
53 
54  const RecordDecl *RD = RT->getDecl();
57  const FieldDecl *Last = nullptr;
58  for (; Iter != End; ++Iter)
59  Last = *Iter;
60  assert(Last && "empty structs should already be handled");
61 
62  const Type *ElemType = Last->getType()->getArrayElementTypeNoTypeQual();
63  CharUnits FlexSize;
64  if (const ConstantArrayType *ArrayTy =
65  Ctx.getAsConstantArrayType(Last->getType())) {
66  FlexSize = Ctx.getTypeSizeInChars(ElemType);
67  if (ArrayTy->getSize() == 1 && TypeSize > FlexSize)
68  TypeSize -= FlexSize;
69  else if (ArrayTy->getSize() != 0)
70  return false;
71  } else if (RD->hasFlexibleArrayMember()) {
72  FlexSize = Ctx.getTypeSizeInChars(ElemType);
73  } else {
74  return false;
75  }
76 
77  if (FlexSize.isZero())
78  return false;
79 
80  CharUnits Left = RegionSize - TypeSize;
81  if (Left.isNegative())
82  return false;
83 
84  return Left % FlexSize == 0;
85 }
86 
87 void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
88  const Expr *E = CE->getSubExpr();
89  ASTContext &Ctx = C.getASTContext();
90  QualType ToTy = Ctx.getCanonicalType(CE->getType());
91  const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
92 
93  if (!ToPTy)
94  return;
95 
96  QualType ToPointeeTy = ToPTy->getPointeeType();
97 
98  // Only perform the check if 'ToPointeeTy' is a complete type.
99  if (ToPointeeTy->isIncompleteType())
100  return;
101 
102  ProgramStateRef state = C.getState();
103  const MemRegion *R = C.getSVal(E).getAsRegion();
104  if (!R)
105  return;
106 
107  const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
108  if (!SR)
109  return;
110 
111  SValBuilder &svalBuilder = C.getSValBuilder();
112  SVal extent = SR->getExtent(svalBuilder);
113  const llvm::APSInt *extentInt = svalBuilder.getKnownValue(state, extent);
114  if (!extentInt)
115  return;
116 
117  CharUnits regionSize = CharUnits::fromQuantity(extentInt->getSExtValue());
118  CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
119 
120  // Ignore void, and a few other un-sizeable types.
121  if (typeSize.isZero())
122  return;
123 
124  if (regionSize % typeSize == 0)
125  return;
126 
127  if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
128  return;
129 
130  if (ExplodedNode *errorNode = C.generateErrorNode()) {
131  if (!BT)
132  BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
133  "Cast a region whose size is not a multiple"
134  " of the destination type size."));
135  auto R = llvm::make_unique<BugReport>(*BT, BT->getDescription(), errorNode);
136  R->addRange(CE->getSourceRange());
137  C.emitReport(std::move(R));
138  }
139 }
140 
141 void ento::registerCastSizeChecker(CheckerManager &mgr) {
142  // PR31226: C++ is more complicated than what this checker currently supports.
143  // There are derived-to-base casts, there are different rules for 0-size
144  // structures, no flexible arrays, etc.
145  // FIXME: Disabled on C++ for now.
146  if (!mgr.getLangOpts().CPlusPlus)
147  mgr.registerChecker<CastSizeChecker>();
148 }
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2539
QualType getPointeeType() const
Definition: Type.h:2552
A (possibly-)qualified type.
Definition: Type.h:637
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
The base class of the type hierarchy.
Definition: Type.h:1406
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:115
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6754
Represents a struct/union/class.
Definition: Decl.h:3592
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Represents a member of a struct/union/class.
Definition: Decl.h:2578
Expr * getSubExpr()
Definition: Expr.h:3056
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6074
field_iterator field_begin() const
Definition: Decl.cpp:4144
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3004
bool isNegative() const
isNegative - Test whether the quantity is less than zero.
Definition: CharUnits.h:124
This represents one expression.
Definition: Expr.h:106
SourceLocation End
static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize, CharUnits TypeSize, QualType ToPointeeTy)
Check if we are casting to a struct with a flexible array at the end.
field_iterator field_end() const
Definition: Decl.h:3786
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:62
QualType getType() const
Definition: Expr.h:128
RecordDecl * getDecl() const
Definition: Type.h:4382
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2415
bool hasFlexibleArrayMember() const
Definition: Decl.h:3646
Dataflow Directional Tag Classes.
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition: Type.cpp:260
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2016
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4372
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2030
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2255
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:275
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2874