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