1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===// 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 defines the C++ expression evaluation engine. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 14 #include "clang/Analysis/ConstructionContext.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/AST/StmtCXX.h" 17 #include "clang/AST/ParentMap.h" 18 #include "clang/Basic/PrettyStackTrace.h" 19 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 20 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 22 23 using namespace clang; 24 using namespace ento; 25 26 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 27 ExplodedNode *Pred, 28 ExplodedNodeSet &Dst) { 29 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 30 const Expr *tempExpr = ME->getSubExpr()->IgnoreParens(); 31 ProgramStateRef state = Pred->getState(); 32 const LocationContext *LCtx = Pred->getLocationContext(); 33 34 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME); 35 Bldr.generateNode(ME, Pred, state); 36 } 37 38 // FIXME: This is the sort of code that should eventually live in a Core 39 // checker rather than as a special case in ExprEngine. 40 void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 41 const CallEvent &Call) { 42 SVal ThisVal; 43 bool AlwaysReturnsLValue; 44 const CXXRecordDecl *ThisRD = nullptr; 45 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) { 46 assert(Ctor->getDecl()->isTrivial()); 47 assert(Ctor->getDecl()->isCopyOrMoveConstructor()); 48 ThisVal = Ctor->getCXXThisVal(); 49 ThisRD = Ctor->getDecl()->getParent(); 50 AlwaysReturnsLValue = false; 51 } else { 52 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial()); 53 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() == 54 OO_Equal); 55 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal(); 56 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent(); 57 AlwaysReturnsLValue = true; 58 } 59 60 assert(ThisRD); 61 if (ThisRD->isEmpty()) { 62 // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal 63 // and bind it and RegionStore would think that the actual value 64 // in this region at this offset is unknown. 65 return; 66 } 67 68 const LocationContext *LCtx = Pred->getLocationContext(); 69 70 ExplodedNodeSet Dst; 71 Bldr.takeNodes(Pred); 72 73 SVal V = Call.getArgSVal(0); 74 75 // If the value being copied is not unknown, load from its location to get 76 // an aggregate rvalue. 77 if (Optional<Loc> L = V.getAs<Loc>()) 78 V = Pred->getState()->getSVal(*L); 79 else 80 assert(V.isUnknownOrUndef()); 81 82 const Expr *CallExpr = Call.getOriginExpr(); 83 evalBind(Dst, CallExpr, Pred, ThisVal, V, true); 84 85 PostStmt PS(CallExpr, LCtx); 86 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); 87 I != E; ++I) { 88 ProgramStateRef State = (*I)->getState(); 89 if (AlwaysReturnsLValue) 90 State = State->BindExpr(CallExpr, LCtx, ThisVal); 91 else 92 State = bindReturnValue(Call, LCtx, State); 93 Bldr.generateNode(PS, State, *I); 94 } 95 } 96 97 SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue, 98 QualType &Ty, bool &IsArray, unsigned Idx) { 99 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 100 ASTContext &Ctx = SVB.getContext(); 101 102 if (const ArrayType *AT = Ctx.getAsArrayType(Ty)) { 103 while (AT) { 104 Ty = AT->getElementType(); 105 AT = dyn_cast<ArrayType>(AT->getElementType()); 106 } 107 LValue = State->getLValue(Ty, SVB.makeArrayIndex(Idx), LValue); 108 IsArray = true; 109 } 110 111 return LValue; 112 } 113 114 SVal ExprEngine::computeObjectUnderConstruction( 115 const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 116 const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx) { 117 SValBuilder &SVB = getSValBuilder(); 118 MemRegionManager &MRMgr = SVB.getRegionManager(); 119 ASTContext &ACtx = SVB.getContext(); 120 121 // Compute the target region by exploring the construction context. 122 if (CC) { 123 switch (CC->getKind()) { 124 case ConstructionContext::CXX17ElidedCopyVariableKind: 125 case ConstructionContext::SimpleVariableKind: { 126 const auto *DSCC = cast<VariableConstructionContext>(CC); 127 const auto *DS = DSCC->getDeclStmt(); 128 const auto *Var = cast<VarDecl>(DS->getSingleDecl()); 129 QualType Ty = Var->getType(); 130 return makeElementRegion(State, State->getLValue(Var, LCtx), Ty, 131 CallOpts.IsArrayCtorOrDtor, Idx); 132 } 133 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 134 case ConstructionContext::SimpleConstructorInitializerKind: { 135 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 136 const auto *Init = ICC->getCXXCtorInitializer(); 137 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 138 Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame()); 139 SVal ThisVal = State->getSVal(ThisPtr); 140 if (Init->isBaseInitializer()) { 141 const auto *ThisReg = cast<SubRegion>(ThisVal.getAsRegion()); 142 const CXXRecordDecl *BaseClass = 143 Init->getBaseClass()->getAsCXXRecordDecl(); 144 const auto *BaseReg = 145 MRMgr.getCXXBaseObjectRegion(BaseClass, ThisReg, 146 Init->isBaseVirtual()); 147 return SVB.makeLoc(BaseReg); 148 } 149 if (Init->isDelegatingInitializer()) 150 return ThisVal; 151 152 const ValueDecl *Field; 153 SVal FieldVal; 154 if (Init->isIndirectMemberInitializer()) { 155 Field = Init->getIndirectMember(); 156 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal); 157 } else { 158 Field = Init->getMember(); 159 FieldVal = State->getLValue(Init->getMember(), ThisVal); 160 } 161 162 QualType Ty = Field->getType(); 163 return makeElementRegion(State, FieldVal, Ty, CallOpts.IsArrayCtorOrDtor, 164 Idx); 165 } 166 case ConstructionContext::NewAllocatedObjectKind: { 167 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 168 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 169 const auto *NE = NECC->getCXXNewExpr(); 170 SVal V = *getObjectUnderConstruction(State, NE, LCtx); 171 if (const SubRegion *MR = 172 dyn_cast_or_null<SubRegion>(V.getAsRegion())) { 173 if (NE->isArray()) { 174 // TODO: In fact, we need to call the constructor for every 175 // allocated element, not just the first one! 176 CallOpts.IsArrayCtorOrDtor = true; 177 178 auto R = MRMgr.getElementRegion(NE->getType()->getPointeeType(), 179 svalBuilder.makeArrayIndex(Idx), MR, 180 SVB.getContext()); 181 182 return loc::MemRegionVal(R); 183 } 184 return V; 185 } 186 // TODO: Detect when the allocator returns a null pointer. 187 // Constructor shall not be called in this case. 188 } 189 break; 190 } 191 case ConstructionContext::SimpleReturnedValueKind: 192 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 193 // The temporary is to be managed by the parent stack frame. 194 // So build it in the parent stack frame if we're not in the 195 // top frame of the analysis. 196 const StackFrameContext *SFC = LCtx->getStackFrame(); 197 if (const LocationContext *CallerLCtx = SFC->getParent()) { 198 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 199 .getAs<CFGCXXRecordTypedCall>(); 200 if (!RTC) { 201 // We were unable to find the correct construction context for the 202 // call in the parent stack frame. This is equivalent to not being 203 // able to find construction context at all. 204 break; 205 } 206 if (isa<BlockInvocationContext>(CallerLCtx)) { 207 // Unwrap block invocation contexts. They're mostly part of 208 // the current stack frame. 209 CallerLCtx = CallerLCtx->getParent(); 210 assert(!isa<BlockInvocationContext>(CallerLCtx)); 211 } 212 return computeObjectUnderConstruction( 213 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 214 RTC->getConstructionContext(), CallOpts); 215 } else { 216 // We are on the top frame of the analysis. We do not know where is the 217 // object returned to. Conjure a symbolic region for the return value. 218 // TODO: We probably need a new MemRegion kind to represent the storage 219 // of that SymbolicRegion, so that we cound produce a fancy symbol 220 // instead of an anonymous conjured symbol. 221 // TODO: Do we need to track the region to avoid having it dead 222 // too early? It does die too early, at least in C++17, but because 223 // putting anything into a SymbolicRegion causes an immediate escape, 224 // it doesn't cause any leak false positives. 225 const auto *RCC = cast<ReturnedValueConstructionContext>(CC); 226 // Make sure that this doesn't coincide with any other symbol 227 // conjured for the returned expression. 228 static const int TopLevelSymRegionTag = 0; 229 const Expr *RetE = RCC->getReturnStmt()->getRetValue(); 230 assert(RetE && "Void returns should not have a construction context"); 231 QualType ReturnTy = RetE->getType(); 232 QualType RegionTy = ACtx.getPointerType(ReturnTy); 233 return SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC, RegionTy, 234 currBldrCtx->blockCount()); 235 } 236 llvm_unreachable("Unhandled return value construction context!"); 237 } 238 case ConstructionContext::ElidedTemporaryObjectKind: { 239 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); 240 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 241 242 // Support pre-C++17 copy elision. We'll have the elidable copy 243 // constructor in the AST and in the CFG, but we'll skip it 244 // and construct directly into the final object. This call 245 // also sets the CallOpts flags for us. 246 // If the elided copy/move constructor is not supported, there's still 247 // benefit in trying to model the non-elided constructor. 248 // Stash our state before trying to elide, as it'll get overwritten. 249 ProgramStateRef PreElideState = State; 250 EvalCallOptions PreElideCallOpts = CallOpts; 251 252 SVal V = computeObjectUnderConstruction( 253 TCC->getConstructorAfterElision(), State, LCtx, 254 TCC->getConstructionContextAfterElision(), CallOpts); 255 256 // FIXME: This definition of "copy elision has not failed" is unreliable. 257 // It doesn't indicate that the constructor will actually be inlined 258 // later; this is still up to evalCall() to decide. 259 if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) 260 return V; 261 262 // Copy elision failed. Revert the changes and proceed as if we have 263 // a simple temporary. 264 CallOpts = PreElideCallOpts; 265 CallOpts.IsElidableCtorThatHasNotBeenElided = true; 266 LLVM_FALLTHROUGH; 267 } 268 case ConstructionContext::SimpleTemporaryObjectKind: { 269 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 270 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); 271 272 CallOpts.IsTemporaryCtorOrDtor = true; 273 if (MTE) { 274 if (const ValueDecl *VD = MTE->getExtendingDecl()) { 275 assert(MTE->getStorageDuration() != SD_FullExpression); 276 if (!VD->getType()->isReferenceType()) { 277 // We're lifetime-extended by a surrounding aggregate. 278 // Automatic destructors aren't quite working in this case 279 // on the CFG side. We should warn the caller about that. 280 // FIXME: Is there a better way to retrieve this information from 281 // the MaterializeTemporaryExpr? 282 CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true; 283 } 284 } 285 286 if (MTE->getStorageDuration() == SD_Static || 287 MTE->getStorageDuration() == SD_Thread) 288 return loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E)); 289 } 290 291 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 292 } 293 case ConstructionContext::ArgumentKind: { 294 // Arguments are technically temporaries. 295 CallOpts.IsTemporaryCtorOrDtor = true; 296 297 const auto *ACC = cast<ArgumentConstructionContext>(CC); 298 const Expr *E = ACC->getCallLikeExpr(); 299 unsigned Idx = ACC->getIndex(); 300 301 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 302 auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> { 303 const LocationContext *FutureSFC = 304 Caller->getCalleeStackFrame(currBldrCtx->blockCount()); 305 // Return early if we are unable to reliably foresee 306 // the future stack frame. 307 if (!FutureSFC) 308 return None; 309 310 // This should be equivalent to Caller->getDecl() for now, but 311 // FutureSFC->getDecl() is likely to support better stuff (like 312 // virtual functions) earlier. 313 const Decl *CalleeD = FutureSFC->getDecl(); 314 315 // FIXME: Support for variadic arguments is not implemented here yet. 316 if (CallEvent::isVariadic(CalleeD)) 317 return None; 318 319 // Operator arguments do not correspond to operator parameters 320 // because this-argument is implemented as a normal argument in 321 // operator call expressions but not in operator declarations. 322 const TypedValueRegion *TVR = Caller->getParameterLocation( 323 *Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount()); 324 if (!TVR) 325 return None; 326 327 return loc::MemRegionVal(TVR); 328 }; 329 330 if (const auto *CE = dyn_cast<CallExpr>(E)) { 331 CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx); 332 if (Optional<SVal> V = getArgLoc(Caller)) 333 return *V; 334 else 335 break; 336 } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) { 337 // Don't bother figuring out the target region for the future 338 // constructor because we won't need it. 339 CallEventRef<> Caller = 340 CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx); 341 if (Optional<SVal> V = getArgLoc(Caller)) 342 return *V; 343 else 344 break; 345 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { 346 CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx); 347 if (Optional<SVal> V = getArgLoc(Caller)) 348 return *V; 349 else 350 break; 351 } 352 } 353 } // switch (CC->getKind()) 354 } 355 356 // If we couldn't find an existing region to construct into, assume we're 357 // constructing a temporary. Notify the caller of our failure. 358 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 359 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 360 } 361 362 ProgramStateRef ExprEngine::updateObjectsUnderConstruction( 363 SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 364 const ConstructionContext *CC, const EvalCallOptions &CallOpts) { 365 if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { 366 // Sounds like we failed to find the target region and therefore 367 // copy elision failed. There's nothing we can do about it here. 368 return State; 369 } 370 371 // See if we're constructing an existing region by looking at the 372 // current construction context. 373 assert(CC && "Computed target region without construction context?"); 374 switch (CC->getKind()) { 375 case ConstructionContext::CXX17ElidedCopyVariableKind: 376 case ConstructionContext::SimpleVariableKind: { 377 const auto *DSCC = cast<VariableConstructionContext>(CC); 378 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V); 379 } 380 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 381 case ConstructionContext::SimpleConstructorInitializerKind: { 382 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 383 const auto *Init = ICC->getCXXCtorInitializer(); 384 // Base and delegating initializers handled above 385 assert(Init->isAnyMemberInitializer() && 386 "Base and delegating initializers should have been handled by" 387 "computeObjectUnderConstruction()"); 388 return addObjectUnderConstruction(State, Init, LCtx, V); 389 } 390 case ConstructionContext::NewAllocatedObjectKind: { 391 return State; 392 } 393 case ConstructionContext::SimpleReturnedValueKind: 394 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 395 const StackFrameContext *SFC = LCtx->getStackFrame(); 396 const LocationContext *CallerLCtx = SFC->getParent(); 397 if (!CallerLCtx) { 398 // No extra work is necessary in top frame. 399 return State; 400 } 401 402 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 403 .getAs<CFGCXXRecordTypedCall>(); 404 assert(RTC && "Could not have had a target region without it"); 405 if (isa<BlockInvocationContext>(CallerLCtx)) { 406 // Unwrap block invocation contexts. They're mostly part of 407 // the current stack frame. 408 CallerLCtx = CallerLCtx->getParent(); 409 assert(!isa<BlockInvocationContext>(CallerLCtx)); 410 } 411 412 return updateObjectsUnderConstruction(V, 413 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 414 RTC->getConstructionContext(), CallOpts); 415 } 416 case ConstructionContext::ElidedTemporaryObjectKind: { 417 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); 418 if (!CallOpts.IsElidableCtorThatHasNotBeenElided) { 419 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 420 State = updateObjectsUnderConstruction( 421 V, TCC->getConstructorAfterElision(), State, LCtx, 422 TCC->getConstructionContextAfterElision(), CallOpts); 423 424 // Remember that we've elided the constructor. 425 State = addObjectUnderConstruction( 426 State, TCC->getConstructorAfterElision(), LCtx, V); 427 428 // Remember that we've elided the destructor. 429 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 430 State = elideDestructor(State, BTE, LCtx); 431 432 // Instead of materialization, shamelessly return 433 // the final object destination. 434 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 435 State = addObjectUnderConstruction(State, MTE, LCtx, V); 436 437 return State; 438 } 439 // If we decided not to elide the constructor, proceed as if 440 // it's a simple temporary. 441 LLVM_FALLTHROUGH; 442 } 443 case ConstructionContext::SimpleTemporaryObjectKind: { 444 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 445 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 446 State = addObjectUnderConstruction(State, BTE, LCtx, V); 447 448 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 449 State = addObjectUnderConstruction(State, MTE, LCtx, V); 450 451 return State; 452 } 453 case ConstructionContext::ArgumentKind: { 454 const auto *ACC = cast<ArgumentConstructionContext>(CC); 455 if (const auto *BTE = ACC->getCXXBindTemporaryExpr()) 456 State = addObjectUnderConstruction(State, BTE, LCtx, V); 457 458 return addObjectUnderConstruction( 459 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V); 460 } 461 } 462 llvm_unreachable("Unhandled construction context!"); 463 } 464 465 static ProgramStateRef 466 bindRequiredArrayElementToEnvironment(ProgramStateRef State, 467 const ArrayInitLoopExpr *AILE, 468 const LocationContext *LCtx, SVal Idx) { 469 // The ctor in this case is guaranteed to be a copy ctor, otherwise we hit a 470 // compile time error. 471 // 472 // -ArrayInitLoopExpr <-- we're here 473 // |-OpaqueValueExpr 474 // | `-DeclRefExpr <-- match this 475 // `-CXXConstructExpr 476 // `-ImplicitCastExpr 477 // `-ArraySubscriptExpr 478 // |-ImplicitCastExpr 479 // | `-OpaqueValueExpr 480 // | `-DeclRefExpr 481 // `-ArrayInitIndexExpr 482 // 483 // The resulting expression might look like the one below in an implicit 484 // copy/move ctor. 485 // 486 // ArrayInitLoopExpr <-- we're here 487 // |-OpaqueValueExpr 488 // | `-MemberExpr <-- match this 489 // | (`-CXXStaticCastExpr) <-- move ctor only 490 // | `-DeclRefExpr 491 // `-CXXConstructExpr 492 // `-ArraySubscriptExpr 493 // |-ImplicitCastExpr 494 // | `-OpaqueValueExpr 495 // | `-MemberExpr 496 // | `-DeclRefExpr 497 // `-ArrayInitIndexExpr 498 // 499 // HACK: There is no way we can put the index of the array element into the 500 // CFG unless we unroll the loop, so we manually select and bind the required 501 // parameter to the environment. 502 const auto *CE = cast<CXXConstructExpr>(AILE->getSubExpr()); 503 const auto *OVESrc = AILE->getCommonExpr()->getSourceExpr(); 504 505 SVal Base = UnknownVal(); 506 if (const auto *ME = dyn_cast<MemberExpr>(OVESrc)) 507 Base = State->getSVal(ME, LCtx); 508 else if (const auto *DRE = cast<DeclRefExpr>(OVESrc)) 509 Base = State->getLValue(cast<VarDecl>(DRE->getDecl()), LCtx); 510 else 511 llvm_unreachable("ArrayInitLoopExpr contains unexpected source expression"); 512 513 SVal NthElem = State->getLValue(CE->getType(), Idx, Base); 514 515 return State->BindExpr(CE->getArg(0), LCtx, NthElem); 516 } 517 518 void ExprEngine::handleConstructor(const Expr *E, 519 ExplodedNode *Pred, 520 ExplodedNodeSet &destNodes) { 521 const auto *CE = dyn_cast<CXXConstructExpr>(E); 522 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E); 523 assert(CE || CIE); 524 525 const LocationContext *LCtx = Pred->getLocationContext(); 526 ProgramStateRef State = Pred->getState(); 527 528 SVal Target = UnknownVal(); 529 530 if (CE) { 531 if (Optional<SVal> ElidedTarget = 532 getObjectUnderConstruction(State, CE, LCtx)) { 533 // We've previously modeled an elidable constructor by pretending that it 534 // in fact constructs into the correct target. This constructor can 535 // therefore be skipped. 536 Target = *ElidedTarget; 537 StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); 538 State = finishObjectConstruction(State, CE, LCtx); 539 if (auto L = Target.getAs<Loc>()) 540 State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); 541 Bldr.generateNode(CE, Pred, State); 542 return; 543 } 544 } 545 546 EvalCallOptions CallOpts; 547 auto C = getCurrentCFGElement().getAs<CFGConstructor>(); 548 assert(C || getCurrentCFGElement().getAs<CFGStmt>()); 549 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; 550 551 const CXXConstructExpr::ConstructionKind CK = 552 CE ? CE->getConstructionKind() : CIE->getConstructionKind(); 553 switch (CK) { 554 case CXXConstructExpr::CK_Complete: { 555 // Inherited constructors are always base class constructors. 556 assert(CE && !CIE && "A complete constructor is inherited?!"); 557 558 // If the ctor is part of an ArrayInitLoopExpr, we want to handle it 559 // differently. 560 auto *AILE = CC ? CC->getArrayInitLoop() : nullptr; 561 562 unsigned Idx = 0; 563 if (CE->getType()->isArrayType() || AILE) { 564 Idx = getIndexOfElementToConstruct(State, CE, LCtx).getValueOr(0u); 565 State = setIndexOfElementToConstruct(State, CE, LCtx, Idx + 1); 566 } 567 568 if (AILE) { 569 // Only set this once even though we loop through it multiple times. 570 if (!getPendingInitLoop(State, CE, LCtx)) 571 State = setPendingInitLoop(State, CE, LCtx, 572 AILE->getArraySize().getLimitedValue()); 573 574 State = bindRequiredArrayElementToEnvironment( 575 State, AILE, LCtx, svalBuilder.makeArrayIndex(Idx)); 576 } 577 578 // The target region is found from construction context. 579 std::tie(State, Target) = 580 handleConstructionContext(CE, State, LCtx, CC, CallOpts, Idx); 581 break; 582 } 583 case CXXConstructExpr::CK_VirtualBase: { 584 // Make sure we are not calling virtual base class initializers twice. 585 // Only the most-derived object should initialize virtual base classes. 586 const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>( 587 LCtx->getStackFrame()->getCallSite()); 588 assert( 589 (!OuterCtor || 590 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete || 591 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) && 592 ("This virtual base should have already been initialized by " 593 "the most derived class!")); 594 (void)OuterCtor; 595 LLVM_FALLTHROUGH; 596 } 597 case CXXConstructExpr::CK_NonVirtualBase: 598 // In C++17, classes with non-virtual bases may be aggregates, so they would 599 // be initialized as aggregates without a constructor call, so we may have 600 // a base class constructed directly into an initializer list without 601 // having the derived-class constructor call on the previous stack frame. 602 // Initializer lists may be nested into more initializer lists that 603 // correspond to surrounding aggregate initializations. 604 // FIXME: For now this code essentially bails out. We need to find the 605 // correct target region and set it. 606 // FIXME: Instead of relying on the ParentMap, we should have the 607 // trigger-statement (InitListExpr in this case) passed down from CFG or 608 // otherwise always available during construction. 609 if (isa_and_nonnull<InitListExpr>(LCtx->getParentMap().getParent(E))) { 610 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 611 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 612 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 613 break; 614 } 615 LLVM_FALLTHROUGH; 616 case CXXConstructExpr::CK_Delegating: { 617 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 618 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 619 LCtx->getStackFrame()); 620 SVal ThisVal = State->getSVal(ThisPtr); 621 622 if (CK == CXXConstructExpr::CK_Delegating) { 623 Target = ThisVal; 624 } else { 625 // Cast to the base type. 626 bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase); 627 SVal BaseVal = 628 getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual); 629 Target = BaseVal; 630 } 631 break; 632 } 633 } 634 635 if (State != Pred->getState()) { 636 static SimpleProgramPointTag T("ExprEngine", 637 "Prepare for object construction"); 638 ExplodedNodeSet DstPrepare; 639 StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx); 640 BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind); 641 assert(DstPrepare.size() <= 1); 642 if (DstPrepare.size() == 0) 643 return; 644 Pred = *BldrPrepare.begin(); 645 } 646 647 const MemRegion *TargetRegion = Target.getAsRegion(); 648 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 649 CallEventRef<> Call = 650 CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall( 651 CIE, TargetRegion, State, LCtx) 652 : (CallEventRef<>)CEMgr.getCXXConstructorCall( 653 CE, TargetRegion, State, LCtx); 654 655 ExplodedNodeSet DstPreVisit; 656 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this); 657 658 ExplodedNodeSet PreInitialized; 659 if (CE) { 660 // FIXME: Is it possible and/or useful to do this before PreStmt? 661 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx); 662 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(), 663 E = DstPreVisit.end(); 664 I != E; ++I) { 665 ProgramStateRef State = (*I)->getState(); 666 if (CE->requiresZeroInitialization()) { 667 // FIXME: Once we properly handle constructors in new-expressions, we'll 668 // need to invalidate the region before setting a default value, to make 669 // sure there aren't any lingering bindings around. This probably needs 670 // to happen regardless of whether or not the object is zero-initialized 671 // to handle random fields of a placement-initialized object picking up 672 // old bindings. We might only want to do it when we need to, though. 673 // FIXME: This isn't actually correct for arrays -- we need to zero- 674 // initialize the entire array, not just the first element -- but our 675 // handling of arrays everywhere else is weak as well, so this shouldn't 676 // actually make things worse. Placement new makes this tricky as well, 677 // since it's then possible to be initializing one part of a multi- 678 // dimensional array. 679 State = State->bindDefaultZero(Target, LCtx); 680 } 681 682 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr, 683 ProgramPoint::PreStmtKind); 684 } 685 } else { 686 PreInitialized = DstPreVisit; 687 } 688 689 ExplodedNodeSet DstPreCall; 690 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized, 691 *Call, *this); 692 693 ExplodedNodeSet DstEvaluated; 694 695 if (CE && CE->getConstructor()->isTrivial() && 696 CE->getConstructor()->isCopyOrMoveConstructor() && 697 !CallOpts.IsArrayCtorOrDtor) { 698 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 699 // FIXME: Handle other kinds of trivial constructors as well. 700 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 701 I != E; ++I) 702 performTrivialCopy(Bldr, *I, *Call); 703 704 } else { 705 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 706 I != E; ++I) 707 getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this, 708 CallOpts); 709 } 710 711 // If the CFG was constructed without elements for temporary destructors 712 // and the just-called constructor created a temporary object then 713 // stop exploration if the temporary object has a noreturn constructor. 714 // This can lose coverage because the destructor, if it were present 715 // in the CFG, would be called at the end of the full expression or 716 // later (for life-time extended temporaries) -- but avoids infeasible 717 // paths when no-return temporary destructors are used for assertions. 718 ExplodedNodeSet DstEvaluatedPostProcessed; 719 StmtNodeBuilder Bldr(DstEvaluated, DstEvaluatedPostProcessed, *currBldrCtx); 720 const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext(); 721 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { 722 if (llvm::isa_and_nonnull<CXXTempObjectRegion>(TargetRegion) && 723 cast<CXXConstructorDecl>(Call->getDecl()) 724 ->getParent() 725 ->isAnyDestructorNoReturn()) { 726 727 // If we've inlined the constructor, then DstEvaluated would be empty. 728 // In this case we still want a sink, which could be implemented 729 // in processCallExit. But we don't have that implemented at the moment, 730 // so if you hit this assertion, see if you can avoid inlining 731 // the respective constructor when analyzer-config cfg-temporary-dtors 732 // is set to false. 733 // Otherwise there's nothing wrong with inlining such constructor. 734 assert(!DstEvaluated.empty() && 735 "We should not have inlined this constructor!"); 736 737 for (ExplodedNode *N : DstEvaluated) { 738 Bldr.generateSink(E, N, N->getState()); 739 } 740 741 // There is no need to run the PostCall and PostStmt checker 742 // callbacks because we just generated sinks on all nodes in th 743 // frontier. 744 return; 745 } 746 } 747 748 ExplodedNodeSet DstPostArgumentCleanup; 749 for (ExplodedNode *I : DstEvaluatedPostProcessed) 750 finishArgumentConstruction(DstPostArgumentCleanup, I, *Call); 751 752 // If there were other constructors called for object-type arguments 753 // of this constructor, clean them up. 754 ExplodedNodeSet DstPostCall; 755 getCheckerManager().runCheckersForPostCall(DstPostCall, 756 DstPostArgumentCleanup, 757 *Call, *this); 758 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this); 759 } 760 761 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 762 ExplodedNode *Pred, 763 ExplodedNodeSet &Dst) { 764 handleConstructor(CE, Pred, Dst); 765 } 766 767 void ExprEngine::VisitCXXInheritedCtorInitExpr( 768 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred, 769 ExplodedNodeSet &Dst) { 770 handleConstructor(CE, Pred, Dst); 771 } 772 773 void ExprEngine::VisitCXXDestructor(QualType ObjectType, 774 const MemRegion *Dest, 775 const Stmt *S, 776 bool IsBaseDtor, 777 ExplodedNode *Pred, 778 ExplodedNodeSet &Dst, 779 EvalCallOptions &CallOpts) { 780 assert(S && "A destructor without a trigger!"); 781 const LocationContext *LCtx = Pred->getLocationContext(); 782 ProgramStateRef State = Pred->getState(); 783 784 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 785 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 786 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 787 // FIXME: There should always be a Decl, otherwise the destructor call 788 // shouldn't have been added to the CFG in the first place. 789 if (!DtorDecl) { 790 // Skip the invalid destructor. We cannot simply return because 791 // it would interrupt the analysis instead. 792 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 793 // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway. 794 PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T); 795 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 796 Bldr.generateNode(PP, Pred->getState(), Pred); 797 return; 798 } 799 800 if (!Dest) { 801 // We're trying to destroy something that is not a region. This may happen 802 // for a variety of reasons (unknown target region, concrete integer instead 803 // of target region, etc.). The current code makes an attempt to recover. 804 // FIXME: We probably don't really need to recover when we're dealing 805 // with concrete integers specifically. 806 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 807 if (const Expr *E = dyn_cast_or_null<Expr>(S)) { 808 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext()); 809 } else { 810 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 811 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 812 Bldr.generateSink(Pred->getLocation().withTag(&T), 813 Pred->getState(), Pred); 814 return; 815 } 816 } 817 818 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 819 CallEventRef<CXXDestructorCall> Call = 820 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 821 822 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 823 Call->getSourceRange().getBegin(), 824 "Error evaluating destructor"); 825 826 ExplodedNodeSet DstPreCall; 827 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 828 *Call, *this); 829 830 ExplodedNodeSet DstInvalidated; 831 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 832 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 833 I != E; ++I) 834 defaultEvalCall(Bldr, *I, *Call, CallOpts); 835 836 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 837 *Call, *this); 838 } 839 840 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 841 ExplodedNode *Pred, 842 ExplodedNodeSet &Dst) { 843 ProgramStateRef State = Pred->getState(); 844 const LocationContext *LCtx = Pred->getLocationContext(); 845 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 846 CNE->getBeginLoc(), 847 "Error evaluating New Allocator Call"); 848 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 849 CallEventRef<CXXAllocatorCall> Call = 850 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 851 852 ExplodedNodeSet DstPreCall; 853 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 854 *Call, *this); 855 856 ExplodedNodeSet DstPostCall; 857 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx); 858 for (ExplodedNode *I : DstPreCall) { 859 // FIXME: Provide evalCall for checkers? 860 defaultEvalCall(CallBldr, I, *Call); 861 } 862 // If the call is inlined, DstPostCall will be empty and we bail out now. 863 864 // Store return value of operator new() for future use, until the actual 865 // CXXNewExpr gets processed. 866 ExplodedNodeSet DstPostValue; 867 StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx); 868 for (ExplodedNode *I : DstPostCall) { 869 // FIXME: Because CNE serves as the "call site" for the allocator (due to 870 // lack of a better expression in the AST), the conjured return value symbol 871 // is going to be of the same type (C++ object pointer type). Technically 872 // this is not correct because the operator new's prototype always says that 873 // it returns a 'void *'. So we should change the type of the symbol, 874 // and then evaluate the cast over the symbolic pointer from 'void *' to 875 // the object pointer type. But without changing the symbol's type it 876 // is breaking too much to evaluate the no-op symbolic cast over it, so we 877 // skip it for now. 878 ProgramStateRef State = I->getState(); 879 SVal RetVal = State->getSVal(CNE, LCtx); 880 881 // If this allocation function is not declared as non-throwing, failures 882 // /must/ be signalled by exceptions, and thus the return value will never 883 // be NULL. -fno-exceptions does not influence this semantics. 884 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 885 // where new can return NULL. If we end up supporting that option, we can 886 // consider adding a check for it here. 887 // C++11 [basic.stc.dynamic.allocation]p3. 888 if (const FunctionDecl *FD = CNE->getOperatorNew()) { 889 QualType Ty = FD->getType(); 890 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 891 if (!ProtoType->isNothrow()) 892 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true); 893 } 894 895 ValueBldr.generateNode( 896 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal)); 897 } 898 899 ExplodedNodeSet DstPostPostCallCallback; 900 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback, 901 DstPostValue, *Call, *this); 902 for (ExplodedNode *I : DstPostPostCallCallback) { 903 getCheckerManager().runCheckersForNewAllocator(*Call, Dst, I, *this); 904 } 905 } 906 907 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 908 ExplodedNodeSet &Dst) { 909 // FIXME: Much of this should eventually migrate to CXXAllocatorCall. 910 // Also, we need to decide how allocators actually work -- they're not 911 // really part of the CXXNewExpr because they happen BEFORE the 912 // CXXConstructExpr subexpression. See PR12014 for some discussion. 913 914 unsigned blockCount = currBldrCtx->blockCount(); 915 const LocationContext *LCtx = Pred->getLocationContext(); 916 SVal symVal = UnknownVal(); 917 FunctionDecl *FD = CNE->getOperatorNew(); 918 919 bool IsStandardGlobalOpNewFunction = 920 FD->isReplaceableGlobalAllocationFunction(); 921 922 ProgramStateRef State = Pred->getState(); 923 924 // Retrieve the stored operator new() return value. 925 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 926 symVal = *getObjectUnderConstruction(State, CNE, LCtx); 927 State = finishObjectConstruction(State, CNE, LCtx); 928 } 929 930 // We assume all standard global 'operator new' functions allocate memory in 931 // heap. We realize this is an approximation that might not correctly model 932 // a custom global allocator. 933 if (symVal.isUnknown()) { 934 if (IsStandardGlobalOpNewFunction) 935 symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount); 936 else 937 symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(), 938 blockCount); 939 } 940 941 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 942 CallEventRef<CXXAllocatorCall> Call = 943 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 944 945 if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 946 // Invalidate placement args. 947 // FIXME: Once we figure out how we want allocators to work, 948 // we should be using the usual pre-/(default-)eval-/post-call checkers 949 // here. 950 State = Call->invalidateRegions(blockCount); 951 if (!State) 952 return; 953 954 // If this allocation function is not declared as non-throwing, failures 955 // /must/ be signalled by exceptions, and thus the return value will never 956 // be NULL. -fno-exceptions does not influence this semantics. 957 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 958 // where new can return NULL. If we end up supporting that option, we can 959 // consider adding a check for it here. 960 // C++11 [basic.stc.dynamic.allocation]p3. 961 if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>()) 962 if (!ProtoType->isNothrow()) 963 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>()) 964 State = State->assume(*dSymVal, true); 965 } 966 967 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 968 969 SVal Result = symVal; 970 971 if (CNE->isArray()) { 972 973 if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) { 974 // If each element is initialized by their default constructor, the field 975 // values are properly placed inside the required region, however if an 976 // initializer list is used, this doesn't happen automatically. 977 auto *Init = CNE->getInitializer(); 978 bool isInitList = isa_and_nonnull<InitListExpr>(Init); 979 980 QualType ObjTy = 981 isInitList ? Init->getType() : CNE->getType()->getPointeeType(); 982 const ElementRegion *EleReg = 983 MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg, 984 svalBuilder.getContext()); 985 Result = loc::MemRegionVal(EleReg); 986 987 // If the array is list initialized, we bind the initializer list to the 988 // memory region here, otherwise we would lose it. 989 if (isInitList) { 990 Bldr.takeNodes(Pred); 991 Pred = Bldr.generateNode(CNE, Pred, State); 992 993 SVal V = State->getSVal(Init, LCtx); 994 ExplodedNodeSet evaluated; 995 evalBind(evaluated, CNE, Pred, Result, V, true); 996 997 Bldr.takeNodes(Pred); 998 Bldr.addNodes(evaluated); 999 1000 Pred = *evaluated.begin(); 1001 State = Pred->getState(); 1002 } 1003 } 1004 1005 State = State->BindExpr(CNE, Pred->getLocationContext(), Result); 1006 Bldr.generateNode(CNE, Pred, State); 1007 return; 1008 } 1009 1010 // FIXME: Once we have proper support for CXXConstructExprs inside 1011 // CXXNewExpr, we need to make sure that the constructed object is not 1012 // immediately invalidated here. (The placement call should happen before 1013 // the constructor call anyway.) 1014 if (FD->isReservedGlobalPlacementOperator()) { 1015 // Non-array placement new should always return the placement location. 1016 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx); 1017 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(), 1018 CNE->getPlacementArg(0)->getType()); 1019 } 1020 1021 // Bind the address of the object, then check to see if we cached out. 1022 State = State->BindExpr(CNE, LCtx, Result); 1023 ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State); 1024 if (!NewN) 1025 return; 1026 1027 // If the type is not a record, we won't have a CXXConstructExpr as an 1028 // initializer. Copy the value over. 1029 if (const Expr *Init = CNE->getInitializer()) { 1030 if (!isa<CXXConstructExpr>(Init)) { 1031 assert(Bldr.getResults().size() == 1); 1032 Bldr.takeNodes(NewN); 1033 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx), 1034 /*FirstInit=*/IsStandardGlobalOpNewFunction); 1035 } 1036 } 1037 } 1038 1039 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 1040 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1041 1042 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 1043 CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall( 1044 CDE, Pred->getState(), Pred->getLocationContext()); 1045 1046 ExplodedNodeSet DstPreCall; 1047 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this); 1048 ExplodedNodeSet DstPostCall; 1049 1050 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 1051 StmtNodeBuilder Bldr(DstPreCall, DstPostCall, *currBldrCtx); 1052 for (ExplodedNode *I : DstPreCall) { 1053 defaultEvalCall(Bldr, I, *Call); 1054 } 1055 } else { 1056 DstPostCall = DstPreCall; 1057 } 1058 getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this); 1059 } 1060 1061 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 1062 ExplodedNodeSet &Dst) { 1063 const VarDecl *VD = CS->getExceptionDecl(); 1064 if (!VD) { 1065 Dst.Add(Pred); 1066 return; 1067 } 1068 1069 const LocationContext *LCtx = Pred->getLocationContext(); 1070 SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(), 1071 currBldrCtx->blockCount()); 1072 ProgramStateRef state = Pred->getState(); 1073 state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx); 1074 1075 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1076 Bldr.generateNode(CS, Pred, state); 1077 } 1078 1079 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 1080 ExplodedNodeSet &Dst) { 1081 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1082 1083 // Get the this object region from StoreManager. 1084 const LocationContext *LCtx = Pred->getLocationContext(); 1085 const MemRegion *R = 1086 svalBuilder.getRegionManager().getCXXThisRegion( 1087 getContext().getCanonicalType(TE->getType()), 1088 LCtx); 1089 1090 ProgramStateRef state = Pred->getState(); 1091 SVal V = state->getSVal(loc::MemRegionVal(R)); 1092 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V)); 1093 } 1094 1095 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 1096 ExplodedNodeSet &Dst) { 1097 const LocationContext *LocCtxt = Pred->getLocationContext(); 1098 1099 // Get the region of the lambda itself. 1100 const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion( 1101 LE, LocCtxt); 1102 SVal V = loc::MemRegionVal(R); 1103 1104 ProgramStateRef State = Pred->getState(); 1105 1106 // If we created a new MemRegion for the lambda, we should explicitly bind 1107 // the captures. 1108 CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin(); 1109 for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(), 1110 e = LE->capture_init_end(); 1111 i != e; ++i, ++CurField) { 1112 FieldDecl *FieldForCapture = *CurField; 1113 SVal FieldLoc = State->getLValue(FieldForCapture, V); 1114 1115 SVal InitVal; 1116 if (!FieldForCapture->hasCapturedVLAType()) { 1117 Expr *InitExpr = *i; 1118 assert(InitExpr && "Capture missing initialization expression"); 1119 InitVal = State->getSVal(InitExpr, LocCtxt); 1120 } else { 1121 // The field stores the length of a captured variable-length array. 1122 // These captures don't have initialization expressions; instead we 1123 // get the length from the VLAType size expression. 1124 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr(); 1125 InitVal = State->getSVal(SizeExpr, LocCtxt); 1126 } 1127 1128 State = State->bindLoc(FieldLoc, InitVal, LocCtxt); 1129 } 1130 1131 // Decay the Loc into an RValue, because there might be a 1132 // MaterializeTemporaryExpr node above this one which expects the bound value 1133 // to be an RValue. 1134 SVal LambdaRVal = State->getSVal(R); 1135 1136 ExplodedNodeSet Tmp; 1137 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 1138 // FIXME: is this the right program point kind? 1139 Bldr.generateNode(LE, Pred, 1140 State->BindExpr(LE, LocCtxt, LambdaRVal), 1141 nullptr, ProgramPoint::PostLValueKind); 1142 1143 // FIXME: Move all post/pre visits to ::Visit(). 1144 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this); 1145 } 1146