1 //== Store.cpp - Interface for maps from Locations to Values ----*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defined the types Store and StoreManager.
12 //===----------------------------------------------------------------------===//
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"
21 using namespace clang;
24 StoreManager::StoreManager(ProgramStateManager &stateMgr)
25 : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
26 MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
28 StoreRef StoreManager::enterStackFrame(Store OldStore,
29 const CallEvent &Call,
30 const StackFrameContext *LCtx) {
31 StoreRef Store = StoreRef(OldStore, *this);
33 SmallVector<CallEvent::FrameBindingTy, 16> InitialBindings;
34 Call.getInitialStackFrameContents(LCtx, InitialBindings);
36 for (CallEvent::BindingsTy::iterator I = InitialBindings.begin(),
37 E = InitialBindings.end();
39 Store = Bind(Store.getStore(), I->first, I->second);
45 const ElementRegion *StoreManager::MakeElementRegion(const SubRegion *Base,
48 NonLoc idx = svalBuilder.makeArrayIndex(index);
49 return MRMgr.getElementRegion(EleTy, idx, Base, svalBuilder.getContext());
52 StoreRef StoreManager::BindDefault(Store store, const MemRegion *R, SVal V) {
53 return StoreRef(store, *this);
56 const ElementRegion *StoreManager::GetElementZeroRegion(const SubRegion *R,
58 NonLoc idx = svalBuilder.makeZeroArrayIndex();
60 return MRMgr.getElementRegion(T, idx, R, Ctx);
63 const MemRegion *StoreManager::castRegion(const MemRegion *R, QualType CastToTy) {
65 ASTContext &Ctx = StateMgr.getContext();
67 // Handle casts to Objective-C objects.
68 if (CastToTy->isObjCObjectPointerType())
69 return R->StripCasts();
71 if (CastToTy->isBlockPointerType()) {
72 // FIXME: We may need different solutions, depending on the symbol
73 // involved. Blocks can be casted to/from 'id', as they can be treated
74 // as Objective-C objects. This could possibly be handled by enhancing
75 // our reasoning of downcasts of symbolic objects.
76 if (isa<CodeTextRegion>(R) || isa<SymbolicRegion>(R))
79 // We don't know what to make of it. Return a NULL region, which
80 // will be interpretted as UnknownVal.
84 // Now assume we are casting from pointer to pointer. Other cases should
85 // already be handled.
86 QualType PointeeTy = CastToTy->getPointeeType();
87 QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
89 // Handle casts to void*. We just pass the region through.
90 if (CanonPointeeTy.getLocalUnqualifiedType() == Ctx.VoidTy)
93 // Handle casts from compatible types.
95 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
96 QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
97 if (CanonPointeeTy == ObjTy)
101 // Process region cast according to the kind of the region being cast.
102 switch (R->getKind()) {
103 case MemRegion::CXXThisRegionKind:
104 case MemRegion::CodeSpaceRegionKind:
105 case MemRegion::StackLocalsSpaceRegionKind:
106 case MemRegion::StackArgumentsSpaceRegionKind:
107 case MemRegion::HeapSpaceRegionKind:
108 case MemRegion::UnknownSpaceRegionKind:
109 case MemRegion::StaticGlobalSpaceRegionKind:
110 case MemRegion::GlobalInternalSpaceRegionKind:
111 case MemRegion::GlobalSystemSpaceRegionKind:
112 case MemRegion::GlobalImmutableSpaceRegionKind: {
113 llvm_unreachable("Invalid region cast");
116 case MemRegion::FunctionCodeRegionKind:
117 case MemRegion::BlockCodeRegionKind:
118 case MemRegion::BlockDataRegionKind:
119 case MemRegion::StringRegionKind:
120 // FIXME: Need to handle arbitrary downcasts.
121 case MemRegion::SymbolicRegionKind:
122 case MemRegion::AllocaRegionKind:
123 case MemRegion::CompoundLiteralRegionKind:
124 case MemRegion::FieldRegionKind:
125 case MemRegion::ObjCIvarRegionKind:
126 case MemRegion::ObjCStringRegionKind:
127 case MemRegion::VarRegionKind:
128 case MemRegion::CXXTempObjectRegionKind:
129 case MemRegion::CXXBaseObjectRegionKind:
130 return MakeElementRegion(cast<SubRegion>(R), PointeeTy);
132 case MemRegion::ElementRegionKind: {
133 // If we are casting from an ElementRegion to another type, the
134 // algorithm is as follows:
136 // (1) Compute the "raw offset" of the ElementRegion from the
137 // base region. This is done by calling 'getAsRawOffset()'.
139 // (2a) If we get a 'RegionRawOffset' after calling
140 // 'getAsRawOffset()', determine if the absolute offset
141 // can be exactly divided into chunks of the size of the
142 // casted-pointee type. If so, create a new ElementRegion with
143 // the pointee-cast type as the new ElementType and the index
144 // being the offset divded by the chunk size. If not, create
145 // a new ElementRegion at offset 0 off the raw offset region.
147 // (2b) If we don't a get a 'RegionRawOffset' after calling
148 // 'getAsRawOffset()', it means that we are at offset 0.
150 // FIXME: Handle symbolic raw offsets.
152 const ElementRegion *elementR = cast<ElementRegion>(R);
153 const RegionRawOffset &rawOff = elementR->getAsArrayOffset();
154 const MemRegion *baseR = rawOff.getRegion();
156 // If we cannot compute a raw offset, throw up our hands and return
157 // a NULL MemRegion*.
161 CharUnits off = rawOff.getOffset();
164 // Edge case: we are at 0 bytes off the beginning of baseR. We
165 // check to see if type we are casting to is the same as the base
166 // region. If so, just return the base region.
167 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(baseR)) {
168 QualType ObjTy = Ctx.getCanonicalType(TR->getValueType());
169 QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy);
170 if (CanonPointeeTy == ObjTy)
174 // Otherwise, create a new ElementRegion at offset 0.
175 return MakeElementRegion(cast<SubRegion>(baseR), PointeeTy);
178 // We have a non-zero offset from the base region. We want to determine
179 // if the offset can be evenly divided by sizeof(PointeeTy). If so,
180 // we create an ElementRegion whose index is that value. Otherwise, we
181 // create two ElementRegions, one that reflects a raw offset and the other
182 // that reflects the cast.
184 // Compute the index for the new ElementRegion.
185 int64_t newIndex = 0;
186 const MemRegion *newSuperR = nullptr;
188 // We can only compute sizeof(PointeeTy) if it is a complete type.
189 if (!PointeeTy->isIncompleteType()) {
190 // Compute the size in **bytes**.
191 CharUnits pointeeTySize = Ctx.getTypeSizeInChars(PointeeTy);
192 if (!pointeeTySize.isZero()) {
193 // Is the offset a multiple of the size? If so, we can layer the
194 // ElementRegion (with elementType == PointeeTy) directly on top of
196 if (off % pointeeTySize == 0) {
197 newIndex = off / pointeeTySize;
204 // Create an intermediate ElementRegion to represent the raw byte.
205 // This will be the super region of the final ElementRegion.
206 newSuperR = MakeElementRegion(cast<SubRegion>(baseR), Ctx.CharTy,
210 return MakeElementRegion(cast<SubRegion>(newSuperR), PointeeTy, newIndex);
214 llvm_unreachable("unreachable");
217 static bool regionMatchesCXXRecordType(SVal V, QualType Ty) {
218 const MemRegion *MR = V.getAsRegion();
222 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
226 const CXXRecordDecl *RD = TVR->getValueType()->getAsCXXRecordDecl();
230 const CXXRecordDecl *Expected = Ty->getPointeeCXXRecordDecl();
232 Expected = Ty->getAsCXXRecordDecl();
234 return Expected->getCanonicalDecl() == RD->getCanonicalDecl();
237 SVal StoreManager::evalDerivedToBase(SVal Derived, const CastExpr *Cast) {
238 // Sanity check to avoid doing the wrong thing in the face of
240 if (!regionMatchesCXXRecordType(Derived, Cast->getSubExpr()->getType()))
243 // Walk through the cast path to create nested CXXBaseRegions.
244 SVal Result = Derived;
245 for (CastExpr::path_const_iterator I = Cast->path_begin(),
246 E = Cast->path_end();
248 Result = evalDerivedToBase(Result, (*I)->getType(), (*I)->isVirtual());
253 SVal StoreManager::evalDerivedToBase(SVal Derived, const CXXBasePath &Path) {
254 // Walk through the path to create nested CXXBaseRegions.
255 SVal Result = Derived;
256 for (CXXBasePath::const_iterator I = Path.begin(), E = Path.end();
258 Result = evalDerivedToBase(Result, I->Base->getType(),
259 I->Base->isVirtual());
264 SVal StoreManager::evalDerivedToBase(SVal Derived, QualType BaseType,
266 Optional<loc::MemRegionVal> DerivedRegVal =
267 Derived.getAs<loc::MemRegionVal>();
271 const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl();
273 BaseDecl = BaseType->getAsCXXRecordDecl();
274 assert(BaseDecl && "not a C++ object?");
276 const MemRegion *BaseReg = MRMgr.getCXXBaseObjectRegion(
277 BaseDecl, cast<SubRegion>(DerivedRegVal->getRegion()), IsVirtual);
279 return loc::MemRegionVal(BaseReg);
282 /// Returns the static type of the given region, if it represents a C++ class
285 /// This handles both fully-typed regions, where the dynamic type is known, and
286 /// symbolic regions, where the dynamic type is merely bounded (and even then,
287 /// only ostensibly!), but does not take advantage of any dynamic type info.
288 static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) {
289 if (const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR))
290 return TVR->getValueType()->getAsCXXRecordDecl();
291 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(MR))
292 return SR->getSymbol()->getType()->getPointeeCXXRecordDecl();
296 SVal StoreManager::attemptDownCast(SVal Base, QualType TargetType,
300 const MemRegion *MR = Base.getAsRegion();
304 // Assume the derived class is a pointer or a reference to a CXX record.
305 TargetType = TargetType->getPointeeType();
306 assert(!TargetType.isNull());
307 const CXXRecordDecl *TargetClass = TargetType->getAsCXXRecordDecl();
308 if (!TargetClass && !TargetType->isVoidType())
311 // Drill down the CXXBaseObject chains, which represent upcasts (casts from
313 while (const CXXRecordDecl *MRClass = getCXXRecordType(MR)) {
314 // If found the derived class, the cast succeeds.
315 if (MRClass == TargetClass)
316 return loc::MemRegionVal(MR);
318 // We skip over incomplete types. They must be the result of an earlier
319 // reinterpret_cast, as one can only dynamic_cast between types in the same
321 if (!TargetType->isVoidType() && MRClass->hasDefinition()) {
322 // Static upcasts are marked as DerivedToBase casts by Sema, so this will
323 // only happen when multiple or virtual inheritance is involved.
324 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true,
325 /*DetectVirtual=*/false);
326 if (MRClass->isDerivedFrom(TargetClass, Paths))
327 return evalDerivedToBase(loc::MemRegionVal(MR), Paths.front());
330 if (const CXXBaseObjectRegion *BaseR = dyn_cast<CXXBaseObjectRegion>(MR)) {
331 // Drill down the chain to get the derived classes.
332 MR = BaseR->getSuperRegion();
336 // If this is a cast to void*, return the region.
337 if (TargetType->isVoidType())
338 return loc::MemRegionVal(MR);
340 // Strange use of reinterpret_cast can give us paths we don't reason
341 // about well, by putting in ElementRegions where we'd expect
342 // CXXBaseObjectRegions. If it's a valid reinterpret_cast (i.e. if the
343 // derived class has a zero offset from the base class), then it's safe
344 // to strip the cast; if it's invalid, -Wreinterpret-base-class should
345 // catch it. In the interest of performance, the analyzer will silently
346 // do the wrong thing in the invalid case (because offsets for subregions
348 const MemRegion *Uncasted = MR->StripCasts(/*IncludeBaseCasts=*/false);
349 if (Uncasted == MR) {
350 // We reached the bottom of the hierarchy and did not find the derived
351 // class. We we must be casting the base to derived, so the cast should
359 // We failed if the region we ended up with has perfect type info.
360 Failed = isa<TypedValueRegion>(MR);
365 /// CastRetrievedVal - Used by subclasses of StoreManager to implement
366 /// implicit casts that arise from loads from regions that are reinterpreted
367 /// as another region.
368 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
369 QualType castTy, bool performTestOnly) {
371 if (castTy.isNull() || V.isUnknownOrUndef())
374 ASTContext &Ctx = svalBuilder.getContext();
376 if (performTestOnly) {
377 // Automatically translate references to pointers.
378 QualType T = R->getValueType();
379 if (const ReferenceType *RT = T->getAs<ReferenceType>())
380 T = Ctx.getPointerType(RT->getPointeeType());
382 assert(svalBuilder.getContext().hasSameUnqualifiedType(castTy, T));
386 return svalBuilder.dispatchCast(V, castTy);
389 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
390 if (Base.isUnknownOrUndef())
393 Loc BaseL = Base.castAs<Loc>();
394 const SubRegion* BaseR = nullptr;
396 switch (BaseL.getSubKind()) {
397 case loc::MemRegionValKind:
398 BaseR = cast<SubRegion>(BaseL.castAs<loc::MemRegionVal>().getRegion());
401 case loc::GotoLabelKind:
402 // These are anormal cases. Flag an undefined value.
403 return UndefinedVal();
405 case loc::ConcreteIntKind:
406 // While these seem funny, this can happen through casts.
407 // FIXME: What we should return is the field offset, not base. For example,
408 // add the field offset to the integer value. That way things
409 // like this work properly: &(((struct foo *) 0xa)->f)
410 // However, that's not easy to fix without reducing our abilities
411 // to catch null pointer dereference. Eg., ((struct foo *)0x0)->f = 7
412 // is a null dereference even though we're dereferencing offset of f
413 // rather than null. Coming up with an approach that computes offsets
414 // over null pointers properly while still being able to catch null
415 // dereferences might be worth it.
419 llvm_unreachable("Unhandled Base.");
422 // NOTE: We must have this check first because ObjCIvarDecl is a subclass
424 if (const ObjCIvarDecl *ID = dyn_cast<ObjCIvarDecl>(D))
425 return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR));
427 return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR));
430 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
431 return getLValueFieldOrIvar(decl, base);
434 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,
437 // If the base is an unknown or undefined value, just return it back.
438 // FIXME: For absolute pointer addresses, we just return that value back as
439 // well, although in reality we should return the offset added to that
440 // value. See also the similar FIXME in getLValueFieldOrIvar().
441 if (Base.isUnknownOrUndef() || Base.getAs<loc::ConcreteInt>())
444 const SubRegion *BaseRegion =
445 Base.castAs<loc::MemRegionVal>().getRegionAs<SubRegion>();
447 // Pointer of any type can be cast and used as array base.
448 const ElementRegion *ElemR = dyn_cast<ElementRegion>(BaseRegion);
450 // Convert the offset to the appropriate size and signedness.
451 Offset = svalBuilder.convertToArrayIndex(Offset).castAs<NonLoc>();
455 // If the base region is not an ElementRegion, create one.
456 // This can happen in the following example:
458 // char *p = __builtin_alloc(10);
461 // Observe that 'p' binds to an AllocaRegion.
463 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset,
467 SVal BaseIdx = ElemR->getIndex();
469 if (!BaseIdx.getAs<nonloc::ConcreteInt>())
472 const llvm::APSInt &BaseIdxI =
473 BaseIdx.castAs<nonloc::ConcreteInt>().getValue();
475 // Only allow non-integer offsets if the base region has no offset itself.
476 // FIXME: This is a somewhat arbitrary restriction. We should be using
477 // SValBuilder here to add the two offsets without checking their types.
478 if (!Offset.getAs<nonloc::ConcreteInt>()) {
479 if (isa<ElementRegion>(BaseRegion->StripCasts()))
482 return loc::MemRegionVal(MRMgr.getElementRegion(
483 elementType, Offset, cast<SubRegion>(ElemR->getSuperRegion()), Ctx));
486 const llvm::APSInt& OffI = Offset.castAs<nonloc::ConcreteInt>().getValue();
487 assert(BaseIdxI.isSigned());
489 // Compute the new index.
490 nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI +
493 // Construct the new ElementRegion.
494 const SubRegion *ArrayR = cast<SubRegion>(ElemR->getSuperRegion());
495 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR,
499 StoreManager::BindingsHandler::~BindingsHandler() {}
501 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
505 SymbolRef SymV = val.getAsLocSymbol();
506 if (!SymV || SymV != Sym)