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