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