1 //===- Store.cpp - Interface for maps from Locations to Values ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defined the types Store and StoreManager. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/CharUnits.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/Type.h" 22 #include "clang/Basic/LLVM.h" 23 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h" 24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 25 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h" 30 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" 31 #include "llvm/ADT/APSInt.h" 32 #include "llvm/ADT/Optional.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/Support/Casting.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include <cassert> 37 #include <cstdint> 38 #include <optional> 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.castAs<Loc>(), 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 std::optional<const MemRegion *> StoreManager::castRegion(const MemRegion *R, 76 QualType CastToTy) { 77 ASTContext &Ctx = StateMgr.getContext(); 78 79 // Handle casts to Objective-C objects. 80 if (CastToTy->isObjCObjectPointerType()) 81 return R->StripCasts(); 82 83 if (CastToTy->isBlockPointerType()) { 84 // FIXME: We may need different solutions, depending on the symbol 85 // involved. Blocks can be casted to/from 'id', as they can be treated 86 // as Objective-C objects. This could possibly be handled by enhancing 87 // our reasoning of downcasts of symbolic objects. 88 if (isa<CodeTextRegion, SymbolicRegion>(R)) 89 return R; 90 91 // We don't know what to make of it. Return a NULL region, which 92 // will be interpreted as UnknownVal. 93 return std::nullopt; 94 } 95 96 // Now assume we are casting from pointer to pointer. Other cases should 97 // already be handled. 98 QualType PointeeTy = CastToTy->getPointeeType(); 99 QualType CanonPointeeTy = Ctx.getCanonicalType(PointeeTy); 100 CanonPointeeTy = CanonPointeeTy.getLocalUnqualifiedType(); 101 102 // Handle casts to void*. We just pass the region through. 103 if (CanonPointeeTy == Ctx.VoidTy) 104 return R; 105 106 const auto IsSameRegionType = [&Ctx](const MemRegion *R, QualType OtherTy) { 107 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) { 108 QualType ObjTy = Ctx.getCanonicalType(TR->getValueType()); 109 if (OtherTy == ObjTy.getLocalUnqualifiedType()) 110 return true; 111 } 112 return false; 113 }; 114 115 // Handle casts from compatible types. 116 if (R->isBoundable() && IsSameRegionType(R, CanonPointeeTy)) 117 return R; 118 119 // Process region cast according to the kind of the region being cast. 120 switch (R->getKind()) { 121 case MemRegion::CXXThisRegionKind: 122 case MemRegion::CodeSpaceRegionKind: 123 case MemRegion::StackLocalsSpaceRegionKind: 124 case MemRegion::StackArgumentsSpaceRegionKind: 125 case MemRegion::HeapSpaceRegionKind: 126 case MemRegion::UnknownSpaceRegionKind: 127 case MemRegion::StaticGlobalSpaceRegionKind: 128 case MemRegion::GlobalInternalSpaceRegionKind: 129 case MemRegion::GlobalSystemSpaceRegionKind: 130 case MemRegion::GlobalImmutableSpaceRegionKind: { 131 llvm_unreachable("Invalid region cast"); 132 } 133 134 case MemRegion::FunctionCodeRegionKind: 135 case MemRegion::BlockCodeRegionKind: 136 case MemRegion::BlockDataRegionKind: 137 case MemRegion::StringRegionKind: 138 // FIXME: Need to handle arbitrary downcasts. 139 case MemRegion::SymbolicRegionKind: 140 case MemRegion::AllocaRegionKind: 141 case MemRegion::CompoundLiteralRegionKind: 142 case MemRegion::FieldRegionKind: 143 case MemRegion::ObjCIvarRegionKind: 144 case MemRegion::ObjCStringRegionKind: 145 case MemRegion::NonParamVarRegionKind: 146 case MemRegion::ParamVarRegionKind: 147 case MemRegion::CXXTempObjectRegionKind: 148 case MemRegion::CXXBaseObjectRegionKind: 149 case MemRegion::CXXDerivedObjectRegionKind: 150 return MakeElementRegion(cast<SubRegion>(R), PointeeTy); 151 152 case MemRegion::ElementRegionKind: { 153 // If we are casting from an ElementRegion to another type, the 154 // algorithm is as follows: 155 // 156 // (1) Compute the "raw offset" of the ElementRegion from the 157 // base region. This is done by calling 'getAsRawOffset()'. 158 // 159 // (2a) If we get a 'RegionRawOffset' after calling 160 // 'getAsRawOffset()', determine if the absolute offset 161 // can be exactly divided into chunks of the size of the 162 // casted-pointee type. If so, create a new ElementRegion with 163 // the pointee-cast type as the new ElementType and the index 164 // being the offset divded by the chunk size. If not, create 165 // a new ElementRegion at offset 0 off the raw offset region. 166 // 167 // (2b) If we don't a get a 'RegionRawOffset' after calling 168 // 'getAsRawOffset()', it means that we are at offset 0. 169 // 170 // FIXME: Handle symbolic raw offsets. 171 172 const ElementRegion *elementR = cast<ElementRegion>(R); 173 const RegionRawOffset &rawOff = elementR->getAsArrayOffset(); 174 const MemRegion *baseR = rawOff.getRegion(); 175 176 // If we cannot compute a raw offset, throw up our hands and return 177 // a NULL MemRegion*. 178 if (!baseR) 179 return std::nullopt; 180 181 CharUnits off = rawOff.getOffset(); 182 183 if (off.isZero()) { 184 // Edge case: we are at 0 bytes off the beginning of baseR. We check to 185 // see if the type we are casting to is the same as the type of the base 186 // region. If so, just return the base region. 187 if (IsSameRegionType(baseR, CanonPointeeTy)) 188 return baseR; 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 // Early return 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 const MemRegion *DerivedReg = Derived.getAsRegion(); 280 if (!DerivedReg) 281 return Derived; 282 283 const CXXRecordDecl *BaseDecl = BaseType->getPointeeCXXRecordDecl(); 284 if (!BaseDecl) 285 BaseDecl = BaseType->getAsCXXRecordDecl(); 286 assert(BaseDecl && "not a C++ object?"); 287 288 if (const auto *AlreadyDerivedReg = 289 dyn_cast<CXXDerivedObjectRegion>(DerivedReg)) { 290 if (const auto *SR = 291 dyn_cast<SymbolicRegion>(AlreadyDerivedReg->getSuperRegion())) 292 if (SR->getSymbol()->getType()->getPointeeCXXRecordDecl() == BaseDecl) 293 return loc::MemRegionVal(SR); 294 295 DerivedReg = AlreadyDerivedReg->getSuperRegion(); 296 } 297 298 const MemRegion *BaseReg = MRMgr.getCXXBaseObjectRegion( 299 BaseDecl, cast<SubRegion>(DerivedReg), IsVirtual); 300 301 return loc::MemRegionVal(BaseReg); 302 } 303 304 /// Returns the static type of the given region, if it represents a C++ class 305 /// object. 306 /// 307 /// This handles both fully-typed regions, where the dynamic type is known, and 308 /// symbolic regions, where the dynamic type is merely bounded (and even then, 309 /// only ostensibly!), but does not take advantage of any dynamic type info. 310 static const CXXRecordDecl *getCXXRecordType(const MemRegion *MR) { 311 if (const auto *TVR = dyn_cast<TypedValueRegion>(MR)) 312 return TVR->getValueType()->getAsCXXRecordDecl(); 313 if (const auto *SR = dyn_cast<SymbolicRegion>(MR)) 314 return SR->getSymbol()->getType()->getPointeeCXXRecordDecl(); 315 return nullptr; 316 } 317 318 std::optional<SVal> StoreManager::evalBaseToDerived(SVal Base, 319 QualType TargetType) { 320 const MemRegion *MR = Base.getAsRegion(); 321 if (!MR) 322 return UnknownVal(); 323 324 // Assume the derived class is a pointer or a reference to a CXX record. 325 TargetType = TargetType->getPointeeType(); 326 assert(!TargetType.isNull()); 327 const CXXRecordDecl *TargetClass = TargetType->getAsCXXRecordDecl(); 328 if (!TargetClass && !TargetType->isVoidType()) 329 return UnknownVal(); 330 331 // Drill down the CXXBaseObject chains, which represent upcasts (casts from 332 // derived to base). 333 while (const CXXRecordDecl *MRClass = getCXXRecordType(MR)) { 334 // If found the derived class, the cast succeeds. 335 if (MRClass == TargetClass) 336 return loc::MemRegionVal(MR); 337 338 // We skip over incomplete types. They must be the result of an earlier 339 // reinterpret_cast, as one can only dynamic_cast between types in the same 340 // class hierarchy. 341 if (!TargetType->isVoidType() && MRClass->hasDefinition()) { 342 // Static upcasts are marked as DerivedToBase casts by Sema, so this will 343 // only happen when multiple or virtual inheritance is involved. 344 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true, 345 /*DetectVirtual=*/false); 346 if (MRClass->isDerivedFrom(TargetClass, Paths)) 347 return evalDerivedToBase(loc::MemRegionVal(MR), Paths.front()); 348 } 349 350 if (const auto *BaseR = dyn_cast<CXXBaseObjectRegion>(MR)) { 351 // Drill down the chain to get the derived classes. 352 MR = BaseR->getSuperRegion(); 353 continue; 354 } 355 356 // If this is a cast to void*, return the region. 357 if (TargetType->isVoidType()) 358 return loc::MemRegionVal(MR); 359 360 // Strange use of reinterpret_cast can give us paths we don't reason 361 // about well, by putting in ElementRegions where we'd expect 362 // CXXBaseObjectRegions. If it's a valid reinterpret_cast (i.e. if the 363 // derived class has a zero offset from the base class), then it's safe 364 // to strip the cast; if it's invalid, -Wreinterpret-base-class should 365 // catch it. In the interest of performance, the analyzer will silently 366 // do the wrong thing in the invalid case (because offsets for subregions 367 // will be wrong). 368 const MemRegion *Uncasted = MR->StripCasts(/*IncludeBaseCasts=*/false); 369 if (Uncasted == MR) { 370 // We reached the bottom of the hierarchy and did not find the derived 371 // class. We must be casting the base to derived, so the cast should 372 // fail. 373 break; 374 } 375 376 MR = Uncasted; 377 } 378 379 // If we're casting a symbolic base pointer to a derived class, use 380 // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an 381 // unrelated type, it must be a weird reinterpret_cast and we have to 382 // be fine with ElementRegion. TODO: Should we instead make 383 // Derived{TargetClass, Element{SourceClass, SR}}? 384 if (const auto *SR = dyn_cast<SymbolicRegion>(MR)) { 385 QualType T = SR->getSymbol()->getType(); 386 const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl(); 387 if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass)) 388 return loc::MemRegionVal( 389 MRMgr.getCXXDerivedObjectRegion(TargetClass, SR)); 390 return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType)); 391 } 392 393 // We failed if the region we ended up with has perfect type info. 394 if (isa<TypedValueRegion>(MR)) 395 return std::nullopt; 396 397 return UnknownVal(); 398 } 399 400 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) { 401 if (Base.isUnknownOrUndef()) 402 return Base; 403 404 Loc BaseL = Base.castAs<Loc>(); 405 const SubRegion* BaseR = nullptr; 406 407 switch (BaseL.getSubKind()) { 408 case loc::MemRegionValKind: 409 BaseR = cast<SubRegion>(BaseL.castAs<loc::MemRegionVal>().getRegion()); 410 break; 411 412 case loc::GotoLabelKind: 413 // These are anormal cases. Flag an undefined value. 414 return UndefinedVal(); 415 416 case loc::ConcreteIntKind: 417 // While these seem funny, this can happen through casts. 418 // FIXME: What we should return is the field offset, not base. For example, 419 // add the field offset to the integer value. That way things 420 // like this work properly: &(((struct foo *) 0xa)->f) 421 // However, that's not easy to fix without reducing our abilities 422 // to catch null pointer dereference. Eg., ((struct foo *)0x0)->f = 7 423 // is a null dereference even though we're dereferencing offset of f 424 // rather than null. Coming up with an approach that computes offsets 425 // over null pointers properly while still being able to catch null 426 // dereferences might be worth it. 427 return Base; 428 429 default: 430 llvm_unreachable("Unhandled Base."); 431 } 432 433 // NOTE: We must have this check first because ObjCIvarDecl is a subclass 434 // of FieldDecl. 435 if (const auto *ID = dyn_cast<ObjCIvarDecl>(D)) 436 return loc::MemRegionVal(MRMgr.getObjCIvarRegion(ID, BaseR)); 437 438 return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR)); 439 } 440 441 SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) { 442 return getLValueFieldOrIvar(decl, base); 443 } 444 445 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset, 446 SVal Base) { 447 448 // Special case, if index is 0, return the same type as if 449 // this was not an array dereference. 450 if (Offset.isZeroConstant()) { 451 QualType BT = Base.getType(this->Ctx); 452 if (!BT.isNull() && !elementType.isNull()) { 453 QualType PointeeTy = BT->getPointeeType(); 454 if (!PointeeTy.isNull() && 455 PointeeTy.getCanonicalType() == elementType.getCanonicalType()) 456 return Base; 457 } 458 } 459 460 // If the base is an unknown or undefined value, just return it back. 461 // FIXME: For absolute pointer addresses, we just return that value back as 462 // well, although in reality we should return the offset added to that 463 // value. See also the similar FIXME in getLValueFieldOrIvar(). 464 if (Base.isUnknownOrUndef() || isa<loc::ConcreteInt>(Base)) 465 return Base; 466 467 if (isa<loc::GotoLabel>(Base)) 468 return UnknownVal(); 469 470 const SubRegion *BaseRegion = 471 Base.castAs<loc::MemRegionVal>().getRegionAs<SubRegion>(); 472 473 // Pointer of any type can be cast and used as array base. 474 const auto *ElemR = dyn_cast<ElementRegion>(BaseRegion); 475 476 // Convert the offset to the appropriate size and signedness. 477 Offset = svalBuilder.convertToArrayIndex(Offset).castAs<NonLoc>(); 478 479 if (!ElemR) { 480 // If the base region is not an ElementRegion, create one. 481 // This can happen in the following example: 482 // 483 // char *p = __builtin_alloc(10); 484 // p[1] = 8; 485 // 486 // Observe that 'p' binds to an AllocaRegion. 487 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, Offset, 488 BaseRegion, Ctx)); 489 } 490 491 SVal BaseIdx = ElemR->getIndex(); 492 493 if (!isa<nonloc::ConcreteInt>(BaseIdx)) 494 return UnknownVal(); 495 496 const llvm::APSInt &BaseIdxI = 497 BaseIdx.castAs<nonloc::ConcreteInt>().getValue(); 498 499 // Only allow non-integer offsets if the base region has no offset itself. 500 // FIXME: This is a somewhat arbitrary restriction. We should be using 501 // SValBuilder here to add the two offsets without checking their types. 502 if (!isa<nonloc::ConcreteInt>(Offset)) { 503 if (isa<ElementRegion>(BaseRegion->StripCasts())) 504 return UnknownVal(); 505 506 return loc::MemRegionVal(MRMgr.getElementRegion( 507 elementType, Offset, cast<SubRegion>(ElemR->getSuperRegion()), Ctx)); 508 } 509 510 const llvm::APSInt& OffI = Offset.castAs<nonloc::ConcreteInt>().getValue(); 511 assert(BaseIdxI.isSigned()); 512 513 // Compute the new index. 514 nonloc::ConcreteInt NewIdx(svalBuilder.getBasicValueFactory().getValue(BaseIdxI + 515 OffI)); 516 517 // Construct the new ElementRegion. 518 const SubRegion *ArrayR = cast<SubRegion>(ElemR->getSuperRegion()); 519 return loc::MemRegionVal(MRMgr.getElementRegion(elementType, NewIdx, ArrayR, 520 Ctx)); 521 } 522 523 StoreManager::BindingsHandler::~BindingsHandler() = default; 524 525 bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr, 526 Store store, 527 const MemRegion* R, 528 SVal val) { 529 SymbolRef SymV = val.getAsLocSymbol(); 530 if (!SymV || SymV != Sym) 531 return true; 532 533 if (Binding) { 534 First = false; 535 return false; 536 } 537 else 538 Binding = R; 539 540 return true; 541 } 542