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/AST/CXXInheritance.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
20 
21 using namespace clang;
22 using namespace ento;
23 
StoreManager(ProgramStateManager & stateMgr)24 StoreManager::StoreManager(ProgramStateManager &stateMgr)
25   : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
26     MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
27 
enterStackFrame(Store OldStore,const CallEvent & Call,const StackFrameContext * LCtx)28 StoreRef StoreManager::enterStackFrame(Store OldStore,
29                                        const CallEvent &Call,
30                                        const StackFrameContext *LCtx) {
31   StoreRef Store = StoreRef(OldStore, *this);
32 
33   SmallVector<CallEvent::FrameBindingTy, 16> InitialBindings;
34   Call.getInitialStackFrameContents(LCtx, InitialBindings);
35 
36   for (CallEvent::BindingsTy::iterator I = InitialBindings.begin(),
37                                        E = InitialBindings.end();
38        I != E; ++I) {
39     Store = Bind(Store.getStore(), I->first, I->second);
40   }
41 
42   return Store;
43 }
44 
MakeElementRegion(const MemRegion * Base,QualType EleTy,uint64_t index)45 const MemRegion *StoreManager::MakeElementRegion(const MemRegion *Base,
46                                               QualType EleTy, uint64_t index) {
47   NonLoc idx = svalBuilder.makeArrayIndex(index);
48   return MRMgr.getElementRegion(EleTy, idx, Base, svalBuilder.getContext());
49 }
50 
BindDefault(Store store,const MemRegion * R,SVal V)51 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
52   return StoreRef(store, *this);
53 }
54 
GetElementZeroRegion(const MemRegion * R,QualType T)55 const ElementRegion *StoreManager::GetElementZeroRegion(const MemRegion *R,
56                                                         QualType T) {
57   NonLoc idx = svalBuilder.makeZeroArrayIndex();
58   assert(!T.isNull());
59   return MRMgr.getElementRegion(T, idx, R, Ctx);
60 }
61 
castRegion(const MemRegion * R,QualType CastToTy)62 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
63 
64   ASTContext &Ctx = StateMgr.getContext();
65 
66   // Handle casts to Objective-C objects.
67   if (CastToTy->isObjCObjectPointerType())
68     return R->StripCasts();
69 
70   if (CastToTy->isBlockPointerType()) {
71     // FIXME: We may need different solutions, depending on the symbol
72     // involved.  Blocks can be casted to/from 'id', as they can be treated
73     // as Objective-C objects.  This could possibly be handled by enhancing
74     // our reasoning of downcasts of symbolic objects.
75     if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
76       return R;
77 
78     // We don't know what to make of it.  Return a NULL region, which
79     // will be interpretted as UnknownVal.
80     return nullptr;
81   }
82 
83   // Now assume we are casting from pointer to pointer. Other cases should
84   // already be handled.
85   QualType PointeeTy = CastToTy->getPointeeType();
86   QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
87 
88   // Handle casts to void*.  We just pass the region through.
89   if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
90     return R;
91 
92   // Handle casts from compatible types.
93   if (R->isBoundable())
94     if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
95       QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
96       if (CanonPointeeTy == ObjTy)
97         return R;
98     }
99 
100   // Process region cast according to the kind of the region being cast.
101   switch (R->getKind()) {
102     case MemRegion::CXXThisRegionKind:
103     case MemRegion::GenericMemSpaceRegionKind:
104     case MemRegion::StackLocalsSpaceRegionKind:
105     case MemRegion::StackArgumentsSpaceRegionKind:
106     case MemRegion::HeapSpaceRegionKind:
107     case MemRegion::UnknownSpaceRegionKind:
108     case MemRegion::StaticGlobalSpaceRegionKind:
109     case MemRegion::GlobalInternalSpaceRegionKind:
110     case MemRegion::GlobalSystemSpaceRegionKind:
111     case MemRegion::GlobalImmutableSpaceRegionKind: {
112       llvm_unreachable("Invalid region cast");
113     }
114 
115     case MemRegion::FunctionTextRegionKind:
116     case MemRegion::BlockTextRegionKind:
117     case MemRegion::BlockDataRegionKind:
118     case MemRegion::StringRegionKind:
119       // FIXME: Need to handle arbitrary downcasts.
120     case MemRegion::SymbolicRegionKind:
121     case MemRegion::AllocaRegionKind:
122     case MemRegion::CompoundLiteralRegionKind:
123     case MemRegion::FieldRegionKind:
124     case MemRegion::ObjCIvarRegionKind:
125     case MemRegion::ObjCStringRegionKind:
126     case MemRegion::VarRegionKind:
127     case MemRegion::CXXTempObjectRegionKind:
128     case MemRegion::CXXBaseObjectRegionKind:
129       return MakeElementRegion(R, PointeeTy);
130 
131     case MemRegion::ElementRegionKind: {
132       // If we are casting from an ElementRegion to another type, the
133       // algorithm is as follows:
134       //
135       // (1) Compute the "raw offset" of the ElementRegion from the
136       //     base region.  This is done by calling 'getAsRawOffset()'.
137       //
138       // (2a) If we get a 'RegionRawOffset' after calling
139       //      'getAsRawOffset()', determine if the absolute offset
140       //      can be exactly divided into chunks of the size of the
141       //      casted-pointee type.  If so, create a new ElementRegion with
142       //      the pointee-cast type as the new ElementType and the index
143       //      being the offset divded by the chunk size.  If not, create
144       //      a new ElementRegion at offset 0 off the raw offset region.
145       //
146       // (2b) If we don't a get a 'RegionRawOffset' after calling
147       //      'getAsRawOffset()', it means that we are at offset 0.
148       //
149       // FIXME: Handle symbolic raw offsets.
150 
151       const ElementRegion *elementR = cast<ElementRegion>(R);
152       const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
153       const MemRegion *baseR = rawOff.getRegion();
154 
155       // If we cannot compute a raw offset, throw up our hands and return
156       // a NULL MemRegion*.
157       if (!baseR)
158         return nullptr;
159 
160       CharUnits off = rawOff.getOffset();
161 
162       if (off.isZero()) {
163         // Edge case: we are at 0 bytes off the beginning of baseR.  We
164         // check to see if type we are casting to is the same as the base
165         // region.  If so, just return the base region.
166         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
167           QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
168           QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
169           if (CanonPointeeTy == ObjTy)
170             return baseR;
171         }
172 
173         // Otherwise, create a new ElementRegion at offset 0.
174         return MakeElementRegion(baseR, PointeeTy);
175       }
176 
177       // We have a non-zero offset from the base region.  We want to determine
178       // if the offset can be evenly divided by sizeof(PointeeTy).  If so,
179       // we create an ElementRegion whose index is that value.  Otherwise, we
180       // create two ElementRegions, one that reflects a raw offset and the other
181       // that reflects the cast.
182 
183       // Compute the index for the new ElementRegion.
184       int64_t newIndex = 0;
185       const MemRegion *newSuperR = nullptr;
186 
187       // We can only compute sizeof(PointeeTy) if it is a complete type.
188       if (!PointeeTy->isIncompleteType()) {
189         // Compute the size in **bytes**.
190         CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
191         if (!pointeeTySize.isZero()) {
192           // Is the offset a multiple of the size?  If so, we can layer the
193           // ElementRegion (with elementType == PointeeTy) directly on top of
194           // the base region.
195           if (off % pointeeTySize == 0) {
196             newIndex = off / pointeeTySize;
197             newSuperR = baseR;
198           }
199         }
200       }
201 
202       if (!newSuperR) {
203         // Create an intermediate ElementRegion to represent the raw byte.
204         // This will be the super region of the final ElementRegion.
205         newSuperR = MakeElementRegion(baseR, Ctx.CharTy, off.getQuantity());
206       }
207 
208       return MakeElementRegion(newSuperR, PointeeTy, newIndex);
209     }
210   }
211 
212   llvm_unreachable("unreachable");
213 }
214 
regionMatchesCXXRecordType(SVal V,QualType Ty)215 static bool regionMatchesCXXRecordType(SVal V, QualType Ty) {
216   const MemRegion *MR = V.getAsRegion();
217   if (!MR)
218     return true;
219 
220   const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
221   if (!TVR)
222     return true;
223 
224   const CXXRecordDecl *RD = TVR->getValueType()->getAsCXXRecordDecl();
225   if (!RD)
226     return true;
227 
228   const CXXRecordDecl *Expected = Ty->getPointeeCXXRecordDecl();
229   if (!Expected)
230     Expected = Ty->getAsCXXRecordDecl();
231 
232   return Expected->getCanonicalDecl() == RD->getCanonicalDecl();
233 }
234 
evalDerivedToBase(SVal Derived,const CastExpr * Cast)235 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
236   // Sanity check to avoid doing the wrong thing in the face of
237   // reinterpret_cast.
238   if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
239     return UnknownVal();
240 
241   // Walk through the cast path to create nested CXXBaseRegions.
242   SVal Result = Derived;
243   for (CastExpr::path_const_iterator I = Cast->path_begin(),
244                                      E = Cast->path_end();
245        I != E; ++I) {
246     Result = evalDerivedToBase(Result, (*I)->getType(), (*I)->isVirtual());
247   }
248   return Result;
249 }
250 
evalDerivedToBase(SVal Derived,const CXXBasePath & Path)251 SVal StoreManager::evalDerivedToBase(SVal Derived, const CXXBasePath &Path) {
252   // Walk through the path to create nested CXXBaseRegions.
253   SVal Result = Derived;
254   for (CXXBasePath::const_iterator I = Path.begin(), E = Path.end();
255        I != E; ++I) {
256     Result = evalDerivedToBase(Result, I->Base->getType(),
257                                I->Base->isVirtual());
258   }
259   return Result;
260 }
261 
evalDerivedToBase(SVal Derived,QualType BaseType,bool IsVirtual)262 SVal StoreManager::evalDerivedToBase(SVal Derived, QualType BaseType,
263                                      bool IsVirtual) {
264   Optional<loc::MemRegionVal> DerivedRegVal =
265       Derived.getAs<loc::MemRegionVal>();
266   if (!DerivedRegVal)
267     return Derived;
268 
269   const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl();
270   if (!BaseDecl)
271     BaseDecl = BaseType->getAsCXXRecordDecl();
272   assert(BaseDecl && "not a C++ object?");
273 
274   const MemRegion *BaseReg =
275     MRMgr.getCXXBaseObjectRegion(BaseDecl, DerivedRegVal->getRegion(),
276                                  IsVirtual);
277 
278   return loc::MemRegionVal(BaseReg);
279 }
280 
281 /// Returns the static type of the given region, if it represents a C++ class
282 /// object.
283 ///
284 /// This handles both fully-typed regions, where the dynamic type is known, and
285 /// symbolic regions, where the dynamic type is merely bounded (and even then,
286 /// only ostensibly!), but does not take advantage of any dynamic type info.
getCXXRecordType(const MemRegion * MR)287 static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) {
288   if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR))
289     return TVR->getValueType()->getAsCXXRecordDecl();
290   if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
291     return SR->getSymbol()->getType()->getPointeeCXXRecordDecl();
292   return nullptr;
293 }
294 
evalDynamicCast(SVal Base,QualType TargetType,bool & Failed)295 SVal StoreManager::evalDynamicCast(SVal Base, QualType TargetType,
296                                    bool &Failed) {
297   Failed = false;
298 
299   const MemRegion *MR = Base.getAsRegion();
300   if (!MR)
301     return UnknownVal();
302 
303   // Assume the derived class is a pointer or a reference to a CXX record.
304   TargetType = TargetType->getPointeeType();
305   assert(!TargetType.isNull());
306   const CXXRecordDecl *TargetClass = TargetType->getAsCXXRecordDecl();
307   if (!TargetClass && !TargetType->isVoidType())
308     return UnknownVal();
309 
310   // Drill down the CXXBaseObject chains, which represent upcasts (casts from
311   // derived to base).
312   while (const CXXRecordDecl *MRClass = getCXXRecordType(MR)) {
313     // If found the derived class, the cast succeeds.
314     if (MRClass == TargetClass)
315       return loc::MemRegionVal(MR);
316 
317     // We skip over incomplete types. They must be the result of an earlier
318     // reinterpret_cast, as one can only dynamic_cast between types in the same
319     // class hierarchy.
320     if (!TargetType->isVoidType() && MRClass->hasDefinition()) {
321       // Static upcasts are marked as DerivedToBase casts by Sema, so this will
322       // only happen when multiple or virtual inheritance is involved.
323       CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
324                          /*DetectVirtual=*/false);
325       if (MRClass->isDerivedFrom(TargetClass, Paths))
326         return evalDerivedToBase(loc::MemRegionVal(MR), Paths.front());
327     }
328 
329     if (const CXXBaseObjectRegion *BaseR = dyn_cast<CXXBaseObjectRegion>(MR)) {
330       // Drill down the chain to get the derived classes.
331       MR = BaseR->getSuperRegion();
332       continue;
333     }
334 
335     // If this is a cast to void*, return the region.
336     if (TargetType->isVoidType())
337       return loc::MemRegionVal(MR);
338 
339     // Strange use of reinterpret_cast can give us paths we don't reason
340     // about well, by putting in ElementRegions where we'd expect
341     // CXXBaseObjectRegions. If it's a valid reinterpret_cast (i.e. if the
342     // derived class has a zero offset from the base class), then it's safe
343     // to strip the cast; if it's invalid, -Wreinterpret-base-class should
344     // catch it. In the interest of performance, the analyzer will silently
345     // do the wrong thing in the invalid case (because offsets for subregions
346     // will be wrong).
347     const MemRegion *Uncasted = MR->StripCasts(/*IncludeBaseCasts=*/false);
348     if (Uncasted == MR) {
349       // We reached the bottom of the hierarchy and did not find the derived
350       // class. We we must be casting the base to derived, so the cast should
351       // fail.
352       break;
353     }
354 
355     MR = Uncasted;
356   }
357 
358   // We failed if the region we ended up with has perfect type info.
359   Failed = isa<TypedValueRegion>(MR);
360   return UnknownVal();
361 }
362 
363 
364 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
365 ///  implicit casts that arise from loads from regions that are reinterpreted
366 ///  as another region.
CastRetrievedVal(SVal V,const TypedValueRegion * R,QualType castTy,bool performTestOnly)367 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
368                                     QualType castTy, bool performTestOnly) {
369 
370   if (castTy.isNull() || V.isUnknownOrUndef())
371     return V;
372 
373   ASTContext &Ctx = svalBuilder.getContext();
374 
375   if (performTestOnly) {
376     // Automatically translate references to pointers.
377     QualType T = R->getValueType();
378     if (const ReferenceType *RT = T->getAs<ReferenceType>())
379       T = Ctx.getPointerType(RT->getPointeeType());
380 
381     assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
382     return V;
383   }
384 
385   return svalBuilder.dispatchCast(V, castTy);
386 }
387 
getLValueFieldOrIvar(const Decl * D,SVal Base)388 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
389   if (Base.isUnknownOrUndef())
390     return Base;
391 
392   Loc BaseL = Base.castAs<Loc>();
393   const MemRegion* BaseR = nullptr;
394 
395   switch (BaseL.getSubKind()) {
396   case loc::MemRegionKind:
397     BaseR = BaseL.castAs<loc::MemRegionVal>().getRegion();
398     break;
399 
400   case loc::GotoLabelKind:
401     // These are anormal cases. Flag an undefined value.
402     return UndefinedVal();
403 
404   case loc::ConcreteIntKind:
405     // While these seem funny, this can happen through casts.
406     // FIXME: What we should return is the field offset.  For example,
407     //  add the field offset to the integer value.  That way funny things
408     //  like this work properly:  &(((struct foo *) 0xa)->f)
409     return Base;
410 
411   default:
412     llvm_unreachable("Unhandled Base.");
413   }
414 
415   // NOTE: We must have this check first because ObjCIvarDecl is a subclass
416   // of FieldDecl.
417   if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
418     return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
419 
420   return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
421 }
422 
getLValueIvar(const ObjCIvarDecl * decl,SVal base)423 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
424   return getLValueFieldOrIvar(decl, base);
425 }
426 
getLValueElement(QualType elementType,NonLoc Offset,SVal Base)427 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,
428                                     SVal Base) {
429 
430   // If the base is an unknown or undefined value, just return it back.
431   // FIXME: For absolute pointer addresses, we just return that value back as
432   //  well, although in reality we should return the offset added to that
433   //  value.
434   if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>())
435     return Base;
436 
437   const MemRegion* BaseRegion = Base.castAs<loc::MemRegionVal>().getRegion();
438 
439   // Pointer of any type can be cast and used as array base.
440   const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
441 
442   // Convert the offset to the appropriate size and signedness.
443   Offset = svalBuilder.convertToArrayIndex(Offset).castAs<NonLoc>();
444 
445   if (!ElemR) {
446     //
447     // If the base region is not an ElementRegion, create one.
448     // This can happen in the following example:
449     //
450     //   char *p = __builtin_alloc(10);
451     //   p[1] = 8;
452     //
453     //  Observe that 'p' binds to an AllocaRegion.
454     //
455     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
456                                                     BaseRegion, Ctx));
457   }
458 
459   SVal BaseIdx = ElemR->getIndex();
460 
461   if (!BaseIdx.getAs<nonloc::ConcreteInt>())
462     return UnknownVal();
463 
464   const llvm::APSInt &BaseIdxI =
465       BaseIdx.castAs<nonloc::ConcreteInt>().getValue();
466 
467   // Only allow non-integer offsets if the base region has no offset itself.
468   // FIXME: This is a somewhat arbitrary restriction. We should be using
469   // SValBuilder here to add the two offsets without checking their types.
470   if (!Offset.getAs<nonloc::ConcreteInt>()) {
471     if (isa<ElementRegion>(BaseRegion->StripCasts()))
472       return UnknownVal();
473 
474     return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
475                                                     ElemR->getSuperRegion(),
476                                                     Ctx));
477   }
478 
479   const llvm::APSInt& OffI = Offset.castAs<nonloc::ConcreteInt>().getValue();
480   assert(BaseIdxI.isSigned());
481 
482   // Compute the new index.
483   nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
484                                                                     OffI));
485 
486   // Construct the new ElementRegion.
487   const MemRegion *ArrayR = ElemR->getSuperRegion();
488   return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
489                                                   Ctx));
490 }
491 
~BindingsHandler()492 StoreManager::BindingsHandler::~BindingsHandler() {}
493 
HandleBinding(StoreManager & SMgr,Store store,const MemRegion * R,SVal val)494 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
495                                                     Store store,
496                                                     const MemRegion* R,
497                                                     SVal val) {
498   SymbolRef SymV = val.getAsLocSymbol();
499   if (!SymV || SymV != Sym)
500     return true;
501 
502   if (Binding) {
503     First = false;
504     return false;
505   }
506   else
507     Binding = R;
508 
509   return true;
510 }
511