1 //== Store.cpp - Interface for maps from Locations to Values ----*- 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 file defined the types Store and StoreManager.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclObjC.h"
18 
19 using namespace clang;
20 using namespace ento;
21 
22 StoreManager::StoreManager(ProgramStateManager &stateMgr)
23   : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
24     MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
25 
26 StoreRef StoreManager::enterStackFrame(ProgramStateRef state,
27                                        const LocationContext *callerCtx,
28                                        const StackFrameContext *calleeCtx) {
29   return StoreRef(state->getStore(), *this);
30 }
31 
32 const MemRegion *StoreManager::MakeElementRegion(const MemRegion *Base,
33                                               QualType EleTy, uint64_t index) {
34   NonLoc idx = svalBuilder.makeArrayIndex(index);
35   return MRMgr.getElementRegion(EleTy, idx, Base, svalBuilder.getContext());
36 }
37 
38 // FIXME: Merge with the implementation of the same method in MemRegion.cpp
39 static bool IsCompleteType(ASTContext &Ctx, QualType Ty) {
40   if (const RecordType *RT = Ty->getAs<RecordType>()) {
41     const RecordDecl *D = RT->getDecl();
42     if (!D->getDefinition())
43       return false;
44   }
45 
46   return true;
47 }
48 
49 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
50   return StoreRef(store, *this);
51 }
52 
53 const ElementRegion *StoreManager::GetElementZeroRegion(const MemRegion *R,
54                                                         QualType T) {
55   NonLoc idx = svalBuilder.makeZeroArrayIndex();
56   assert(!T.isNull());
57   return MRMgr.getElementRegion(T, idx, R, Ctx);
58 }
59 
60 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
61 
62   ASTContext &Ctx = StateMgr.getContext();
63 
64   // Handle casts to Objective-C objects.
65   if (CastToTy->isObjCObjectPointerType())
66     return R->StripCasts();
67 
68   if (CastToTy->isBlockPointerType()) {
69     // FIXME: We may need different solutions, depending on the symbol
70     // involved.  Blocks can be casted to/from 'id', as they can be treated
71     // as Objective-C objects.  This could possibly be handled by enhancing
72     // our reasoning of downcasts of symbolic objects.
73     if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
74       return R;
75 
76     // We don't know what to make of it.  Return a NULL region, which
77     // will be interpretted as UnknownVal.
78     return NULL;
79   }
80 
81   // Now assume we are casting from pointer to pointer. Other cases should
82   // already be handled.
83   QualType PointeeTy = CastToTy->getPointeeType();
84   QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
85 
86   // Handle casts to void*.  We just pass the region through.
87   if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
88     return R;
89 
90   // Handle casts from compatible types.
91   if (R->isBoundable())
92     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
93       QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
94       if (CanonPointeeTy == ObjTy)
95         return R;
96     }
97 
98   // Process region cast according to the kind of the region being cast.
99   switch (R->getKind()) {
100     case MemRegion::CXXThisRegionKind:
101     case MemRegion::GenericMemSpaceRegionKind:
102     case MemRegion::StackLocalsSpaceRegionKind:
103     case MemRegion::StackArgumentsSpaceRegionKind:
104     case MemRegion::HeapSpaceRegionKind:
105     case MemRegion::UnknownSpaceRegionKind:
106     case MemRegion::StaticGlobalSpaceRegionKind:
107     case MemRegion::GlobalInternalSpaceRegionKind:
108     case MemRegion::GlobalSystemSpaceRegionKind:
109     case MemRegion::GlobalImmutableSpaceRegionKind: {
110       llvm_unreachable("Invalid region cast");
111     }
112 
113     case MemRegion::FunctionTextRegionKind:
114     case MemRegion::BlockTextRegionKind:
115     case MemRegion::BlockDataRegionKind:
116     case MemRegion::StringRegionKind:
117       // FIXME: Need to handle arbitrary downcasts.
118     case MemRegion::SymbolicRegionKind:
119     case MemRegion::AllocaRegionKind:
120     case MemRegion::CompoundLiteralRegionKind:
121     case MemRegion::FieldRegionKind:
122     case MemRegion::ObjCIvarRegionKind:
123     case MemRegion::VarRegionKind:
124     case MemRegion::CXXTempObjectRegionKind:
125     case MemRegion::CXXBaseObjectRegionKind:
126       return MakeElementRegion(R, PointeeTy);
127 
128     case MemRegion::ElementRegionKind: {
129       // If we are casting from an ElementRegion to another type, the
130       // algorithm is as follows:
131       //
132       // (1) Compute the "raw offset" of the ElementRegion from the
133       //     base region.  This is done by calling 'getAsRawOffset()'.
134       //
135       // (2a) If we get a 'RegionRawOffset' after calling
136       //      'getAsRawOffset()', determine if the absolute offset
137       //      can be exactly divided into chunks of the size of the
138       //      casted-pointee type.  If so, create a new ElementRegion with
139       //      the pointee-cast type as the new ElementType and the index
140       //      being the offset divded by the chunk size.  If not, create
141       //      a new ElementRegion at offset 0 off the raw offset region.
142       //
143       // (2b) If we don't a get a 'RegionRawOffset' after calling
144       //      'getAsRawOffset()', it means that we are at offset 0.
145       //
146       // FIXME: Handle symbolic raw offsets.
147 
148       const ElementRegion *elementR = cast<ElementRegion>(R);
149       const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
150       const MemRegion *baseR = rawOff.getRegion();
151 
152       // If we cannot compute a raw offset, throw up our hands and return
153       // a NULL MemRegion*.
154       if (!baseR)
155         return NULL;
156 
157       CharUnits off = rawOff.getOffset();
158 
159       if (off.isZero()) {
160         // Edge case: we are at 0 bytes off the beginning of baseR.  We
161         // check to see if type we are casting to is the same as the base
162         // region.  If so, just return the base region.
163         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
164           QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
165           QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
166           if (CanonPointeeTy == ObjTy)
167             return baseR;
168         }
169 
170         // Otherwise, create a new ElementRegion at offset 0.
171         return MakeElementRegion(baseR, PointeeTy);
172       }
173 
174       // We have a non-zero offset from the base region.  We want to determine
175       // if the offset can be evenly divided by sizeof(PointeeTy).  If so,
176       // we create an ElementRegion whose index is that value.  Otherwise, we
177       // create two ElementRegions, one that reflects a raw offset and the other
178       // that reflects the cast.
179 
180       // Compute the index for the new ElementRegion.
181       int64_t newIndex = 0;
182       const MemRegion *newSuperR = 0;
183 
184       // We can only compute sizeof(PointeeTy) if it is a complete type.
185       if (IsCompleteType(Ctx, PointeeTy)) {
186         // Compute the size in **bytes**.
187         CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
188         if (!pointeeTySize.isZero()) {
189           // Is the offset a multiple of the size?  If so, we can layer the
190           // ElementRegion (with elementType == PointeeTy) directly on top of
191           // the base region.
192           if (off % pointeeTySize == 0) {
193             newIndex = off / pointeeTySize;
194             newSuperR = baseR;
195           }
196         }
197       }
198 
199       if (!newSuperR) {
200         // Create an intermediate ElementRegion to represent the raw byte.
201         // This will be the super region of the final ElementRegion.
202         newSuperR = MakeElementRegion(baseR, Ctx.CharTy, off.getQuantity());
203       }
204 
205       return MakeElementRegion(newSuperR, PointeeTy, newIndex);
206     }
207   }
208 
209   llvm_unreachable("unreachable");
210 }
211 
212 
213 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
214 ///  implicit casts that arise from loads from regions that are reinterpreted
215 ///  as another region.
216 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
217                                     QualType castTy, bool performTestOnly) {
218 
219   if (castTy.isNull() || V.isUnknownOrUndef())
220     return V;
221 
222   ASTContext &Ctx = svalBuilder.getContext();
223 
224   if (performTestOnly) {
225     // Automatically translate references to pointers.
226     QualType T = R->getValueType();
227     if (const ReferenceType *RT = T->getAs<ReferenceType>())
228       T = Ctx.getPointerType(RT->getPointeeType());
229 
230     assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
231     return V;
232   }
233 
234   return svalBuilder.dispatchCast(V, castTy);
235 }
236 
237 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
238   if (Base.isUnknownOrUndef())
239     return Base;
240 
241   Loc BaseL = cast<Loc>(Base);
242   const MemRegion* BaseR = 0;
243 
244   switch (BaseL.getSubKind()) {
245   case loc::MemRegionKind:
246     BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
247     break;
248 
249   case loc::GotoLabelKind:
250     // These are anormal cases. Flag an undefined value.
251     return UndefinedVal();
252 
253   case loc::ConcreteIntKind:
254     // While these seem funny, this can happen through casts.
255     // FIXME: What we should return is the field offset.  For example,
256     //  add the field offset to the integer value.  That way funny things
257     //  like this work properly:  &(((struct foo *) 0xa)->f)
258     return Base;
259 
260   default:
261     llvm_unreachable("Unhandled Base.");
262   }
263 
264   // NOTE: We must have this check first because ObjCIvarDecl is a subclass
265   // of FieldDecl.
266   if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
267     return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
268 
269   return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
270 }
271 
272 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
273   return getLValueFieldOrIvar(decl, base);
274 }
275 
276 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,
277                                     SVal Base) {
278 
279   // If the base is an unknown or undefined value, just return it back.
280   // FIXME: For absolute pointer addresses, we just return that value back as
281   //  well, although in reality we should return the offset added to that
282   //  value.
283   if (Base.isUnknownOrUndef() || isa<loc::ConcreteInt>(Base))
284     return Base;
285 
286   const MemRegion* BaseRegion = cast<loc::MemRegionVal>(Base).getRegion();
287 
288   // Pointer of any type can be cast and used as array base.
289   const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
290 
291   // Convert the offset to the appropriate size and signedness.
292   Offset = cast<NonLoc>(svalBuilder.convertToArrayIndex(Offset));
293 
294   if (!ElemR) {
295     //
296     // If the base region is not an ElementRegion, create one.
297     // This can happen in the following example:
298     //
299     //   char *p = __builtin_alloc(10);
300     //   p[1] = 8;
301     //
302     //  Observe that 'p' binds to an AllocaRegion.
303     //
304     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
305                                                     BaseRegion, Ctx));
306   }
307 
308   SVal BaseIdx = ElemR->getIndex();
309 
310   if (!isa<nonloc::ConcreteInt>(BaseIdx))
311     return UnknownVal();
312 
313   const llvm::APSInt& BaseIdxI = cast<nonloc::ConcreteInt>(BaseIdx).getValue();
314 
315   // Only allow non-integer offsets if the base region has no offset itself.
316   // FIXME: This is a somewhat arbitrary restriction. We should be using
317   // SValBuilder here to add the two offsets without checking their types.
318   if (!isa<nonloc::ConcreteInt>(Offset)) {
319     if (isa<ElementRegion>(BaseRegion->StripCasts()))
320       return UnknownVal();
321 
322     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
323                                                     ElemR->getSuperRegion(),
324                                                     Ctx));
325   }
326 
327   const llvm::APSInt& OffI = cast<nonloc::ConcreteInt>(Offset).getValue();
328   assert(BaseIdxI.isSigned());
329 
330   // Compute the new index.
331   nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
332                                                                     OffI));
333 
334   // Construct the new ElementRegion.
335   const MemRegion *ArrayR = ElemR->getSuperRegion();
336   return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
337                                                   Ctx));
338 }
339 
340 StoreManager::BindingsHandler::~BindingsHandler() {}
341 
342 void SubRegionMap::anchor() { }
343 void SubRegionMap::Visitor::anchor() { }
344