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 [[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::LambdaCaptureKind: { 294 CallOpts.IsTemporaryCtorOrDtor = true; 295 296 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC); 297 298 SVal Base = loc::MemRegionVal( 299 MRMgr.getCXXTempObjectRegion(LCC->getInitializer(), LCtx)); 300 301 const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E); 302 if (getIndexOfElementToConstruct(State, CE, LCtx)) { 303 CallOpts.IsArrayCtorOrDtor = true; 304 Base = State->getLValue(E->getType(), svalBuilder.makeArrayIndex(Idx), 305 Base); 306 } 307 308 return Base; 309 } 310 case ConstructionContext::ArgumentKind: { 311 // Arguments are technically temporaries. 312 CallOpts.IsTemporaryCtorOrDtor = true; 313 314 const auto *ACC = cast<ArgumentConstructionContext>(CC); 315 const Expr *E = ACC->getCallLikeExpr(); 316 unsigned Idx = ACC->getIndex(); 317 318 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 319 auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> { 320 const LocationContext *FutureSFC = 321 Caller->getCalleeStackFrame(currBldrCtx->blockCount()); 322 // Return early if we are unable to reliably foresee 323 // the future stack frame. 324 if (!FutureSFC) 325 return None; 326 327 // This should be equivalent to Caller->getDecl() for now, but 328 // FutureSFC->getDecl() is likely to support better stuff (like 329 // virtual functions) earlier. 330 const Decl *CalleeD = FutureSFC->getDecl(); 331 332 // FIXME: Support for variadic arguments is not implemented here yet. 333 if (CallEvent::isVariadic(CalleeD)) 334 return None; 335 336 // Operator arguments do not correspond to operator parameters 337 // because this-argument is implemented as a normal argument in 338 // operator call expressions but not in operator declarations. 339 const TypedValueRegion *TVR = Caller->getParameterLocation( 340 *Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount()); 341 if (!TVR) 342 return None; 343 344 return loc::MemRegionVal(TVR); 345 }; 346 347 if (const auto *CE = dyn_cast<CallExpr>(E)) { 348 CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx); 349 if (Optional<SVal> V = getArgLoc(Caller)) 350 return *V; 351 else 352 break; 353 } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) { 354 // Don't bother figuring out the target region for the future 355 // constructor because we won't need it. 356 CallEventRef<> Caller = 357 CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx); 358 if (Optional<SVal> V = getArgLoc(Caller)) 359 return *V; 360 else 361 break; 362 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { 363 CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx); 364 if (Optional<SVal> V = getArgLoc(Caller)) 365 return *V; 366 else 367 break; 368 } 369 } 370 } // switch (CC->getKind()) 371 } 372 373 // If we couldn't find an existing region to construct into, assume we're 374 // constructing a temporary. Notify the caller of our failure. 375 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 376 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 377 } 378 379 ProgramStateRef ExprEngine::updateObjectsUnderConstruction( 380 SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 381 const ConstructionContext *CC, const EvalCallOptions &CallOpts) { 382 if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { 383 // Sounds like we failed to find the target region and therefore 384 // copy elision failed. There's nothing we can do about it here. 385 return State; 386 } 387 388 // See if we're constructing an existing region by looking at the 389 // current construction context. 390 assert(CC && "Computed target region without construction context?"); 391 switch (CC->getKind()) { 392 case ConstructionContext::CXX17ElidedCopyVariableKind: 393 case ConstructionContext::SimpleVariableKind: { 394 const auto *DSCC = cast<VariableConstructionContext>(CC); 395 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V); 396 } 397 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 398 case ConstructionContext::SimpleConstructorInitializerKind: { 399 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 400 const auto *Init = ICC->getCXXCtorInitializer(); 401 // Base and delegating initializers handled above 402 assert(Init->isAnyMemberInitializer() && 403 "Base and delegating initializers should have been handled by" 404 "computeObjectUnderConstruction()"); 405 return addObjectUnderConstruction(State, Init, LCtx, V); 406 } 407 case ConstructionContext::NewAllocatedObjectKind: { 408 return State; 409 } 410 case ConstructionContext::SimpleReturnedValueKind: 411 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 412 const StackFrameContext *SFC = LCtx->getStackFrame(); 413 const LocationContext *CallerLCtx = SFC->getParent(); 414 if (!CallerLCtx) { 415 // No extra work is necessary in top frame. 416 return State; 417 } 418 419 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 420 .getAs<CFGCXXRecordTypedCall>(); 421 assert(RTC && "Could not have had a target region without it"); 422 if (isa<BlockInvocationContext>(CallerLCtx)) { 423 // Unwrap block invocation contexts. They're mostly part of 424 // the current stack frame. 425 CallerLCtx = CallerLCtx->getParent(); 426 assert(!isa<BlockInvocationContext>(CallerLCtx)); 427 } 428 429 return updateObjectsUnderConstruction(V, 430 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 431 RTC->getConstructionContext(), CallOpts); 432 } 433 case ConstructionContext::ElidedTemporaryObjectKind: { 434 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); 435 if (!CallOpts.IsElidableCtorThatHasNotBeenElided) { 436 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 437 State = updateObjectsUnderConstruction( 438 V, TCC->getConstructorAfterElision(), State, LCtx, 439 TCC->getConstructionContextAfterElision(), CallOpts); 440 441 // Remember that we've elided the constructor. 442 State = addObjectUnderConstruction( 443 State, TCC->getConstructorAfterElision(), LCtx, V); 444 445 // Remember that we've elided the destructor. 446 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 447 State = elideDestructor(State, BTE, LCtx); 448 449 // Instead of materialization, shamelessly return 450 // the final object destination. 451 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 452 State = addObjectUnderConstruction(State, MTE, LCtx, V); 453 454 return State; 455 } 456 // If we decided not to elide the constructor, proceed as if 457 // it's a simple temporary. 458 [[fallthrough]]; 459 } 460 case ConstructionContext::SimpleTemporaryObjectKind: { 461 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 462 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 463 State = addObjectUnderConstruction(State, BTE, LCtx, V); 464 465 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 466 State = addObjectUnderConstruction(State, MTE, LCtx, V); 467 468 return State; 469 } 470 case ConstructionContext::LambdaCaptureKind: { 471 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC); 472 473 // If we capture and array, we want to store the super region, not a 474 // sub-region. 475 if (const auto *EL = dyn_cast_or_null<ElementRegion>(V.getAsRegion())) 476 V = loc::MemRegionVal(EL->getSuperRegion()); 477 478 return addObjectUnderConstruction( 479 State, {LCC->getLambdaExpr(), LCC->getIndex()}, LCtx, V); 480 } 481 case ConstructionContext::ArgumentKind: { 482 const auto *ACC = cast<ArgumentConstructionContext>(CC); 483 if (const auto *BTE = ACC->getCXXBindTemporaryExpr()) 484 State = addObjectUnderConstruction(State, BTE, LCtx, V); 485 486 return addObjectUnderConstruction( 487 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V); 488 } 489 } 490 llvm_unreachable("Unhandled construction context!"); 491 } 492 493 static ProgramStateRef 494 bindRequiredArrayElementToEnvironment(ProgramStateRef State, 495 const ArrayInitLoopExpr *AILE, 496 const LocationContext *LCtx, SVal Idx) { 497 // The ctor in this case is guaranteed to be a copy ctor, otherwise we hit a 498 // compile time error. 499 // 500 // -ArrayInitLoopExpr <-- we're here 501 // |-OpaqueValueExpr 502 // | `-DeclRefExpr <-- match this 503 // `-CXXConstructExpr 504 // `-ImplicitCastExpr 505 // `-ArraySubscriptExpr 506 // |-ImplicitCastExpr 507 // | `-OpaqueValueExpr 508 // | `-DeclRefExpr 509 // `-ArrayInitIndexExpr 510 // 511 // The resulting expression might look like the one below in an implicit 512 // copy/move ctor. 513 // 514 // ArrayInitLoopExpr <-- we're here 515 // |-OpaqueValueExpr 516 // | `-MemberExpr <-- match this 517 // | (`-CXXStaticCastExpr) <-- move ctor only 518 // | `-DeclRefExpr 519 // `-CXXConstructExpr 520 // `-ArraySubscriptExpr 521 // |-ImplicitCastExpr 522 // | `-OpaqueValueExpr 523 // | `-MemberExpr 524 // | `-DeclRefExpr 525 // `-ArrayInitIndexExpr 526 // 527 // The resulting expression for a multidimensional array. 528 // ArrayInitLoopExpr <-- we're here 529 // |-OpaqueValueExpr 530 // | `-DeclRefExpr <-- match this 531 // `-ArrayInitLoopExpr 532 // |-OpaqueValueExpr 533 // | `-ArraySubscriptExpr 534 // | |-ImplicitCastExpr 535 // | | `-OpaqueValueExpr 536 // | | `-DeclRefExpr 537 // | `-ArrayInitIndexExpr 538 // `-CXXConstructExpr <-- extract this 539 // ` ... 540 541 const auto *OVESrc = AILE->getCommonExpr()->getSourceExpr(); 542 543 // HACK: There is no way we can put the index of the array element into the 544 // CFG unless we unroll the loop, so we manually select and bind the required 545 // parameter to the environment. 546 const auto *CE = 547 cast<CXXConstructExpr>(extractElementInitializerFromNestedAILE(AILE)); 548 549 SVal Base = UnknownVal(); 550 if (const auto *ME = dyn_cast<MemberExpr>(OVESrc)) 551 Base = State->getSVal(ME, LCtx); 552 else if (const auto *DRE = dyn_cast<DeclRefExpr>(OVESrc)) 553 Base = State->getLValue(cast<VarDecl>(DRE->getDecl()), LCtx); 554 else 555 llvm_unreachable("ArrayInitLoopExpr contains unexpected source expression"); 556 557 SVal NthElem = State->getLValue(CE->getType(), Idx, Base); 558 559 return State->BindExpr(CE->getArg(0), LCtx, NthElem); 560 } 561 562 void ExprEngine::handleConstructor(const Expr *E, 563 ExplodedNode *Pred, 564 ExplodedNodeSet &destNodes) { 565 const auto *CE = dyn_cast<CXXConstructExpr>(E); 566 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E); 567 assert(CE || CIE); 568 569 const LocationContext *LCtx = Pred->getLocationContext(); 570 ProgramStateRef State = Pred->getState(); 571 572 SVal Target = UnknownVal(); 573 574 if (CE) { 575 if (Optional<SVal> ElidedTarget = 576 getObjectUnderConstruction(State, CE, LCtx)) { 577 // We've previously modeled an elidable constructor by pretending that it 578 // in fact constructs into the correct target. This constructor can 579 // therefore be skipped. 580 Target = *ElidedTarget; 581 StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); 582 State = finishObjectConstruction(State, CE, LCtx); 583 if (auto L = Target.getAs<Loc>()) 584 State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); 585 Bldr.generateNode(CE, Pred, State); 586 return; 587 } 588 } 589 590 EvalCallOptions CallOpts; 591 auto C = getCurrentCFGElement().getAs<CFGConstructor>(); 592 assert(C || getCurrentCFGElement().getAs<CFGStmt>()); 593 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; 594 595 const CXXConstructExpr::ConstructionKind CK = 596 CE ? CE->getConstructionKind() : CIE->getConstructionKind(); 597 switch (CK) { 598 case CXXConstructExpr::CK_Complete: { 599 // Inherited constructors are always base class constructors. 600 assert(CE && !CIE && "A complete constructor is inherited?!"); 601 602 // If the ctor is part of an ArrayInitLoopExpr, we want to handle it 603 // differently. 604 auto *AILE = CC ? CC->getArrayInitLoop() : nullptr; 605 606 unsigned Idx = 0; 607 if (CE->getType()->isArrayType() || AILE) { 608 Idx = getIndexOfElementToConstruct(State, CE, LCtx).value_or(0u); 609 State = setIndexOfElementToConstruct(State, CE, LCtx, Idx + 1); 610 } 611 612 if (AILE) { 613 // Only set this once even though we loop through it multiple times. 614 if (!getPendingInitLoop(State, CE, LCtx)) 615 State = setPendingInitLoop( 616 State, CE, LCtx, 617 getContext().getArrayInitLoopExprElementCount(AILE)); 618 619 State = bindRequiredArrayElementToEnvironment( 620 State, AILE, LCtx, svalBuilder.makeArrayIndex(Idx)); 621 } 622 623 // The target region is found from construction context. 624 std::tie(State, Target) = 625 handleConstructionContext(CE, State, LCtx, CC, CallOpts, Idx); 626 break; 627 } 628 case CXXConstructExpr::CK_VirtualBase: { 629 // Make sure we are not calling virtual base class initializers twice. 630 // Only the most-derived object should initialize virtual base classes. 631 const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>( 632 LCtx->getStackFrame()->getCallSite()); 633 assert( 634 (!OuterCtor || 635 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete || 636 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) && 637 ("This virtual base should have already been initialized by " 638 "the most derived class!")); 639 (void)OuterCtor; 640 [[fallthrough]]; 641 } 642 case CXXConstructExpr::CK_NonVirtualBase: 643 // In C++17, classes with non-virtual bases may be aggregates, so they would 644 // be initialized as aggregates without a constructor call, so we may have 645 // a base class constructed directly into an initializer list without 646 // having the derived-class constructor call on the previous stack frame. 647 // Initializer lists may be nested into more initializer lists that 648 // correspond to surrounding aggregate initializations. 649 // FIXME: For now this code essentially bails out. We need to find the 650 // correct target region and set it. 651 // FIXME: Instead of relying on the ParentMap, we should have the 652 // trigger-statement (InitListExpr in this case) passed down from CFG or 653 // otherwise always available during construction. 654 if (isa_and_nonnull<InitListExpr>(LCtx->getParentMap().getParent(E))) { 655 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 656 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 657 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 658 break; 659 } 660 [[fallthrough]]; 661 case CXXConstructExpr::CK_Delegating: { 662 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 663 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 664 LCtx->getStackFrame()); 665 SVal ThisVal = State->getSVal(ThisPtr); 666 667 if (CK == CXXConstructExpr::CK_Delegating) { 668 Target = ThisVal; 669 } else { 670 // Cast to the base type. 671 bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase); 672 SVal BaseVal = 673 getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual); 674 Target = BaseVal; 675 } 676 break; 677 } 678 } 679 680 if (State != Pred->getState()) { 681 static SimpleProgramPointTag T("ExprEngine", 682 "Prepare for object construction"); 683 ExplodedNodeSet DstPrepare; 684 StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx); 685 BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind); 686 assert(DstPrepare.size() <= 1); 687 if (DstPrepare.size() == 0) 688 return; 689 Pred = *BldrPrepare.begin(); 690 } 691 692 const MemRegion *TargetRegion = Target.getAsRegion(); 693 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 694 CallEventRef<> Call = 695 CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall( 696 CIE, TargetRegion, State, LCtx) 697 : (CallEventRef<>)CEMgr.getCXXConstructorCall( 698 CE, TargetRegion, State, LCtx); 699 700 ExplodedNodeSet DstPreVisit; 701 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this); 702 703 ExplodedNodeSet PreInitialized; 704 if (CE) { 705 // FIXME: Is it possible and/or useful to do this before PreStmt? 706 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx); 707 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(), 708 E = DstPreVisit.end(); 709 I != E; ++I) { 710 ProgramStateRef State = (*I)->getState(); 711 if (CE->requiresZeroInitialization()) { 712 // FIXME: Once we properly handle constructors in new-expressions, we'll 713 // need to invalidate the region before setting a default value, to make 714 // sure there aren't any lingering bindings around. This probably needs 715 // to happen regardless of whether or not the object is zero-initialized 716 // to handle random fields of a placement-initialized object picking up 717 // old bindings. We might only want to do it when we need to, though. 718 // FIXME: This isn't actually correct for arrays -- we need to zero- 719 // initialize the entire array, not just the first element -- but our 720 // handling of arrays everywhere else is weak as well, so this shouldn't 721 // actually make things worse. Placement new makes this tricky as well, 722 // since it's then possible to be initializing one part of a multi- 723 // dimensional array. 724 State = State->bindDefaultZero(Target, LCtx); 725 } 726 727 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr, 728 ProgramPoint::PreStmtKind); 729 } 730 } else { 731 PreInitialized = DstPreVisit; 732 } 733 734 ExplodedNodeSet DstPreCall; 735 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized, 736 *Call, *this); 737 738 ExplodedNodeSet DstEvaluated; 739 740 if (CE && CE->getConstructor()->isTrivial() && 741 CE->getConstructor()->isCopyOrMoveConstructor() && 742 !CallOpts.IsArrayCtorOrDtor) { 743 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 744 // FIXME: Handle other kinds of trivial constructors as well. 745 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 746 I != E; ++I) 747 performTrivialCopy(Bldr, *I, *Call); 748 749 } else { 750 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 751 I != E; ++I) 752 getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this, 753 CallOpts); 754 } 755 756 // If the CFG was constructed without elements for temporary destructors 757 // and the just-called constructor created a temporary object then 758 // stop exploration if the temporary object has a noreturn constructor. 759 // This can lose coverage because the destructor, if it were present 760 // in the CFG, would be called at the end of the full expression or 761 // later (for life-time extended temporaries) -- but avoids infeasible 762 // paths when no-return temporary destructors are used for assertions. 763 ExplodedNodeSet DstEvaluatedPostProcessed; 764 StmtNodeBuilder Bldr(DstEvaluated, DstEvaluatedPostProcessed, *currBldrCtx); 765 const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext(); 766 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { 767 if (llvm::isa_and_nonnull<CXXTempObjectRegion>(TargetRegion) && 768 cast<CXXConstructorDecl>(Call->getDecl()) 769 ->getParent() 770 ->isAnyDestructorNoReturn()) { 771 772 // If we've inlined the constructor, then DstEvaluated would be empty. 773 // In this case we still want a sink, which could be implemented 774 // in processCallExit. But we don't have that implemented at the moment, 775 // so if you hit this assertion, see if you can avoid inlining 776 // the respective constructor when analyzer-config cfg-temporary-dtors 777 // is set to false. 778 // Otherwise there's nothing wrong with inlining such constructor. 779 assert(!DstEvaluated.empty() && 780 "We should not have inlined this constructor!"); 781 782 for (ExplodedNode *N : DstEvaluated) { 783 Bldr.generateSink(E, N, N->getState()); 784 } 785 786 // There is no need to run the PostCall and PostStmt checker 787 // callbacks because we just generated sinks on all nodes in th 788 // frontier. 789 return; 790 } 791 } 792 793 ExplodedNodeSet DstPostArgumentCleanup; 794 for (ExplodedNode *I : DstEvaluatedPostProcessed) 795 finishArgumentConstruction(DstPostArgumentCleanup, I, *Call); 796 797 // If there were other constructors called for object-type arguments 798 // of this constructor, clean them up. 799 ExplodedNodeSet DstPostCall; 800 getCheckerManager().runCheckersForPostCall(DstPostCall, 801 DstPostArgumentCleanup, 802 *Call, *this); 803 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this); 804 } 805 806 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 807 ExplodedNode *Pred, 808 ExplodedNodeSet &Dst) { 809 handleConstructor(CE, Pred, Dst); 810 } 811 812 void ExprEngine::VisitCXXInheritedCtorInitExpr( 813 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred, 814 ExplodedNodeSet &Dst) { 815 handleConstructor(CE, Pred, Dst); 816 } 817 818 void ExprEngine::VisitCXXDestructor(QualType ObjectType, 819 const MemRegion *Dest, 820 const Stmt *S, 821 bool IsBaseDtor, 822 ExplodedNode *Pred, 823 ExplodedNodeSet &Dst, 824 EvalCallOptions &CallOpts) { 825 assert(S && "A destructor without a trigger!"); 826 const LocationContext *LCtx = Pred->getLocationContext(); 827 ProgramStateRef State = Pred->getState(); 828 829 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 830 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 831 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 832 // FIXME: There should always be a Decl, otherwise the destructor call 833 // shouldn't have been added to the CFG in the first place. 834 if (!DtorDecl) { 835 // Skip the invalid destructor. We cannot simply return because 836 // it would interrupt the analysis instead. 837 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 838 // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway. 839 PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T); 840 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 841 Bldr.generateNode(PP, Pred->getState(), Pred); 842 return; 843 } 844 845 if (!Dest) { 846 // We're trying to destroy something that is not a region. This may happen 847 // for a variety of reasons (unknown target region, concrete integer instead 848 // of target region, etc.). The current code makes an attempt to recover. 849 // FIXME: We probably don't really need to recover when we're dealing 850 // with concrete integers specifically. 851 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 852 if (const Expr *E = dyn_cast_or_null<Expr>(S)) { 853 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext()); 854 } else { 855 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 856 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 857 Bldr.generateSink(Pred->getLocation().withTag(&T), 858 Pred->getState(), Pred); 859 return; 860 } 861 } 862 863 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 864 CallEventRef<CXXDestructorCall> Call = 865 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 866 867 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 868 Call->getSourceRange().getBegin(), 869 "Error evaluating destructor"); 870 871 ExplodedNodeSet DstPreCall; 872 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 873 *Call, *this); 874 875 ExplodedNodeSet DstInvalidated; 876 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 877 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 878 I != E; ++I) 879 defaultEvalCall(Bldr, *I, *Call, CallOpts); 880 881 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 882 *Call, *this); 883 } 884 885 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 886 ExplodedNode *Pred, 887 ExplodedNodeSet &Dst) { 888 ProgramStateRef State = Pred->getState(); 889 const LocationContext *LCtx = Pred->getLocationContext(); 890 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 891 CNE->getBeginLoc(), 892 "Error evaluating New Allocator Call"); 893 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 894 CallEventRef<CXXAllocatorCall> Call = 895 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 896 897 ExplodedNodeSet DstPreCall; 898 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 899 *Call, *this); 900 901 ExplodedNodeSet DstPostCall; 902 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx); 903 for (ExplodedNode *I : DstPreCall) { 904 // FIXME: Provide evalCall for checkers? 905 defaultEvalCall(CallBldr, I, *Call); 906 } 907 // If the call is inlined, DstPostCall will be empty and we bail out now. 908 909 // Store return value of operator new() for future use, until the actual 910 // CXXNewExpr gets processed. 911 ExplodedNodeSet DstPostValue; 912 StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx); 913 for (ExplodedNode *I : DstPostCall) { 914 // FIXME: Because CNE serves as the "call site" for the allocator (due to 915 // lack of a better expression in the AST), the conjured return value symbol 916 // is going to be of the same type (C++ object pointer type). Technically 917 // this is not correct because the operator new's prototype always says that 918 // it returns a 'void *'. So we should change the type of the symbol, 919 // and then evaluate the cast over the symbolic pointer from 'void *' to 920 // the object pointer type. But without changing the symbol's type it 921 // is breaking too much to evaluate the no-op symbolic cast over it, so we 922 // skip it for now. 923 ProgramStateRef State = I->getState(); 924 SVal RetVal = State->getSVal(CNE, LCtx); 925 926 // If this allocation function is not declared as non-throwing, failures 927 // /must/ be signalled by exceptions, and thus the return value will never 928 // be NULL. -fno-exceptions does not influence this semantics. 929 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 930 // where new can return NULL. If we end up supporting that option, we can 931 // consider adding a check for it here. 932 // C++11 [basic.stc.dynamic.allocation]p3. 933 if (const FunctionDecl *FD = CNE->getOperatorNew()) { 934 QualType Ty = FD->getType(); 935 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 936 if (!ProtoType->isNothrow()) 937 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true); 938 } 939 940 ValueBldr.generateNode( 941 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal)); 942 } 943 944 ExplodedNodeSet DstPostPostCallCallback; 945 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback, 946 DstPostValue, *Call, *this); 947 for (ExplodedNode *I : DstPostPostCallCallback) { 948 getCheckerManager().runCheckersForNewAllocator(*Call, Dst, I, *this); 949 } 950 } 951 952 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 953 ExplodedNodeSet &Dst) { 954 // FIXME: Much of this should eventually migrate to CXXAllocatorCall. 955 // Also, we need to decide how allocators actually work -- they're not 956 // really part of the CXXNewExpr because they happen BEFORE the 957 // CXXConstructExpr subexpression. See PR12014 for some discussion. 958 959 unsigned blockCount = currBldrCtx->blockCount(); 960 const LocationContext *LCtx = Pred->getLocationContext(); 961 SVal symVal = UnknownVal(); 962 FunctionDecl *FD = CNE->getOperatorNew(); 963 964 bool IsStandardGlobalOpNewFunction = 965 FD->isReplaceableGlobalAllocationFunction(); 966 967 ProgramStateRef State = Pred->getState(); 968 969 // Retrieve the stored operator new() return value. 970 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 971 symVal = *getObjectUnderConstruction(State, CNE, LCtx); 972 State = finishObjectConstruction(State, CNE, LCtx); 973 } 974 975 // We assume all standard global 'operator new' functions allocate memory in 976 // heap. We realize this is an approximation that might not correctly model 977 // a custom global allocator. 978 if (symVal.isUnknown()) { 979 if (IsStandardGlobalOpNewFunction) 980 symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount); 981 else 982 symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(), 983 blockCount); 984 } 985 986 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 987 CallEventRef<CXXAllocatorCall> Call = 988 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 989 990 if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 991 // Invalidate placement args. 992 // FIXME: Once we figure out how we want allocators to work, 993 // we should be using the usual pre-/(default-)eval-/post-call checkers 994 // here. 995 State = Call->invalidateRegions(blockCount); 996 if (!State) 997 return; 998 999 // If this allocation function is not declared as non-throwing, failures 1000 // /must/ be signalled by exceptions, and thus the return value will never 1001 // be NULL. -fno-exceptions does not influence this semantics. 1002 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 1003 // where new can return NULL. If we end up supporting that option, we can 1004 // consider adding a check for it here. 1005 // C++11 [basic.stc.dynamic.allocation]p3. 1006 if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>()) 1007 if (!ProtoType->isNothrow()) 1008 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>()) 1009 State = State->assume(*dSymVal, true); 1010 } 1011 1012 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1013 1014 SVal Result = symVal; 1015 1016 if (CNE->isArray()) { 1017 1018 if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) { 1019 // If each element is initialized by their default constructor, the field 1020 // values are properly placed inside the required region, however if an 1021 // initializer list is used, this doesn't happen automatically. 1022 auto *Init = CNE->getInitializer(); 1023 bool isInitList = isa_and_nonnull<InitListExpr>(Init); 1024 1025 QualType ObjTy = 1026 isInitList ? Init->getType() : CNE->getType()->getPointeeType(); 1027 const ElementRegion *EleReg = 1028 MRMgr.getElementRegion(ObjTy, svalBuilder.makeArrayIndex(0), NewReg, 1029 svalBuilder.getContext()); 1030 Result = loc::MemRegionVal(EleReg); 1031 1032 // If the array is list initialized, we bind the initializer list to the 1033 // memory region here, otherwise we would lose it. 1034 if (isInitList) { 1035 Bldr.takeNodes(Pred); 1036 Pred = Bldr.generateNode(CNE, Pred, State); 1037 1038 SVal V = State->getSVal(Init, LCtx); 1039 ExplodedNodeSet evaluated; 1040 evalBind(evaluated, CNE, Pred, Result, V, true); 1041 1042 Bldr.takeNodes(Pred); 1043 Bldr.addNodes(evaluated); 1044 1045 Pred = *evaluated.begin(); 1046 State = Pred->getState(); 1047 } 1048 } 1049 1050 State = State->BindExpr(CNE, Pred->getLocationContext(), Result); 1051 Bldr.generateNode(CNE, Pred, State); 1052 return; 1053 } 1054 1055 // FIXME: Once we have proper support for CXXConstructExprs inside 1056 // CXXNewExpr, we need to make sure that the constructed object is not 1057 // immediately invalidated here. (The placement call should happen before 1058 // the constructor call anyway.) 1059 if (FD->isReservedGlobalPlacementOperator()) { 1060 // Non-array placement new should always return the placement location. 1061 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx); 1062 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(), 1063 CNE->getPlacementArg(0)->getType()); 1064 } 1065 1066 // Bind the address of the object, then check to see if we cached out. 1067 State = State->BindExpr(CNE, LCtx, Result); 1068 ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State); 1069 if (!NewN) 1070 return; 1071 1072 // If the type is not a record, we won't have a CXXConstructExpr as an 1073 // initializer. Copy the value over. 1074 if (const Expr *Init = CNE->getInitializer()) { 1075 if (!isa<CXXConstructExpr>(Init)) { 1076 assert(Bldr.getResults().size() == 1); 1077 Bldr.takeNodes(NewN); 1078 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx), 1079 /*FirstInit=*/IsStandardGlobalOpNewFunction); 1080 } 1081 } 1082 } 1083 1084 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 1085 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 1086 1087 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 1088 CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall( 1089 CDE, Pred->getState(), Pred->getLocationContext()); 1090 1091 ExplodedNodeSet DstPreCall; 1092 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this); 1093 ExplodedNodeSet DstPostCall; 1094 1095 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 1096 StmtNodeBuilder Bldr(DstPreCall, DstPostCall, *currBldrCtx); 1097 for (ExplodedNode *I : DstPreCall) { 1098 defaultEvalCall(Bldr, I, *Call); 1099 } 1100 } else { 1101 DstPostCall = DstPreCall; 1102 } 1103 getCheckerManager().runCheckersForPostCall(Dst, DstPostCall, *Call, *this); 1104 } 1105 1106 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 1107 ExplodedNodeSet &Dst) { 1108 const VarDecl *VD = CS->getExceptionDecl(); 1109 if (!VD) { 1110 Dst.Add(Pred); 1111 return; 1112 } 1113 1114 const LocationContext *LCtx = Pred->getLocationContext(); 1115 SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(), 1116 currBldrCtx->blockCount()); 1117 ProgramStateRef state = Pred->getState(); 1118 state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx); 1119 1120 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1121 Bldr.generateNode(CS, Pred, state); 1122 } 1123 1124 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 1125 ExplodedNodeSet &Dst) { 1126 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 1127 1128 // Get the this object region from StoreManager. 1129 const LocationContext *LCtx = Pred->getLocationContext(); 1130 const MemRegion *R = 1131 svalBuilder.getRegionManager().getCXXThisRegion( 1132 getContext().getCanonicalType(TE->getType()), 1133 LCtx); 1134 1135 ProgramStateRef state = Pred->getState(); 1136 SVal V = state->getSVal(loc::MemRegionVal(R)); 1137 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V)); 1138 } 1139 1140 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 1141 ExplodedNodeSet &Dst) { 1142 const LocationContext *LocCtxt = Pred->getLocationContext(); 1143 1144 // Get the region of the lambda itself. 1145 const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion( 1146 LE, LocCtxt); 1147 SVal V = loc::MemRegionVal(R); 1148 1149 ProgramStateRef State = Pred->getState(); 1150 1151 // If we created a new MemRegion for the lambda, we should explicitly bind 1152 // the captures. 1153 unsigned Idx = 0; 1154 CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin(); 1155 for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(), 1156 e = LE->capture_init_end(); 1157 i != e; ++i, ++CurField, ++Idx) { 1158 FieldDecl *FieldForCapture = *CurField; 1159 SVal FieldLoc = State->getLValue(FieldForCapture, V); 1160 1161 SVal InitVal; 1162 if (!FieldForCapture->hasCapturedVLAType()) { 1163 const Expr *InitExpr = *i; 1164 1165 assert(InitExpr && "Capture missing initialization expression"); 1166 1167 // With C++17 copy elision the InitExpr can be anything, so instead of 1168 // pattern matching all cases, we simple check if the current field is 1169 // under construction or not, regardless what it's InitExpr is. 1170 if (const auto OUC = 1171 getObjectUnderConstruction(State, {LE, Idx}, LocCtxt)) { 1172 InitVal = State->getSVal(OUC->getAsRegion()); 1173 1174 State = finishObjectConstruction(State, {LE, Idx}, LocCtxt); 1175 } else 1176 InitVal = State->getSVal(InitExpr, LocCtxt); 1177 1178 } else { 1179 1180 assert(!getObjectUnderConstruction(State, {LE, Idx}, LocCtxt) && 1181 "VLA capture by value is a compile time error!"); 1182 1183 // The field stores the length of a captured variable-length array. 1184 // These captures don't have initialization expressions; instead we 1185 // get the length from the VLAType size expression. 1186 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr(); 1187 InitVal = State->getSVal(SizeExpr, LocCtxt); 1188 } 1189 1190 State = State->bindLoc(FieldLoc, InitVal, LocCtxt); 1191 } 1192 1193 // Decay the Loc into an RValue, because there might be a 1194 // MaterializeTemporaryExpr node above this one which expects the bound value 1195 // to be an RValue. 1196 SVal LambdaRVal = State->getSVal(R); 1197 1198 ExplodedNodeSet Tmp; 1199 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 1200 // FIXME: is this the right program point kind? 1201 Bldr.generateNode(LE, Pred, 1202 State->BindExpr(LE, LocCtxt, LambdaRVal), 1203 nullptr, ProgramPoint::PostLValueKind); 1204 1205 // FIXME: Move all post/pre visits to ::Visit(). 1206 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this); 1207 } 1208